@madarco/agentbox 0.31.3 → 0.32.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 +47 -0
- package/README.md +2 -0
- package/dist/_cloud-attach-6RKS3MAP.js +31 -0
- package/dist/{chunk-E2RPG54S.js → chunk-27S7QLDF.js} +3 -3
- package/dist/{chunk-EZPCCJPE.js → chunk-2APGFWEU.js} +24 -24
- package/dist/{chunk-7PDYVJ2Q.js → chunk-3AYSA62C.js} +3 -3
- package/dist/{chunk-SHFU2KSY.js → chunk-3ISG5THX.js} +3 -3
- package/dist/{chunk-D67Q5MNA.js → chunk-3L2DIPRM.js} +2 -2
- package/dist/{chunk-GYUOXSUX.js → chunk-4FOXMGJ7.js} +4 -4
- package/dist/{chunk-VIB2FMJJ.js → chunk-5OKDSI6M.js} +44 -44
- package/dist/{chunk-QWUZJCF5.js → chunk-66GAYIJZ.js} +3253 -937
- package/dist/chunk-66GAYIJZ.js.map +1 -0
- package/dist/{chunk-Q3BHXL47.js → chunk-6XMOBI5V.js} +4 -4
- package/dist/{chunk-VNXWOWQ7.js → chunk-7QTBRHB7.js} +4 -4
- package/dist/{chunk-UWKJ3HIA.js → chunk-ANSPBIYG.js} +4 -4
- package/dist/{chunk-7N3CJNR5.js → chunk-AWFTAHGF.js} +20 -7
- package/dist/chunk-AWFTAHGF.js.map +1 -0
- package/dist/{chunk-EHLPIWRR.js → chunk-AWI2TSWS.js} +2 -2
- package/dist/{chunk-GZHJVCBG.js → chunk-CDRKQ5BH.js} +9 -9
- package/dist/{chunk-W7P2HHFI.js → chunk-CXAWPWGZ.js} +6 -6
- package/dist/{chunk-V5IMDVV5.js → chunk-EDJ6O6CI.js} +6 -6
- package/dist/{chunk-PYPIECDD.js → chunk-GSMQL4IJ.js} +17 -17
- package/dist/chunk-GVNKIACA.js +223 -0
- package/dist/chunk-GVNKIACA.js.map +1 -0
- package/dist/{chunk-DKUSSE5G.js → chunk-JWQYZ6V4.js} +2 -2
- package/dist/{chunk-WMILLMJZ.js → chunk-KOTW7QQW.js} +5 -5
- package/dist/{chunk-XHCGVCSA.js → chunk-L4KBYI3I.js} +5 -5
- package/dist/{chunk-BMZOMC6X.js → chunk-M2DWTQRF.js} +3 -3
- package/dist/{chunk-XLFQXROC.js → chunk-MB2K74BI.js} +165 -3
- package/dist/chunk-MB2K74BI.js.map +1 -0
- package/dist/{chunk-MKZHCLFJ.js → chunk-MI3V2MAE.js} +4 -4
- package/dist/{chunk-ZMNLEZJB.js → chunk-MO3QJTVS.js} +7 -7
- package/dist/{chunk-MBFN2XNU.js → chunk-MPTE57BZ.js} +6 -6
- package/dist/{chunk-ZK6KD7ME.js → chunk-PE5LPD23.js} +68 -25
- package/dist/chunk-PE5LPD23.js.map +1 -0
- package/dist/{chunk-RNYH5465.js → chunk-QBVRWGXD.js} +3 -3
- package/dist/{chunk-VEO6ZYQY.js → chunk-RIXW4HSE.js} +6 -6
- package/dist/{chunk-QER5WHBC.js → chunk-S7LPQXR5.js} +6 -6
- package/dist/{chunk-JS5DLUUX.js → chunk-TAZYSVLT.js} +26 -22
- package/dist/{chunk-JS5DLUUX.js.map → chunk-TAZYSVLT.js.map} +1 -1
- package/dist/{chunk-QTMUJETE.js → chunk-TDPHZWJI.js} +4 -4
- package/dist/{chunk-M42UQWVO.js → chunk-WLEGSKKE.js} +4 -4
- package/dist/{chunk-UENVVGWE.js → chunk-WTOG3CC6.js} +4 -4
- package/dist/{chunk-QB7XVOYW.js → chunk-X6CO4WIX.js} +4 -4
- package/dist/{chunk-744IB5WM.js → chunk-XLJ4D4FI.js} +4 -4
- package/dist/{chunk-FVBEUPVM.js → chunk-XNZ6UHTM.js} +27 -5
- package/dist/chunk-XNZ6UHTM.js.map +1 -0
- package/dist/{chunk-SZTHLJ5J.js → chunk-XTNAIM7X.js} +6 -6
- package/dist/{chunk-S3SJIWSU.js → chunk-YNAJUTYC.js} +7 -7
- package/dist/{chunk-6GJDU3FN.js → chunk-YSACCMUB.js} +13 -13
- package/dist/{chunk-6RREIUAE.js → chunk-ZKOLV4ZN.js} +39 -4
- package/dist/chunk-ZKOLV4ZN.js.map +1 -0
- package/dist/{cli-JNOPYAUM.js → cli-IFXU5XNZ.js} +9 -9
- package/dist/{cli-I6TXLNRQ.js → cli-MZSWFSTW.js} +9 -9
- package/dist/{cli-VU2ALT6L.js → cli-O3WXOFNS.js} +8 -8
- package/dist/{cli-YYXO4WX5.js → cli-RQJUQJEP.js} +8 -8
- package/dist/{cli-W2WNV64V.js → cli-ZGYSHJP7.js} +9 -9
- package/dist/cloud-backends.js +5 -5
- package/dist/{control-plane-JUAINN2X.js → control-plane-3TII2JGM.js} +20 -20
- package/dist/{cp-hub-upload-VHU5TBHQ.js → cp-hub-upload-3W7Z4BMT.js} +7 -7
- package/dist/{custody-client-5OHF3SEX.js → custody-client-KYEZET6C.js} +5 -5
- package/dist/{deploy-hetzner-RTQW3B7P.js → deploy-hetzner-EO5PFKBG.js} +9 -9
- package/dist/{dist-H4FFY5TX.js → dist-3AR6L5MF.js} +8 -8
- package/dist/{dist-5HJBDLJP.js → dist-4GHNQ2AK.js} +8 -8
- package/dist/{dist-H72NQCKO.js → dist-BFH537FO.js} +9 -9
- package/dist/{dist-MBPDLQUR.js → dist-BUCKUE4V.js} +2 -2
- package/dist/{dist-64YIP2AZ.js → dist-ETGTZQUT.js} +256 -6
- package/dist/{dist-UGI5L7BN.js → dist-H2CSUDEI.js} +8 -8
- package/dist/{dist-7IANPBF4.js → dist-IABCQB5D.js} +8 -8
- package/dist/{dist-EDCGUXVI.js → dist-JJZ3NZRO.js} +10 -6
- package/dist/{dist-7RMVQOWJ.js → dist-RPBA2EL5.js} +8 -8
- package/dist/{dist-NJOKYHDI.js → dist-URWWHI3X.js} +9 -3
- package/dist/{dist-XWDFVTFR.js → dist-V224SH3Z.js} +7 -7
- package/dist/{host-reach-drainer-GTNLQWWM.js → host-reach-drainer-NYN3YXHG.js} +2 -2
- package/dist/host-session-YP5RKV6T.js +29 -0
- package/dist/hub-OWUC4IGW.js +39 -0
- package/dist/{hub-adopt-TVDMOZSP.js → hub-adopt-HYXFUPPO.js} +7 -7
- package/dist/{hub-api-client-RISAC6GB.js → hub-api-client-BI3E37CF.js} +4 -4
- package/dist/{hub-docker-target-QEALUMIZ.js → hub-docker-target-6ODSK7ZE.js} +14 -14
- package/dist/index.js +1224 -230
- package/dist/index.js.map +1 -1
- package/dist/{plugin-update-LG45ZFCU.js → plugin-update-LI3QDA4K.js} +5 -5
- package/dist/prepare-MYFNDJPP.js +45 -0
- package/dist/prepared-custody-WSHX6XTQ.js +39 -0
- package/dist/{prepared-state-FO74QUCP-SW3QMBW5.js → prepared-state-FO74QUCP-M4Q2X3KN.js} +4 -4
- package/dist/{publish-credentials-T7DDJVC4.js → publish-credentials-FCEQSIPE.js} +9 -9
- package/dist/{registry-UCFNYOAU.js → registry-GG23NEBF.js} +5 -5
- package/dist/relay-YUOIK3HN.js +22 -0
- package/dist/{remote-docker-share-SY7CWW5R.js → remote-docker-share-4Z4VVUPG.js} +11 -11
- package/dist/remote-docker-share-4Z4VVUPG.js.map +1 -0
- package/dist/{tool-grant-push-OJHLVAPZ.js → tool-grant-push-A2JYLJVF.js} +3 -3
- package/package.json +1 -1
- package/runtime/_shared/ctl.cjs +1046 -316
- package/runtime/digitalocean/ctl.cjs +1046 -316
- package/runtime/docker/packages/ctl/dist/bin.cjs +1046 -316
- package/runtime/e2b/ctl.cjs +1046 -316
- package/runtime/hetzner/ctl.cjs +1046 -316
- package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
- package/runtime/hub/apps/hub/.next/app-path-routes-manifest.json +24 -0
- package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
- package/runtime/hub/apps/hub/.next/routes-manifest.json +188 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/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.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js +4 -4
- 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.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/backup/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/backup/route.js.nft.json +1 -1
- 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]/clone/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/clone/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js +4 -4
- 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.nft.json +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.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.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/upload/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/upload/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/web/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js +4 -4
- 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.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/[...path]/route.js +3 -3
- 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.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.nft.json +1 -1
- 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.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route_client-reference-manifest.js +3 -0
- 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]/bots/route.js.nft.json +1 -1
- 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]/create-preflight/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/create-preflight/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/restore/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/restore/route.js.nft.json +1 -1
- 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.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/[id]/size-check/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/size-check/route.js.nft.json +1 -1
- 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.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route.js +10 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.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.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/web/route.js.nft.json +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)/custody/page_client-reference-manifest.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)/page_client-reference-manifest.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)/projects/[id]/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/system/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/system/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js +1 -1
- 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/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app-paths-manifest.json +24 -0
- package/runtime/hub/apps/hub/.next/server/chunks/00je_(dashboard)_api_v1_workspaces_[id]_tasks_[taskId]_assign_route_actions_1sufsej.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/00je_(dashboard)_api_v1_workspaces_[id]_tasks_[taskId]_done_route_actions_216dixx.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_managers_route_actions_1_vtgih.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_tasks_route_actions_1h8tg_m.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_managers_sessions_route_actions_16dksub.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_managers_start_route_actions_1g-vmis.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_tasks_[taskId]_route_actions_03oih6y.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_tasks_assign_route_actions_196zwo9.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_tasks_reorder_route_actions_1zkcfk-.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0ssw__next-internal_server_app_(dashboard)_api_v1_workspaces_route_actions_12a7_y8.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0web_next-internal_server_app_(dashboard)_api_v1_managers_[id]_route_actions_07cpyb_.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_attach_route_actions_0o-khw8.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_message_route_actions_0rjcqe5.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_notes_route_actions_1-mf4r_.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_resume_route_actions_0-cm1mu.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_stop_route_actions_16nrl1r.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_detect_route_actions_1sdbs-_.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_managers_route_actions_1sxymv0.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_rename_route_actions_0df5zi2.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_rescan_route_actions_1yra_w8.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_route_actions_1f56n_0.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_tasks_route_actions_1t-6quw.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_timeline_route_actions_0pbxblt.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1viy_api_v1_workspaces_[id]_tasks_[taskId]_unassign_route_actions_18a1p_r.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-c97gb._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0spnud2._.js → [root-of-the-server]__0-kl55b._.js} +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__074mxl5._.js → [root-of-the-server]__0-xlf9z._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__028ifqb._.js → [root-of-the-server]__0004tsz._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__00bupbc._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1cpr4qy._.js → [root-of-the-server]__0126167._.js} +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__01fy5q0._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__02c077x._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1ta1gr1._.js → [root-of-the-server]__02sueng._.js} +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0nndlre._.js → [root-of-the-server]__04-gm8c._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05uinnp._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__06wy8zz._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__071c-t4._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__08jg8w8._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09059m-._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__092y7_z._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09ti2-t._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09y4pdw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0_mog_h._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a689u5._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a8ere2._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0bzqrje._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c_r3oe._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cdoz9i._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cmu4sk._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cxjxz0._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d27tlu._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d3fx1z._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dm5oqm._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dy5g2k._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0e1uaxg._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0e6_t-d._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ets4cd._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f2u0ul._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f9p_4f._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f_jmq2._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0fksz_r._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0fpygqn._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0gym-rp._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0hhlb2_._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0i9phow._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ikyoac._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0j72bti._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jb371p._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jq6cdw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jt1d2s._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0kcw8t0._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0kdt9-i._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0l27vs0._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lc-j_n._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lna-vq._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0m5woxc._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0mi9xib._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0muy7eg._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nn0_b5._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0no30or._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0o3sjtx._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0onk5r0._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0pik2ie._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0qde3vr._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0qt_r6a._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ry8baf._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0sg4y_2._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0sgjn2j._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0st6oln._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0t0p64l._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0tbl11-._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ve_tqz._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0w4smfx._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0wo4sqj._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0wujjkl._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xbu3yj._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xl1-w6._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yct1tu._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yg67t0._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ykw5oe._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1c1rcl-._.js → [root-of-the-server]__0zznyx2._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1--u2xl._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-8sj4i._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10kmcrt._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10l_-cd._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10yfcvu._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__112hqrh._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11c-21i._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11qbpq8._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11s1mrd._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__128w1nz._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__12b2kuv._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__12gbq5m._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13nfpq5._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13vl4-h._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__153b7kv._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__157kmse._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16695dw._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__166_uek._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16o0ij7._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__175lucf._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__17p53e3._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__17y9pmx._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__18ec5_t._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__18xpvkc._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1925hyw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19ew1r2._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19grunx._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_4v0mh._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_cbcl1._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_wb2uh._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_xgm2e._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1an6-yb._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1c0ex8m._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1c1e08-._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1c9f4uu._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ci8hc2._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1cs6d52._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d60scp._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dicjoc._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1diipl4._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dp2exz._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1epnstn._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1fjnz2l._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1g5wnt2._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1g9v7bq._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1gon0_4._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h_59cs._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h_q3sn._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hlugb4._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hux-70._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1i-7bnu._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1i_el2y._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1j6clag._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1k6q17t._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1khvg39._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1lx9lyn._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1m36v6k._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mgu19x._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mhyrr5._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mk_lpu._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mt32fu._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1n1_2tw._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1na4sdw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ntihlm._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1odu62n._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1q6xrlt._.js +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1r4x1-y._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1rjs_x0._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1rxud0j._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1s5app0._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1sjz59l._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1slo4q_._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1thrazp._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1twtnwr._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1txvsbk._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1uch-60._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1um2jum._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1vnnuo1._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1wegvep._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1wi5roz._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1xa9oiv._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ypmy86._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1zml9me._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1zrf_a6._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__2019yzl._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20jyxyo._.js +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20ybhif._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20zl5fr._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__212dyoi._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__218oup-._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__21abvx9._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_0907rw0._.js +2 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0mcxq5g._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0vg6gvw._.js +41 -41
- 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/apps_hub_app_(dashboard)_api_v1_lib_validate_ts_16dhbzz._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/packages_agent-registry_dist_index_1ze3mqq.js +28 -19
- package/runtime/hub/apps/hub/.next/server/chunks/packages_relay_dist_control-plane_03a-9aj.js +6 -6
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__03-x9xy._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1jqga8h._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0r2xlss._.js +2 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_14-qzbg._.js +26 -26
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/packages_agent-registry_dist_index_0z476w4.js +26 -17
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/packages_relay_dist_control-plane_0ve-wz4.js +1 -1
- package/runtime/hub/apps/hub/.next/server/functions-config-manifest.json +24 -0
- package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
- package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
- package/runtime/hub/apps/hub/.next/static/chunks/{31e1wjin30i__.css → 03_fxfc3849ms.css} +1 -1
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/[id]/[action]/route.ts +4 -2
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.ts +6 -4
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/route.ts +2 -1
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/actor.ts +48 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/envelope.ts +5 -2
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/openapi.ts +1687 -52
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/validate.ts +527 -1
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/attach/route.ts +26 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/message/route.ts +34 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/notes/route.ts +26 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/resume/route.ts +26 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/route.ts +34 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/stop/route.ts +23 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/detect/route.ts +33 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/route.ts +27 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/tasks/route.ts +30 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/managers/route.ts +19 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.ts +22 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.ts +61 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/rename/route.ts +25 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.ts +20 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/route.ts +34 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.ts +33 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.ts +23 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.ts +54 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.ts +25 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.ts +34 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.ts +33 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.ts +59 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.ts +25 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/route.ts +31 -0
- package/runtime/hub/apps/hub/{chunk-FQY5OEWX.js → chunk-2LE76CT3.js} +19 -6
- package/runtime/hub/apps/hub/{chunk-MIETKCV4.js → chunk-BR4WVGWJ.js} +3 -3
- package/runtime/hub/apps/hub/{chunk-KTWFE5BB.js → chunk-EVB2OTLU.js} +3312 -1032
- package/runtime/hub/apps/hub/{chunk-IDL7RJBP.js → chunk-FBNAIUXZ.js} +38 -3
- package/runtime/hub/apps/hub/{chunk-ORTYCJ2U.js → chunk-G2AEPH7C.js} +4 -4
- package/runtime/hub/apps/hub/{chunk-VNLPJ45F.js → chunk-JX5JUFSR.js} +9 -9
- package/runtime/hub/apps/hub/{chunk-PM2365RW.js → chunk-MD2UNTZR.js} +6 -6
- package/runtime/hub/apps/hub/{dist-4DVVLHK2.js → dist-3LDUYWPK.js} +8 -2
- package/runtime/hub/apps/hub/{dist-RWN4Z57N.js → dist-CJ6QFUFV.js} +5 -5
- package/runtime/hub/apps/hub/{dist-FM26NQ4V.js → dist-D36FTGG6.js} +1 -1
- package/runtime/hub/apps/hub/{dist-VF56FSKH.js → dist-GGLWLMY6.js} +6 -6
- package/runtime/hub/apps/hub/{dist-WA2LO2DU.js → dist-HLLYJGIT.js} +6 -6
- package/runtime/hub/apps/hub/{dist-OAS6A7E4.js → dist-IIQU4I42.js} +5 -5
- package/runtime/hub/apps/hub/{dist-3IYYT3II.js → dist-UFMCOK3W.js} +5 -5
- package/runtime/hub/apps/hub/{dist-LMXU56B2.js → dist-XUNBQ4WM.js} +5 -5
- package/runtime/hub/apps/hub/{dist-LOZYEDXA.js → dist-Y2263LMY.js} +8 -4
- package/runtime/hub/apps/hub/{dist-UPKSCLZ2.js → dist-YV4M6NJO.js} +5 -5
- package/runtime/hub/apps/hub/{hub-worker-6JAWRLP2.js → hub-worker-LJYEEAJL.js} +7 -7
- package/runtime/hub/apps/hub/lib/backend/background.ts +19 -0
- package/runtime/hub/apps/hub/lib/backend/box-facts.ts +97 -0
- package/runtime/hub/apps/hub/lib/backend/box-prs.ts +213 -0
- package/runtime/hub/apps/hub/lib/backend/deps.ts +99 -0
- package/runtime/hub/apps/hub/lib/backend/errors.ts +7 -0
- package/runtime/hub/apps/hub/lib/backend/github-prs.ts +302 -0
- package/runtime/hub/apps/hub/lib/backend/managers.ts +748 -0
- package/runtime/hub/apps/hub/lib/backend/timeline-lanes.ts +150 -0
- package/runtime/hub/apps/hub/lib/backend/timeline.ts +611 -0
- package/runtime/hub/apps/hub/lib/backend/workspaces.ts +439 -0
- package/runtime/hub/apps/hub/lib/boxes/backend-types.ts +355 -10
- package/runtime/hub/apps/hub/lib/boxes/postgres-source.ts +3 -0
- package/runtime/hub/apps/hub/lib/boxes/source.ts +18 -1
- package/runtime/hub/apps/hub/lib/boxes/types.ts +66 -0
- package/runtime/hub/apps/hub/lib/hub-backend.ts +114 -7
- package/runtime/hub/apps/hub/{prepared-state-FO74QUCP-QR6ZNI3Q.js → prepared-state-FO74QUCP-75UBPW5I.js} +3 -3
- package/runtime/hub/apps/hub/server.js +2033 -164
- package/runtime/hub/apps/hub/test/backend-managers-background.test.ts +336 -0
- package/runtime/hub/apps/hub/test/backend-managers.test.ts +493 -0
- package/runtime/hub/apps/hub/test/backend-workspaces.test.ts +208 -0
- package/runtime/hub/apps/hub/test/box-prs.test.ts +198 -0
- package/runtime/hub/apps/hub/test/timeline-lanes.test.ts +261 -0
- package/runtime/hub/apps/hub/test/timeline.test.ts +1185 -0
- package/runtime/hub/apps/hub/test/validate.test.ts +252 -0
- package/runtime/hub/apps/hub/tsconfig.tsbuildinfo +1 -1
- package/runtime/relay/bin.cjs +1419 -623
- package/runtime/vercel/ctl.cjs +1046 -316
- package/share/host-skills/agentbox-info/SKILL.md +25 -4
- package/dist/_cloud-attach-QB72ZV7T.js +0 -31
- package/dist/chunk-6RREIUAE.js.map +0 -1
- package/dist/chunk-7N3CJNR5.js.map +0 -1
- package/dist/chunk-FVBEUPVM.js.map +0 -1
- package/dist/chunk-QWUZJCF5.js.map +0 -1
- package/dist/chunk-XLFQXROC.js.map +0 -1
- package/dist/chunk-ZK6KD7ME.js.map +0 -1
- package/dist/hub-C5B3CRP6.js +0 -39
- package/dist/prepare-6JLTXX65.js +0 -45
- package/dist/prepared-custody-YVVTL2ZM.js +0 -39
- package/dist/relay-W73AIA35.js +0 -22
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__00o_3sf._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__08xwxyo._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-mtsr6._.js +0 -3
- /package/dist/{_cloud-attach-QB72ZV7T.js.map → _cloud-attach-6RKS3MAP.js.map} +0 -0
- /package/dist/{chunk-E2RPG54S.js.map → chunk-27S7QLDF.js.map} +0 -0
- /package/dist/{chunk-EZPCCJPE.js.map → chunk-2APGFWEU.js.map} +0 -0
- /package/dist/{chunk-7PDYVJ2Q.js.map → chunk-3AYSA62C.js.map} +0 -0
- /package/dist/{chunk-SHFU2KSY.js.map → chunk-3ISG5THX.js.map} +0 -0
- /package/dist/{chunk-D67Q5MNA.js.map → chunk-3L2DIPRM.js.map} +0 -0
- /package/dist/{chunk-GYUOXSUX.js.map → chunk-4FOXMGJ7.js.map} +0 -0
- /package/dist/{chunk-VIB2FMJJ.js.map → chunk-5OKDSI6M.js.map} +0 -0
- /package/dist/{chunk-Q3BHXL47.js.map → chunk-6XMOBI5V.js.map} +0 -0
- /package/dist/{chunk-VNXWOWQ7.js.map → chunk-7QTBRHB7.js.map} +0 -0
- /package/dist/{chunk-UWKJ3HIA.js.map → chunk-ANSPBIYG.js.map} +0 -0
- /package/dist/{chunk-EHLPIWRR.js.map → chunk-AWI2TSWS.js.map} +0 -0
- /package/dist/{chunk-GZHJVCBG.js.map → chunk-CDRKQ5BH.js.map} +0 -0
- /package/dist/{chunk-W7P2HHFI.js.map → chunk-CXAWPWGZ.js.map} +0 -0
- /package/dist/{chunk-V5IMDVV5.js.map → chunk-EDJ6O6CI.js.map} +0 -0
- /package/dist/{chunk-PYPIECDD.js.map → chunk-GSMQL4IJ.js.map} +0 -0
- /package/dist/{chunk-DKUSSE5G.js.map → chunk-JWQYZ6V4.js.map} +0 -0
- /package/dist/{chunk-WMILLMJZ.js.map → chunk-KOTW7QQW.js.map} +0 -0
- /package/dist/{chunk-XHCGVCSA.js.map → chunk-L4KBYI3I.js.map} +0 -0
- /package/dist/{chunk-BMZOMC6X.js.map → chunk-M2DWTQRF.js.map} +0 -0
- /package/dist/{chunk-MKZHCLFJ.js.map → chunk-MI3V2MAE.js.map} +0 -0
- /package/dist/{chunk-ZMNLEZJB.js.map → chunk-MO3QJTVS.js.map} +0 -0
- /package/dist/{chunk-MBFN2XNU.js.map → chunk-MPTE57BZ.js.map} +0 -0
- /package/dist/{chunk-RNYH5465.js.map → chunk-QBVRWGXD.js.map} +0 -0
- /package/dist/{chunk-VEO6ZYQY.js.map → chunk-RIXW4HSE.js.map} +0 -0
- /package/dist/{chunk-QER5WHBC.js.map → chunk-S7LPQXR5.js.map} +0 -0
- /package/dist/{chunk-QTMUJETE.js.map → chunk-TDPHZWJI.js.map} +0 -0
- /package/dist/{chunk-M42UQWVO.js.map → chunk-WLEGSKKE.js.map} +0 -0
- /package/dist/{chunk-UENVVGWE.js.map → chunk-WTOG3CC6.js.map} +0 -0
- /package/dist/{chunk-QB7XVOYW.js.map → chunk-X6CO4WIX.js.map} +0 -0
- /package/dist/{chunk-744IB5WM.js.map → chunk-XLJ4D4FI.js.map} +0 -0
- /package/dist/{chunk-SZTHLJ5J.js.map → chunk-XTNAIM7X.js.map} +0 -0
- /package/dist/{chunk-S3SJIWSU.js.map → chunk-YNAJUTYC.js.map} +0 -0
- /package/dist/{chunk-6GJDU3FN.js.map → chunk-YSACCMUB.js.map} +0 -0
- /package/dist/{cli-I6TXLNRQ.js.map → cli-IFXU5XNZ.js.map} +0 -0
- /package/dist/{cli-JNOPYAUM.js.map → cli-MZSWFSTW.js.map} +0 -0
- /package/dist/{cli-VU2ALT6L.js.map → cli-O3WXOFNS.js.map} +0 -0
- /package/dist/{cli-W2WNV64V.js.map → cli-RQJUQJEP.js.map} +0 -0
- /package/dist/{cli-YYXO4WX5.js.map → cli-ZGYSHJP7.js.map} +0 -0
- /package/dist/{control-plane-JUAINN2X.js.map → control-plane-3TII2JGM.js.map} +0 -0
- /package/dist/{cp-hub-upload-VHU5TBHQ.js.map → cp-hub-upload-3W7Z4BMT.js.map} +0 -0
- /package/dist/{custody-client-5OHF3SEX.js.map → custody-client-KYEZET6C.js.map} +0 -0
- /package/dist/{deploy-hetzner-RTQW3B7P.js.map → deploy-hetzner-EO5PFKBG.js.map} +0 -0
- /package/dist/{dist-64YIP2AZ.js.map → dist-3AR6L5MF.js.map} +0 -0
- /package/dist/{dist-5HJBDLJP.js.map → dist-4GHNQ2AK.js.map} +0 -0
- /package/dist/{dist-7IANPBF4.js.map → dist-BFH537FO.js.map} +0 -0
- /package/dist/{dist-EDCGUXVI.js.map → dist-BUCKUE4V.js.map} +0 -0
- /package/dist/{dist-H4FFY5TX.js.map → dist-ETGTZQUT.js.map} +0 -0
- /package/dist/{dist-H72NQCKO.js.map → dist-H2CSUDEI.js.map} +0 -0
- /package/dist/{dist-MBPDLQUR.js.map → dist-IABCQB5D.js.map} +0 -0
- /package/dist/{dist-NJOKYHDI.js.map → dist-JJZ3NZRO.js.map} +0 -0
- /package/dist/{dist-7RMVQOWJ.js.map → dist-RPBA2EL5.js.map} +0 -0
- /package/dist/{dist-UGI5L7BN.js.map → dist-URWWHI3X.js.map} +0 -0
- /package/dist/{dist-XWDFVTFR.js.map → dist-V224SH3Z.js.map} +0 -0
- /package/dist/{host-reach-drainer-GTNLQWWM.js.map → host-reach-drainer-NYN3YXHG.js.map} +0 -0
- /package/dist/{hub-C5B3CRP6.js.map → host-session-YP5RKV6T.js.map} +0 -0
- /package/dist/{hub-adopt-TVDMOZSP.js.map → hub-OWUC4IGW.js.map} +0 -0
- /package/dist/{hub-api-client-RISAC6GB.js.map → hub-adopt-HYXFUPPO.js.map} +0 -0
- /package/dist/{prepare-6JLTXX65.js.map → hub-api-client-BI3E37CF.js.map} +0 -0
- /package/dist/{hub-docker-target-QEALUMIZ.js.map → hub-docker-target-6ODSK7ZE.js.map} +0 -0
- /package/dist/{plugin-update-LG45ZFCU.js.map → plugin-update-LI3QDA4K.js.map} +0 -0
- /package/dist/{prepared-custody-YVVTL2ZM.js.map → prepare-MYFNDJPP.js.map} +0 -0
- /package/dist/{prepared-state-FO74QUCP-SW3QMBW5.js.map → prepared-custody-WSHX6XTQ.js.map} +0 -0
- /package/dist/{registry-UCFNYOAU.js.map → prepared-state-FO74QUCP-M4Q2X3KN.js.map} +0 -0
- /package/dist/{publish-credentials-T7DDJVC4.js.map → publish-credentials-FCEQSIPE.js.map} +0 -0
- /package/dist/{relay-W73AIA35.js.map → registry-GG23NEBF.js.map} +0 -0
- /package/dist/{remote-docker-share-SY7CWW5R.js.map → relay-YUOIK3HN.js.map} +0 -0
- /package/dist/{tool-grant-push-OJHLVAPZ.js.map → tool-grant-push-A2JYLJVF.js.map} +0 -0
- /package/runtime/hub/apps/hub/.next/static/{kg0mtyaaNMvU3P8p7nLPa → QDhlg7V_fEVGv_NfM2cEJ}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{kg0mtyaaNMvU3P8p7nLPa → QDhlg7V_fEVGv_NfM2cEJ}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{kg0mtyaaNMvU3P8p7nLPa → QDhlg7V_fEVGv_NfM2cEJ}/_ssgManifest.js +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../packages/sandbox-docker/src/sync/agents/module.ts","../../../packages/sandbox-docker/src/sync/agents/shared.ts","../../../packages/sandbox-docker/src/docker-provider.ts","../../../packages/sandbox-docker/src/sync/docker-sync.ts","../../../packages/sandbox-docker/src/sync/agents/seed.ts","../../../packages/sandbox-docker/src/sync/claude-credentials.ts","../../../packages/sandbox-docker/src/state.ts","../../../packages/sandbox-docker/src/sync/agents/skills.ts","../../../packages/sandbox-docker/src/docker.ts","../../../packages/sandbox-docker/src/sync/sync-transport.ts","../../../packages/sandbox-docker/src/sync/host-export.ts","../../../packages/sandbox-docker/src/box-cp.ts","../../../packages/sandbox-docker/src/sync/in-box-git.ts","../../../packages/sandbox-docker/src/git-worktree.ts","../../../packages/sandbox-docker/src/create.ts","../../../packages/sandbox-docker/src/direct-web-url.ts","../../../packages/sandbox-docker/src/dockerd.ts","../../../packages/sandbox-docker/src/vnc.ts","../../../packages/sandbox-docker/src/ssh.ts","../../../packages/sandbox-docker/src/web.ts","../../../packages/sandbox-docker/src/portless.ts","../../../packages/sandbox-docker/src/snapshot.ts","../../../packages/sandbox-docker/src/checkpoint.ts","../../../packages/sandbox-docker/src/ctl.ts","../../../packages/sandbox-docker/src/box-env.ts","../../../packages/sandbox-docker/src/agent-isolation.ts","../../../packages/sandbox-docker/src/home-ownership.ts","../../../packages/sandbox-docker/src/relay.ts","../../../packages/sandbox-docker/src/vscode.ts","../../../packages/sandbox-docker/src/lifecycle.ts","../../../packages/sandbox-docker/src/shell-session.ts","../../../packages/sandbox-docker/src/endpoints.ts","../../../packages/sandbox-docker/src/stats.ts","../../../packages/sandbox-docker/src/provider-module.ts","../../../packages/sandbox-docker/src/sync/settings-propagate.ts","../../../packages/sandbox-docker/src/hub-portless.ts","../../../packages/sandbox-docker/src/credential-refresh.ts","../../../packages/sandbox-docker/src/index.ts","../../../packages/sandbox-docker/src/sync/dynamic-sync.ts","../../../packages/sandbox-docker/src/browser.ts","../../../packages/ctl/src/types.ts","../../../packages/ctl/src/client.ts","../../../packages/ctl/src/render.ts","../../../packages/ctl/src/config.ts","../../../packages/ctl/src/replace.ts","../../../packages/ctl/src/carry.ts","../../../packages/ctl/src/agent-units.ts","../../../packages/ctl/src/overlay-diff.ts","../../../packages/ctl/src/relay-rpc.ts","../../../packages/ctl/src/relay-env.ts","../../../packages/ctl/src/tool-links.ts","../../../packages/ctl/src/tool-links-watcher.ts","../../../packages/ctl/src/tools-spec.ts"],"sourcesContent":["/**\n * What this package needs from an agent, as ONE interface it RECEIVES rather\n * than three modules it imports.\n *\n * `sandbox-docker` used to import `claude.ts`, `codex.ts` and `opencode.ts`\n * directly, which is why a fourth agent could not be added without editing this\n * package. It cannot import them once each agent is its own package either: an\n * agent's behavior depends on `sandbox-docker`, so importing it back is the\n * dependency cycle turbo already refused (see `agent-registry`).\n *\n * So the direction inverts. Agents REGISTER; this package looks them up. Same\n * shape `check-cloud-backend-wiring.mjs` already guards for cloud backends,\n * where the relay is handed a loader rather than importing providers.\n *\n * The method set is not invented — it is exactly what a grep of this package's\n * imports showed it actually uses, with the three names per concept collapsed to\n * one.\n */\n\nimport type { AgentId } from '@agentbox/core';\n\n/** A live tmux session probe. The three agents' versions were byte-identical. */\nexport interface AgentSessionInfo {\n running: boolean;\n sessionName: string;\n /** ISO-8601 from tmux's `#{session_created}`, or null when not running. */\n startedAt: string | null;\n}\n\n/** Which config volume a box uses for one agent. */\nexport interface AgentVolumeChoice {\n /** Resolved docker volume name mounted at the agent's box config dir. */\n volume: string;\n}\n\n/**\n * What an agent contributes to `docker run`. The three agents' mount results\n * were already identical field-for-field.\n */\nexport interface AgentMountResult {\n /** `-v` spec strings appended to `runBox(extraVolumes)`. */\n extraVolumes: string[];\n /** Env forwarded into the container; only host keys that were set + non-empty. */\n env: Record<string, string>;\n volumeName: string;\n}\n\n/**\n * Outcome of seeding an agent's volume.\n *\n * `created`/`synced` are common to all three. Claude reports more (dropped host\n * hooks, trust/alias writes) and keeps doing so through `notes`, rather than\n * widening this shape with fields only one agent can populate — the mistake the\n * per-agent result types made.\n */\nexport interface EnsureAgentVolumeResult {\n /** True only the very first time the volume is created on this host. */\n created: boolean;\n /** True when the host→volume sync actually ran. */\n synced: boolean;\n /** Human-readable lines the create log prints verbatim. */\n notes?: string[];\n}\n\n/** One agent's docker-side behavior. */\nexport interface AgentSyncModule {\n readonly id: AgentId;\n\n /** Pick the config volume: the shared one, or a per-box volume when isolated. */\n resolveVolume(opts: { isolate: boolean; boxId: string }): AgentVolumeChoice;\n\n /** Mounts + env this agent contributes to `docker run`. */\n buildMounts(spec: AgentVolumeChoice, hostEnv: NodeJS.ProcessEnv): AgentMountResult;\n\n /**\n * Create the volume if absent and seed it from the host config.\n *\n * `hostWorkspace` is passed because an agent may need to rewrite host-scoped\n * state as it syncs — claude aliases its `projects[<hostWorkspace>]` key to\n * `/workspace` so the in-box session sees the host's project state. Optional:\n * an agent that does not care simply ignores it.\n */\n ensureVolume(\n spec: AgentVolumeChoice,\n opts: { syncFromHost: boolean; image: string; hostWorkspace?: string },\n ): Promise<EnsureAgentVolumeResult>;\n\n /** Probe the agent's tmux session in a running box. */\n sessionInfo(container: string): Promise<AgentSessionInfo>;\n\n /**\n * Anything the agent needs done to its volume AFTER the sync. Absorbs what\n * were per-agent one-offs called by name from `docker-sync.ts` — codex's\n * `AGENTS.override.md` box-facts fold is the first.\n */\n afterVolumeSync?(volume: string, image: string): Promise<{ notes: string[] }>;\n\n /**\n * Refresh a credential that expires on its own, before a box starts.\n * Claude-only today; optional because most agents' tokens do not expire.\n *\n * `attempts` and `onProgress` are here because renewing is a real, slow,\n * fallible operation the host reports on as it goes — not a fire-and-forget.\n */\n warmUpCredentials?(\n volume: string,\n image: string,\n opts?: { attempts?: number; onProgress?: (line: string) => void },\n ): Promise<{ warmed: boolean; notes: string[] }>;\n\n /**\n * Bring this agent's HOST credential backup up to date from its docker volume,\n * before a box starts.\n *\n * `dockerCredentialRefresh` used to do this for three agents by name — a\n * claude sync gated on claude's token expiry, then a codex extract, then an\n * opencode extract. A fourth agent got no refresh at all, silently, which is\n * the same gap `assert-creds` and the cloud volume table each had.\n *\n * Optional, and best-effort by contract: the caller swallows throws, so an\n * agent with nothing to refresh omits it and one whose docker volume is\n * missing simply reports no change.\n */\n refreshHostBackup?(image: string, log: (line: string) => void): Promise<void>;\n}\n\n/**\n * The registered agents.\n *\n * Populated by whoever assembles the app — the CLI at startup, a test in its\n * setup. This package never fills it in, which is the point.\n */\nconst MODULES = new Map<AgentId, AgentSyncModule>();\n\n/** Register (or replace) one agent's docker behavior. */\nexport function registerAgentSyncModule(mod: AgentSyncModule): void {\n MODULES.set(mod.id, mod);\n}\n\n/** Every registered agent, in registration order. */\nexport function registeredAgentSyncModules(): AgentSyncModule[] {\n return [...MODULES.values()];\n}\n\n/**\n * One agent's module, or undefined when it has none.\n *\n * Deliberately NOT throwing: a box may legitimately reference an agent this\n * build has no docker behavior for (a registry row added ahead of its package,\n * or a cloud-only agent). Callers skip; they must not crash a create.\n */\nexport function agentSyncModule(id: AgentId): AgentSyncModule | undefined {\n return MODULES.get(id);\n}\n\n/**\n * The module for `id`, or a thrown error naming it.\n *\n * For call sites that cannot proceed without it. The throw is the point: an\n * unpopulated registry otherwise reads as \"this box has no agents\", which is a\n * silent wrong answer rather than a failure.\n */\nexport function requireAgentSyncModule(id: AgentId): AgentSyncModule {\n const mod = MODULES.get(id);\n if (!mod) {\n throw new Error(\n `no docker sync module registered for agent '${id}' — ` +\n `the app must register it before creating or inspecting a box`,\n );\n }\n return mod;\n}\n","/**\n * Box plumbing every agent shares — the tmux session shape, the TERM guard, and\n * the container user.\n *\n * These lived in `claude.ts` and were imported from there by `codex.ts`,\n * `opencode.ts`, `seed.ts` and `shell-session.ts`, which made Claude the de\n * facto shared module: nothing here is Claude-specific, and `buildShellArgv`\n * backs `agentbox shell`, which has no agent at all. That was harmless while the\n * three agents were siblings in one package; it stops being harmless the moment\n * each agent becomes its own package, because every one of them would then\n * depend on `@agentbox/agent-claude` for a tmux flag.\n */\n\n/** The unprivileged user a box's work runs as. */\nexport const CONTAINER_USER = 'vscode';\n\n/**\n * Shell snippet (run via `sh -c`) that guarantees TERM resolves inside the box\n * before tmux starts. The box runs Ubuntu, whose terminfo database does not\n * carry every host terminal: notably `xterm-ghostty`, which was added to\n * ncurses after 24.04 shipped. Forwarding such a TERM makes `tmux attach` exit\n * immediately with \"missing or unsuitable terminal\", which looks like a brief\n * flash and an instant exit. When the box cannot resolve $TERM, fall back to\n * xterm-256color, which the image always provides.\n */\nexport const TERM_FALLBACK_SNIPPET =\n 'if ! infocmp \"$TERM\" >/dev/null 2>&1; then TERM=xterm-256color; export TERM; fi; ';\n\n/**\n * Build the `docker exec` argv that runs an in-box tmux command under `sh -c`\n * with the TERM guard ({@link TERM_FALLBACK_SNIPPET}) applied first.\n *\n * `tmuxScript` is the tmux command line as it should reach tmux (use `\\;` for\n * tmux's own command separator, since a shell now parses it). `positionals` are\n * bound to \"$1\", \"$2\", ... inside the script, so session names are passed as\n * args rather than interpolated, keeping names with odd characters safe. The\n * host's TERM is still forwarded via `-e`, so a box that does know it keeps full\n * fidelity; the guard only downgrades the unknown case.\n */\nexport function buildTermSafeTmuxExec(opts: {\n container: string;\n user: string;\n tmuxScript: string;\n positionals: string[];\n}): string[] {\n const term = process.env['TERM'] ?? 'xterm-256color';\n return [\n 'exec',\n '-it',\n '-e',\n `TERM=${term}`,\n '--user',\n opts.user,\n opts.container,\n 'sh',\n '-c',\n `${TERM_FALLBACK_SNIPPET}${opts.tmuxScript}`,\n 'sh',\n ...opts.positionals,\n ];\n}\n\n/**\n * The list of tmux subcommands that configure a session: remap the prefix\n * (Ctrl+a primary, Ctrl+b kept as secondary), enable CSI-u extended-key\n * reporting so Claude Code can distinguish Shift+Enter from Enter, and turn\n * the inner tmux status bar off so it doesn't double up with the outer\n * wrapped-pty footer. Single source of truth shared by the docker path\n * (via {@link buildTmuxSessionArgs}, which folds these into execa argv with\n * `;` separators) and the cloud path (via\n * {@link buildTmuxConfigShellSnippet}, which formats them as `tmux …`\n * shell statements for SSH transport).\n *\n * `prefix`/`bind-key` are server-global (no `-t`) — fine because each box\n * runs one tmux server per session role. `status off` is session-scoped\n * with `-t <session>` so the dashboard's grouped sibling session\n * (`<name>-dash`) keeps its own option scope.\n */\nfunction tmuxConfigSubcommands(sessionName: string): readonly (readonly string[])[] {\n return [\n ['set', '-g', 'prefix', 'C-a'],\n ['set', '-g', 'prefix2', 'C-b'],\n ['bind-key', 'C-a', 'send-prefix'],\n ['bind-key', 'C-b', 'send-prefix', '-2'],\n ['bind-key', 'd', 'detach-client'],\n ['set', '-g', 'extended-keys', 'on'],\n ['set', '-as', 'terminal-features', ',*:extkeys'],\n ['set', '-t', sessionName, 'status', 'off'],\n ];\n}\n\n/**\n * tmux command-list (separator-prefixed) appended after `tmux new-session …`\n * in {@link startClaudeSession}. The bare `;` elements are tmux's command\n * separator (execa array args, no host shell, so they reach tmux verbatim).\n * See {@link tmuxConfigSubcommands} for the shared subcommand definitions\n * and why each setting is set the way it is.\n */\nexport function buildTmuxSessionArgs(sessionName: string): string[] {\n const out: string[] = [];\n for (const sub of tmuxConfigSubcommands(sessionName)) {\n out.push(';', ...sub);\n }\n return out;\n}\n\n/**\n * Same tmux configuration as {@link buildTmuxSessionArgs}, formatted as a\n * shell snippet (`tmux <args>; tmux <args>; …`) suitable for transports\n * that go through a remote shell — i.e. the cloud providers' `ssh -t`\n * attach in `@agentbox/sandbox-cloud`'s `renderInnerCommand`. The docker\n * path uses execa argv directly and doesn't need this.\n *\n * Each subcommand is its own `tmux` invocation joined with `; ` (shell\n * statement separator), because the in-tmux `;` separator can't pass\n * through `ssh -t '...'` without ambiguity — single-quoted shell args\n * forward `;` to the remote shell, where it would split the command line\n * before reaching tmux. Multiple `tmux` invocations are equivalent\n * (they're all idempotent `set`/`bind-key` operations) and re-applying\n * on every reattach is harmless.\n */\nexport function buildTmuxConfigShellSnippet(sessionName: string): string {\n return tmuxConfigSubcommands(sessionName)\n .map((sub) => `tmux ${sub.map(shellSingleQuoteIfNeeded).join(' ')}`)\n .join('; ');\n}\n\n/**\n * Wrap `s` in POSIX single quotes only if it contains characters that\n * shells (sh/bash/zsh) parse specially. Tmux args like `,*:extkeys` need\n * quoting (the `*` would glob); plain identifiers like `C-a` or `prefix`\n * don't. Keeping the unquoted form when safe makes the generated SSH\n * command easier to read in logs.\n */\nfunction shellSingleQuoteIfNeeded(s: string): string {\n return /^[A-Za-z0-9_:.\\/=+-]+$/.test(s) ? s : \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n\n/**\n * The `docker` argv for an interactive login shell in a box — the same shape\n * `agentbox shell` uses (vscode user, image WORKDIR `/workspace`, `bash -l`).\n * Handed to node-pty by the dashboard's \"open a shell\" action.\n */\nexport function buildShellArgv(container: string): string[] {\n const term = process.env['TERM'] ?? 'xterm-256color';\n return ['exec', '-it', '-e', `TERM=${term}`, '--user', CONTAINER_USER, container, 'bash', '-l'];\n}\n","/**\n * `DockerProvider` — the local-Docker implementation of the provider-neutral\n * `Provider` interface. A thin adapter: every method delegates to the existing\n * `createBox` / lifecycle / docker / stats functions. The CLI resolves this via\n * the provider registry for any box whose `provider` is `'docker'`.\n */\n\nimport type {\n BoxRecord,\n BoxResourceStats,\n BoxRuntimeState,\n CreateBoxRequest,\n CreatedBox,\n ExecOptions,\n ExecResult,\n InspectedBox,\n PrepareOptions,\n PrepareResult,\n Provider,\n ProviderSync,\n ResyncResult,\n SyncTransport,\n} from '@agentbox/core';\nimport { makeSyncContext } from '@agentbox/sandbox-core';\nimport { makeDockerSync } from './sync/docker-sync.js';\nimport { createDockerSyncTransport } from './sync/sync-transport.js';\nimport { createBox, type CreateBoxOptions } from './create.js';\nimport { destroyBox, inspectBox, pauseBox, startBox, stopBox, unpauseBox } from './lifecycle.js';\nimport { execInBox, inspectContainerStatus } from './docker.js';\nimport { boxResourceStats } from './stats.js';\nimport { detectEngine } from './sync/host-export.js';\nimport { portlessGetUrl } from './portless.js';\nimport { DEFAULT_BOX_IMAGE, imageExists, pullOrBuild } from './image.js';\nimport {\n computeDockerContextFingerprint,\n preparedMatches,\n readPreparedDockerState,\n} from './prepared-state.js';\nimport { downloadFromBox, uploadToBox } from './box-cp.js';\n\n/**\n * Docker-specific knobs the CLI passes through `CreateBoxRequest.providerOptions`.\n * Kept out of the provider-neutral `CreateBoxRequest` so cloud backends don't\n * carry Docker concepts.\n */\nexport interface DockerCreateOptions {\n useSnapshot?: boolean;\n sharedCache?: boolean;\n portless?: boolean;\n portlessStateDir?: string;\n claudeConfig?: { isolate: boolean };\n codexConfig?: { isolate: boolean };\n opencodeConfig?: { isolate: boolean };\n /** Per-agent config-volume options for agents outside the named three. */\n agentConfig?: Record<string, { isolate?: boolean }>;\n claudeEnv?: Record<string, string>;\n}\n\nexport const dockerProvider: Provider = {\n name: 'docker',\n\n async create(req: CreateBoxRequest): Promise<CreatedBox> {\n const po = (req.providerOptions ?? {}) as DockerCreateOptions;\n const opts: CreateBoxOptions = {\n workspacePath: req.workspacePath,\n name: req.name,\n nameBasis: req.nameBasis,\n useSnapshot: po.useSnapshot ?? false,\n checkpointRef: req.checkpointRef,\n fromBranch: req.fromBranch,\n useBranch: req.useBranch,\n resyncOnStart: req.resyncOnStart,\n image: req.image,\n allowPull: req.allowPull,\n imageRegistry: req.imageRegistry,\n onLog: req.onLog,\n // The CLI's docker paths call `createBox` directly with a literal, but a\n // hub / control-plane create only ever arrives as a CreateBoxRequest —\n // so without this those boxes silently keep the all-agents behaviour.\n ...(req.agents ? { agents: req.agents } : {}),\n ...(req.borrowCredentials ? { borrowCredentials: req.borrowCredentials } : {}),\n claudeConfig: po.claudeConfig,\n claudeEnv: po.claudeEnv,\n codexConfig: po.codexConfig,\n opencodeConfig: po.opencodeConfig,\n agentConfig: po.agentConfig,\n withPlaywright: req.withPlaywright,\n withEnv: req.withEnv,\n envFilesToImport: req.envFilesToImport,\n carry: req.carry,\n vnc: req.vnc,\n // Always-on box. The CLI's own docker paths call `createBox` directly and\n // pass this themselves, so it was invisible until a caller arrived that\n // only ever goes through `provider.create` (a service agent) — the box\n // came out expendable with no error anywhere. Same shape as `agents`\n // above, and the same lesson.\n persistent: req.persistent,\n docker: po.sharedCache !== undefined ? { sharedCache: po.sharedCache } : undefined,\n portless: po.portless,\n portlessStateDir: po.portlessStateDir,\n projectRoot: req.projectRoot,\n limits: req.limits ?? undefined,\n credentialSync: req.credentialSync,\n };\n const result = await createBox(opts);\n return {\n record: { ...result.record, provider: 'docker' },\n imageBuilt: result.imageBuilt,\n resync: result.resync,\n };\n },\n\n async start(box: BoxRecord): Promise<BoxRecord> {\n const { record } = await startBox(box.id);\n return { ...record, provider: 'docker' };\n },\n\n async reconnect(box: BoxRecord): Promise<BoxRecord> {\n // Reconnect re-establishes host-side wiring without a needless power-cycle.\n // A PAUSED container can't `docker start` (\"cannot start a paused\n // container\") — unpause resumes its still-frozen ctl/dockerd/vnc, and the\n // portless alias is untouched by pause, so that's all it needs. A running or\n // stopped container goes through `startBox`, which is idempotent (a\n // `docker start` on a live container is a no-op) and relaunches the daemons\n // + re-registers portless — the work a host reboot / relay restart needs.\n const insp = await inspectBox(box.id);\n if (insp.state === 'missing' || insp.state === 'destroyed') {\n throw new Error(`box ${box.name} has no container; was it destroyed?`);\n }\n if (insp.state === 'paused') {\n const record = await unpauseBox(box.id);\n return { ...record, provider: 'docker' };\n }\n const { record } = await startBox(box.id);\n return { ...record, provider: 'docker' };\n },\n\n async pause(box: BoxRecord): Promise<void> {\n await pauseBox(box.id);\n },\n\n async resume(box: BoxRecord): Promise<void> {\n await unpauseBox(box.id);\n },\n\n async stop(box: BoxRecord): Promise<void> {\n await stopBox(box.id);\n },\n\n async destroy(box: BoxRecord, opts?: { keepSnapshot?: boolean }): Promise<void> {\n await destroyBox(box.id, { keepSnapshot: opts?.keepSnapshot });\n },\n\n async resyncWorkspace(box: BoxRecord, onLog?: (line: string) => void): Promise<ResyncResult> {\n // Merge the host's current branch into each per-box worktree + overlay the\n // host's uncommitted/untracked (box wins). Reproduces `resyncBox`: the\n // facade short-circuits when the box has no worktrees. Only `ctx.onLog` is\n // read by resync (the concern reads each worktree's hostMainRepo).\n const ctx = makeSyncContext({\n boxName: box.name,\n boxId: box.id,\n provider: 'docker',\n hostWorkspace: box.workspacePath,\n onLog,\n });\n return makeDockerSync({ container: box.container }).resyncWorkspace(\n ctx,\n box.gitWorktrees ?? [],\n );\n },\n\n sync(box: BoxRecord): ProviderSync {\n return makeDockerSync({ container: box.container });\n },\n\n syncTransport(box: BoxRecord): SyncTransport {\n return createDockerSyncTransport({ container: box.container, image: box.image });\n },\n\n async inspect(box: BoxRecord): Promise<InspectedBox> {\n const insp = await inspectBox(box.id);\n return {\n record: insp.record,\n // The Docker `BoxState` adds a 'destroyed' value the provider-neutral\n // `BoxRuntimeState` folds into 'missing'.\n state: insp.state === 'destroyed' ? 'missing' : insp.state,\n endpoints: insp.endpoints,\n raw: insp.dockerInspect,\n };\n },\n\n async probeState(box: BoxRecord): Promise<BoxRuntimeState> {\n return inspectContainerStatus(box.container);\n },\n\n async stats(box: BoxRecord): Promise<BoxResourceStats> {\n return boxResourceStats(box);\n },\n\n async exec(box: BoxRecord, argv: string[], opts?: ExecOptions): Promise<ExecResult> {\n const r = await execInBox(box.container, argv, opts?.user ? { user: opts.user } : {});\n return { exitCode: r.exitCode, stdout: r.stdout, stderr: r.stderr };\n },\n\n async uploadPath(\n box: BoxRecord,\n hostSrcs: string[],\n boxDst: string,\n exclude?: string[],\n ): Promise<{ finalPath: string }> {\n const r = await uploadToBox(box, hostSrcs, boxDst, exclude);\n return { finalPath: r.finalPath };\n },\n\n async downloadPath(\n box: BoxRecord,\n boxSrcs: string[],\n hostDst: string,\n exclude?: string[],\n ): Promise<{ finalPath: string }> {\n const r = await downloadFromBox(box, boxSrcs, hostDst, exclude);\n return { finalPath: r.finalPath };\n },\n\n async resolveUrl(\n box: BoxRecord,\n opts?: { loopback?: boolean; kind?: 'web' | 'vnc'; ttl?: number },\n ): Promise<string> {\n if (box.webContainerPort === undefined) {\n throw new Error(\n `box ${box.name} predates the reserved web port; recreate it to use \\`agentbox url\\``,\n );\n }\n const engine = await detectEngine();\n if (engine === 'orbstack' && !opts?.loopback) {\n // OrbStack auto-routes <container>.orb.local to the container; :80 is\n // declared (EXPOSE 80) so no port suffix is needed.\n return `http://${box.container}.orb.local`;\n }\n if (box.portlessAlias && !opts?.loopback) {\n return box.portlessUrl ?? (await portlessGetUrl(box.portlessAlias));\n }\n if (box.webHostPort === undefined) {\n throw new Error(`web port not resolved for box ${box.name}; is the container running?`);\n }\n return `http://127.0.0.1:${String(box.webHostPort)}`;\n },\n\n async prepare(opts: PrepareOptions): Promise<PrepareResult> {\n // Docker uses the rsync-into-named-volume flow at create time, so the\n // base image stays generic — no agent-config layering. `prepare` here is\n // just an explicit handle on the build step `agentbox create` does\n // lazily on first use. Idempotent: skip when the image exists *and* the\n // build-context fingerprint matches the recorded one. `--force`\n // overrides both checks.\n const ref = DEFAULT_BOX_IMAGE;\n // The raw context sha, never folded with an agent setting: this is the\n // AGENTLESS base and installs no agent, so nothing an agent declares can\n // change what it contains. Per-agent artifacts get their own variant\n // fingerprint in `ensureImage`.\n const fingerprint = await computeDockerContextFingerprint();\n const prepared = readPreparedDockerState();\n\n if (!opts.force) {\n const exists = await imageExists(ref);\n if (exists && fingerprint && preparedMatches(prepared, fingerprint.contextSha256)) {\n opts.onLog?.(\n `docker image ${ref} up to date (fingerprint ${fingerprint.contextSha256.slice(0, 12)}) — skipping (use --force to rebuild)`,\n );\n return {};\n }\n if (exists && !fingerprint) {\n opts.onLog?.(\n `docker image ${ref} present but build context could not be fingerprinted — skipping (use --force to rebuild)`,\n );\n return {};\n }\n }\n\n // `--force` skips the registry pull and always builds a fresh local image.\n const { source } = await pullOrBuild(ref, fingerprint, {\n onProgress: opts.onLog,\n allowPull: opts.force ? false : opts.allowPull,\n registry: opts.registry,\n });\n if (fingerprint) {\n opts.onLog?.(\n `docker image ${ref} ${source}; recorded fingerprint ${fingerprint.contextSha256.slice(0, 12)}`,\n );\n } else {\n opts.onLog?.(\n `docker image ${ref} ${source} (fingerprint unavailable, prepared state not written)`,\n );\n }\n return {};\n },\n};\n","/**\n * `makeDockerSync` — the co-located `ProviderSync` facade for the docker\n * provider. THIS FILE is \"everything docker syncs\": one method per shared sync\n * op, each a thin delegation to the existing docker seed/copy/credential/resync\n * function, byte-identical to the pre-facade create path.\n *\n * The handle is closed at construction. Post-create (`dockerProvider.sync(box)`)\n * needs only `{ container }` — it's used for `resyncWorkspace`. The create path\n * builds the full handle (image + the resolved per-tool volume specs) so\n * `seedAgentConfig` / `seedCredentials` can run the volume seeds; create.ts still\n * resolves those specs once and builds the container mounts from them (one source\n * of truth for the `--isolate-*` flags + want-codex/opencode conditionals).\n *\n * NOT here (deliberate carve-out): **workspace seed** — docker's `git worktree\n * add` + `mount --bind` replay of host stash/untracked has no cloud analog (cloud\n * clones), so it stays a provider-specific step called directly by `create()`.\n * See `docs/sync-architecture.md` §\"Deliberate non-unifications\".\n */\n\nimport type {\n CarryApplyResult,\n GitWorktreeRecord,\n ProviderSync,\n ResolvedCarryEntry,\n ResyncResult,\n SyncContext,\n} from '@agentbox/core';\nimport { dryRunProviderSync, SYNC_DRYRUN_ENV } from '@agentbox/core';\nimport { AGENT_SYNC_SPECS, renderCarryEntries } from '@agentbox/sandbox-core';\nimport type { AgentSyncSpec } from '@agentbox/sandbox-core';\nimport { seedAgentDeclaredFiles, seedLabels } from './agents/seed.js';\nimport { requireAgentSyncModule, type AgentVolumeChoice } from './agents/module.js';\nimport { syncClaudeCredentials } from './claude-credentials.js';\nimport type { AgentsConfigSpec } from './agents/skills.js';\nimport { ensureAgentsVolume } from './agents/skills.js';\nimport { copyCarryPathsToBox, copyHostEnvFilesToBox } from './host-export.js';\nimport { resyncWorkspaceFromHost } from './in-box-git.js';\n\nexport interface DockerSyncHandle {\n /** Running container name (all box-side ops target it). */\n container: string;\n /**\n * Box image (ensureRef) used by the throwaway root seed-helper containers.\n * Required for the create-path seeds (`seedAgentConfig`/`seedCredentials`);\n * omitted post-create (those ops don't run then).\n */\n image?: string;\n /**\n * Resolved config-volume spec per agent, keyed by agent id. Absent key = that\n * agent isn't wanted in this box (the host has no `~/.codex` and the caller\n * didn't ask for codex, say).\n *\n * Keyed rather than one field per agent: the three named fields grew three\n * near-identical branches below, and the divergence between them is how\n * `afterVolumeSync` came to run for codex only. A map has one branch.\n */\n agentSpecs?: Record<string, AgentVolumeChoice>;\n /** Whether the claude config volume is per-box isolated (gates the credential extract). */\n claudeIsolate?: boolean;\n /** Resolved agents (~/.agents) spec, or undefined when the host has no ~/.agents. */\n agentsSpec?: AgentsConfigSpec;\n}\n\n/**\n * Guard: the create-path seeds need the box image in the handle.\n *\n * `agentSpecs` is deliberately NOT required — a box selected for one agent has\n * no volume for the others, and demanding one here would make one-agent-per-box\n * impossible. An absent key is simply an agent this box doesn't have.\n */\n/**\n * Where an agent's config comes from on the host, for the progress line —\n * derived from its `staticPaths` rather than written per agent, so a new agent\n * gets a truthful line instead of a missing one.\n */\nfunction hostSourceLabel(spec: AgentSyncSpec): string {\n const paths = spec.staticPaths.map((sp) => `~/${sp.hostHomeRel.join('/')}`);\n return paths.length > 0 ? paths.join(' + ') : `~/.${spec.id}`;\n}\n\nfunction requireCreateHandle(handle: DockerSyncHandle, op: string): { image: string } {\n if (!handle.image) {\n throw new Error(\n `dockerSync.${op} requires a create-time handle (image); it is not available post-create`,\n );\n }\n return { image: handle.image };\n}\n\nexport function makeDockerSync(handle: DockerSyncHandle): ProviderSync {\n if (process.env[SYNC_DRYRUN_ENV]) return dryRunProviderSync('docker');\n return {\n async resyncWorkspace(ctx: SyncContext, worktrees: GitWorktreeRecord[]): Promise<ResyncResult> {\n // Reproduces `resyncBox`'s empty-worktrees short-circuit, then drives the\n // provider-neutral resync concern through the docker resync ports.\n if (worktrees.length === 0) return { repos: [], hadConflicts: false };\n const repos = await resyncWorkspaceFromHost({\n container: handle.container,\n worktrees,\n onLog: ctx.onLog,\n });\n const hadConflicts = repos.some(\n (r) => r.mergeConflicts.length > 0 || r.overlaySkipped.length > 0,\n );\n return { repos, hadConflicts };\n },\n\n async seedAgentConfig(ctx: SyncContext): Promise<void> {\n // The per-tool config volume seeds, in create order. Static config +\n // skills + dynamic + box-facts all ride these volume rsyncs / overrides:\n // - every wanted agent: its module's `ensureVolume` (host config rsync),\n // its declared `seeds`, then its `afterVolumeSync`.\n // - agents: ensureAgentsVolume (~/.agents skills) — not an agent.\n // Volume *mounts* are built by create.ts from the same specs.\n const { image } = requireCreateHandle(handle, 'seedAgentConfig');\n const log = ctx.onLog;\n // Agentbox-owned files (activity hooks, the state plugin, the wizard\n // skill) come from `AgentSyncSpec.seeds` — one declaration the cloud path\n // runs too, instead of three hand-written per-agent seeders that only\n // docker ever called.\n const seedDeclared = async (agent: string, volume: string): Promise<void> => {\n const { seeded } = await seedAgentDeclaredFiles(agent, volume, image);\n for (const label of seedLabels(agent, seeded)) log(`seeded ${label} into ${volume}`);\n };\n\n // One loop, in registry order. There is no per-agent branch left here:\n // which volume, where it comes from and what to seed into it are all the\n // agent's own data, and the post-sync step is the agent's own code.\n for (const spec of AGENT_SYNC_SPECS) {\n const choice = handle.agentSpecs?.[spec.id];\n if (!choice) continue;\n const mod = requireAgentSyncModule(spec.id);\n // `hostWorkspace` is passed to every agent, not just claude: it is a\n // fact about the box, and an agent that doesn't rewrite host-scoped\n // state simply ignores it.\n const ensured = await mod.ensureVolume(choice, {\n syncFromHost: true,\n image,\n hostWorkspace: ctx.hostWorkspace,\n });\n if (ensured.synced) log(`synced ${choice.volume} from ${hostSourceLabel(spec)}`);\n else if (ensured.created)\n log(`created empty volume ${choice.volume} (no host ${hostSourceLabel(spec)})`);\n else log(`reusing volume ${choice.volume}`);\n // An ensure can report more than created/synced — claude's filters host\n // hooks, coerces the install method, aliases the project key and\n // pre-trusts the workspace. Those travel as free-form notes so the\n // shared contract keeps no field only one agent can fill.\n for (const note of ensured.notes ?? []) log(note);\n\n await seedDeclared(spec.id, choice.volume);\n\n // Every agent's post-sync step, not just codex's. Codex's AGENTS.override\n // fold was called by name here and the hook was wired into that one\n // branch, so an agent implementing it was silently skipped.\n for (const note of (await mod.afterVolumeSync?.(choice.volume, image))?.notes ?? []) {\n log(`${note} (${choice.volume})`);\n }\n }\n\n // `~/.agents` is the cross-agent skills tree, not an agent: no module, no\n // seeds, shared across boxes. It stays a separate step for that reason.\n if (handle.agentsSpec) {\n const agentsSpec = handle.agentsSpec;\n const agentsEnsured = await ensureAgentsVolume(agentsSpec, { syncFromHost: true, image });\n if (agentsEnsured.synced) log(`synced ${agentsSpec.volume} from ~/.agents`);\n else if (agentsEnsured.created) log(`created empty volume ${agentsSpec.volume}`);\n else log(`reusing volume ${agentsSpec.volume}`);\n }\n },\n\n async seedCredentials(ctx: SyncContext): Promise<void> {\n // Mirror the in-box OAuth credentials with the host backup: extract a\n // box-written `.credentials.json` out, or seed a fresh volume from a\n // previous login. syncClaudeCredentials decides the direction; isolate\n // boxes are read-seed only. Best-effort (never throws).\n const { image } = requireCreateHandle(handle, 'seedCredentials');\n // Nothing to mirror when this box wasn't created for claude.\n const claudeSpec = handle.agentSpecs?.claude;\n if (!claudeSpec) return;\n const credSync = await syncClaudeCredentials(claudeSpec, {\n image,\n isolate: handle.claudeIsolate ?? false,\n });\n if (credSync.direction === 'extracted') {\n ctx.onLog('extracted box claude credentials to host backup');\n } else if (credSync.direction === 'seeded') {\n ctx.onLog(`seeded claude credentials into ${claudeSpec.volume} from host backup`);\n }\n },\n\n // Docker has no separate post-create credential extract: the box shares the\n // host's real auth via the config volume, and `seedCredentials` already does\n // the bidirectional volume↔host-backup sync (extract branch of\n // syncClaudeCredentials) at create. So `dockerProvider` omits\n // `extractAgentCredentials` and this peer method is a documented no-op.\n extractCredentials(): Promise<string[]> {\n return Promise.resolve([]);\n },\n\n // Docker bind-mounts the host's ~/.gitconfig straight into the box, so there\n // is nothing to seed. Documented no-op (the cloud body copies it in).\n seedGitIdentity(): Promise<void> {\n return Promise.resolve();\n },\n\n async seedEnvFiles(ctx: SyncContext, patterns: string[]): Promise<{ copied: number }> {\n return copyHostEnvFilesToBox({\n container: handle.container,\n workspaceDir: ctx.hostWorkspace,\n patterns,\n onLog: ctx.onLog,\n });\n },\n\n async applyCarry(ctx: SyncContext, entries: ResolvedCarryEntry[]): Promise<CarryApplyResult> {\n // Render `replaceEnvs`/`replace` entries host-side (placeholder + rule\n // substitution) then apply the per-entry tar copy.\n const rendered = await renderCarryEntries(\n entries,\n {\n name: ctx.boxName,\n id: ctx.boxId,\n kind: 'docker',\n hostWorkspace: ctx.hostWorkspace,\n projectRoot: ctx.projectRoot,\n },\n ctx.onLog,\n );\n return copyCarryPathsToBox({\n container: handle.container,\n entries: rendered,\n onLog: ctx.onLog,\n });\n },\n };\n}\n","/**\n * Place an agent's declared `seeds` (`AgentSyncSpec.seeds`) into its docker\n * config volume, from the image-baked copies.\n *\n * Replaces `seedSetupSkillIntoVolume` / `seedCodexHooks` / `seedOpencodePlugin`,\n * which were the same throwaway-container copy written three times. The script\n * itself is built in `@agentbox/sandbox-core` so the cloud path runs the same\n * plan against the live box — that is the whole point, since the cloud path\n * previously ran nothing at all.\n *\n * Reads the volume through a throwaway container rather than a host bind mount:\n * a named volume is the only handle that works while the box is stopped, and\n * `remote-docker` drives a docker engine on another machine where a host path\n * would not resolve.\n */\n\nimport { execa } from 'execa';\nimport {\n agentSeedPlacements,\n buildAgentSeedScript,\n parseSeedMarkers,\n planAgentSeeds,\n resolveAgentSpec,\n type AgentId,\n} from '@agentbox/sandbox-core';\nimport { CONTAINER_USER } from './shared.js';\n\n/** Volume mount point inside the throwaway container. */\nconst DST = '/dst';\n\n/**\n * Copy every declared seed for `agent` into `volume`. Best-effort: returns the\n * `destRel`s that actually landed and never throws — a box create must not fail\n * because an activity hook could not be copied.\n */\nexport async function seedAgentDeclaredFiles(\n agent: AgentId,\n volume: string,\n image: string,\n): Promise<{ seeded: string[] }> {\n const spec = resolveAgentSpec(agent);\n if (!spec.seeds || spec.seeds.length === 0) return { seeded: [] };\n // Root, so it can write into a freshly created volume; chown by NAME because\n // the box user's uid is not 1000 on every provider.\n const script = buildAgentSeedScript(planAgentSeeds(spec.seeds, DST), {\n owner: `${CONTAINER_USER}:${CONTAINER_USER}`,\n });\n try {\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:${DST}`,\n image,\n 'sh',\n '-c',\n script,\n ]);\n return { seeded: parseSeedMarkers(stdout) };\n } catch {\n return { seeded: [] };\n }\n}\n\n/** Human-readable labels for what a seed run copied, for the create/start log. */\nexport function seedLabels(agent: AgentId, seeded: readonly string[]): string[] {\n const byRel = new Map(agentSeedPlacements(agent).map((p) => [p.destRel, p.label]));\n return seeded.map((rel) => byRel.get(rel) ?? rel);\n}\n","import type { AgentVolumeChoice } from './agents/module.js';\nimport { chmod, mkdir } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\nimport { execa } from 'execa';\nimport { STATE_DIR } from '../state.js';\n\n// The pure, agent-neutral credential guards moved to the credentials concern in\n// @agentbox/sandbox-core (the per-agent real-credential shape is registry data,\n// `credential.realShape`, shared with cloud). Re-exported here so existing\n// docker importers/tests — and the `@agentbox/sandbox-docker` barrel — are\n// untouched.\n//\n// The two claude-OAUTH guards that used to ride along here\n// (`hostClaudeAccessTokenExpired` / `hostClaudeLoginDead`) went further: they\n// only mean anything for a `claude-oauth` blob, so they live in\n// `@agentbox/agent-claude` now.\nexport {\n isRealAgentCredential,\n hostBackupHasCredentials,\n type CredentialAgentKind,\n} from '@agentbox/sandbox-core';\nimport { resolveAgentSpec } from '@agentbox/sandbox-core';\nimport { requireAgentCredential } from '@agentbox/core';\n\n/**\n * Host-side backup of the in-box Claude Code OAuth credentials.\n *\n * Claude's interactive login (inside a box) writes the only Linux auth file:\n * `~/.claude/.credentials.json`, holding a `claudeAiOauth` block with a real\n * `refreshToken` — that refresh token is what makes claude report \"Claude Max\"\n * instead of \"Claude API\". This host backup mirrors that blob so a fresh\n * `--isolate-claude-config` box, or a recreated shared volume, can be seeded\n * with the user's login instead of forcing a re-login.\n *\n * Security: the file holds a live refresh token. It is written mode 0600 under\n * `~/.agentbox/` (already the 0600-convention dir for `auth.json`). Plaintext\n * on disk matches the existing model — the claude-config volume already stores\n * the same blob in the clear; macOS Keychain is the *host* claude's store and\n * is unreachable from a Linux container.\n */\nexport const CREDENTIALS_BACKUP_FILE = join(STATE_DIR, 'claude-credentials.json');\n\n/**\n * Host-side backups of the in-box codex / opencode auth files, the cloud\n * analogue of {@link CREDENTIALS_BACKUP_FILE} for Claude. Unlike docker (which\n * bind-mounts the host's real `~/.codex` / `~/.config/opencode`), cloud\n * providers have no shared volume, so a login captured inside a cloud box is\n * stored here (by `extractCloudAgentCredentials` on `checkpoint --set-default`)\n * and re-pushed to the next box. The cloud stagers prefer these copies and fall\n * back to the host's real path when absent. Written mode 0600 like the claude\n * backup.\n */\nexport const CODEX_CREDENTIALS_BACKUP_FILE = join(STATE_DIR, 'codex-credentials.json');\nexport const OPENCODE_CREDENTIALS_BACKUP_FILE = join(STATE_DIR, 'opencode-credentials.json');\n\n/** Result line parser for the volume→backup extract helper. Pure (unit-tested). */\nexport function parseExtractResult(stdout: string): { copied: boolean } {\n return { copied: /\\bCOPIED=yes\\b/.test(stdout) };\n}\n\n/**\n * One-directional extract of a codex/opencode `auth.json` from a shared docker\n * config volume to a host backup under `~/.agentbox` — the cloud analogue of\n * `syncClaudeCredentials`'s extract, used after a host `agentbox <agent> login`\n * so the cloud push can seed the captured login into future boxes. The volume\n * root holds `auth.json` (same convention `volumeHas{Codex,Opencode}Auth` uses\n * for `/dst/auth.json`). Best-effort: any failure resolves to not-copied and\n * never throws into a login flow.\n */\nexport async function extractVolumeAuthToBackup(opts: {\n volume: string;\n image: string;\n backupFile: string;\n}): Promise<{ copied: boolean }> {\n try {\n await mkdir(STATE_DIR, { recursive: true });\n const script =\n 'COPIED=no; ' +\n 'if [ -s /dst/auth.json ]; then cp -a /dst/auth.json \"/host-state/$DEST\" && COPIED=yes; fi; ' +\n 'echo \"COPIED=$COPIED\"';\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${opts.volume}:/dst`,\n '-v',\n `${STATE_DIR}:/host-state`,\n '-e',\n // Pass the destination filename via env so the path isn't interpolated\n // into the script string (keeps the docker arg list static + injection-safe).\n `DEST=${basename(opts.backupFile)}`,\n opts.image,\n 'sh',\n '-c',\n script,\n ]);\n const result = parseExtractResult(stdout);\n if (result.copied) await chmod(opts.backupFile, 0o600).catch(() => {});\n return result;\n } catch {\n return { copied: false };\n }\n}\n\n/** Extract codex `auth.json` from its shared volume to `~/.agentbox/codex-credentials.json`. */\nexport function extractCodexCredentials(\n volume: string,\n image: string,\n): Promise<{ copied: boolean }> {\n return extractVolumeAuthToBackup({ volume, image, backupFile: CODEX_CREDENTIALS_BACKUP_FILE });\n}\n\n/** Extract opencode `auth.json` from its shared volume to `~/.agentbox/opencode-credentials.json`. */\nexport function extractOpencodeCredentials(\n volume: string,\n image: string,\n): Promise<{ copied: boolean }> {\n return extractVolumeAuthToBackup({ volume, image, backupFile: OPENCODE_CREDENTIALS_BACKUP_FILE });\n}\n\nexport type CredentialSyncDirection = 'extracted' | 'seeded' | 'noop';\n\nexport interface SyncClaudeCredentialsResult {\n /**\n * `extracted` — the volume's live credentials were copied out to the host\n * backup. `seeded` — the host backup was copied into an empty volume.\n * `noop` — nothing to do (or the best-effort helper failed silently).\n */\n direction: CredentialSyncDirection;\n /**\n * Whether the volume holds a real OAuth blob *after* the sync (true also\n * right after a `seeded`). When false, the in-box claude will fall back to\n * the setup-token / API key, or prompt for an interactive login.\n */\n volumeHasCredentials: boolean;\n}\n\nexport interface VolumeClaudeCredentials {\n /** A `.credentials.json` exists in the shared claude-config volume. */\n present: boolean;\n /** That file carries a usable (non-empty) `claudeAiOauth.refreshToken`. */\n hasRefreshToken: boolean;\n}\n\n/**\n * Parse the `PRESENT=<yes|no> REFRESH=<yes|no>` line the probe container prints.\n * Pure — unit-tested independently of docker.\n */\nexport function parseVolumeClaudeCredentials(stdout: string): VolumeClaudeCredentials {\n return {\n present: /\\bPRESENT=yes\\b/.test(stdout),\n hasRefreshToken: /\\bREFRESH=yes\\b/.test(stdout),\n };\n}\n\n// Probe the live `.credentials.json` the box actually boots from. `jq` ships in\n// the box image; the \"usable\" test matches SYNC_SCRIPT — a non-empty\n// `claudeAiOauth.refreshToken`. A file present with a blanked refreshToken is\n// the dead state claude leaves behind after a rejected refresh.\nconst VOLUME_CRED_PROBE_SCRIPT = `\nPRESENT=no\nREFRESH=no\nVOL=/dst/.credentials.json\nif [ -f \"$VOL\" ]; then\n PRESENT=yes\n if jq -e '(.claudeAiOauth.refreshToken // \"\") | length > 0' \"$VOL\" >/dev/null 2>&1; then REFRESH=yes; fi\nfi\necho \"PRESENT=$PRESENT REFRESH=$REFRESH\"\n`;\n\n/**\n * Inspect the shared claude-config VOLUME's live `.credentials.json` — the\n * authoritative store the in-box claude reads and refreshes. Unlike the host\n * backup (a mirror that lags and diverges when a refresh fails), this reports\n * what the next box will actually boot with: whether a credentials file exists\n * and whether it still holds a usable refresh token. Used to offer a re-login\n * only when the volume's login is dead (file present, refresh token blanked),\n * not on a merely-stale access token the in-box refresh can renew on its own.\n *\n * Best-effort: an unreadable volume / missing image resolves to\n * `{ present: false, hasRefreshToken: false }` and never throws into a flow.\n */\nexport async function volumeClaudeCredentials(\n volume: string,\n image: string,\n): Promise<VolumeClaudeCredentials> {\n try {\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n VOLUME_CRED_PROBE_SCRIPT,\n ]);\n return parseVolumeClaudeCredentials(stdout);\n } catch {\n return { present: false, hasRefreshToken: false };\n }\n}\n\n/**\n * Parse the `EXTRACTED=<yes|no> SEEDED=<yes|no> VOLREAL=<yes|no>` line the\n * helper container prints. Pure — unit-tested independently of docker.\n */\nexport function parseSyncResult(stdout: string): SyncClaudeCredentialsResult {\n const volumeHasCredentials = /\\bVOLREAL=yes\\b/.test(stdout);\n if (/\\bEXTRACTED=yes\\b/.test(stdout)) return { direction: 'extracted', volumeHasCredentials };\n if (/\\bSEEDED=yes\\b/.test(stdout)) return { direction: 'seeded', volumeHasCredentials };\n return { direction: 'noop', volumeHasCredentials };\n}\n\n// Bidirectional, best-effort, NEWEST-WINS. `jq` ships in the box image. A\n// credentials blob only counts as \"real\" when `claudeAiOauth.refreshToken` is a\n// non-empty string — a setup-token blob has an accessToken but no refreshToken,\n// and seeding/extracting it would just reproduce the \"Claude API\" label. The\n// final `echo` always runs so the caller can read the outcome; a failed `cp`\n// leaves the flag at `no` and the whole thing still exits 0.\n//\n// The direction is decided by `claudeAiOauth.expiresAt`, which strictly\n// increases on every OAuth refresh — the same ordering key the relay's\n// `shouldAcceptCredentialUpdate` fan-out gate uses. This used to extract\n// volume→host unconditionally whenever the volume held any refresh token, which\n// let a stale volume overwrite a fresher backup. Since a refresh ROTATES the\n// refresh token, the older blob isn't merely expired, it is dead — so a\n// downgrade here logs the whole fleet out. It also never seeded a volume that\n// already had *some* credential, so a volume left holding a rotated-dead blob\n// could never be repaired from a good backup.\n/**\n * The jq path for claude's declared freshness field, rendered from the SAME spec\n * entry `shouldAcceptCredentialUpdate` reads.\n *\n * This script is the rule's second implementation, in another language, running\n * in a container that has only `jq`. Hardcoding the field here is what made it a\n * copy that could drift; `credential-freshness.test.ts` pins the two together.\n */\nconst FRESHNESS_JQ = (\n requireAgentCredential(resolveAgentSpec('claude')).freshness?.jsonPath ?? [\n 'claudeAiOauth',\n 'expiresAt',\n ]\n)\n .map((k: string) => `.${k}`)\n .join('');\n\nexport const SYNC_SCRIPT = `\nEXTRACTED=no\nSEEDED=no\nVOL=/dst/.credentials.json\nHOST=/host-state/claude-credentials.json\nnum() { case \"$1\" in ''|*[!0-9]*) echo 0;; *) echo \"$1\";; esac; }\nif [ -f \"$VOL\" ] && jq -e '(.claudeAiOauth.refreshToken // \"\") | length > 0' \"$VOL\" >/dev/null 2>&1; then VOL_REAL=yes; else VOL_REAL=no; fi\nif [ -f \"$HOST\" ] && jq -e '(.claudeAiOauth.refreshToken // \"\") | length > 0' \"$HOST\" >/dev/null 2>&1; then HOST_REAL=yes; else HOST_REAL=no; fi\nVOL_EXP=$(num \"$(jq -r '(${FRESHNESS_JQ} // 0) | floor' \"$VOL\" 2>/dev/null)\")\nHOST_EXP=$(num \"$(jq -r '(${FRESHNESS_JQ} // 0) | floor' \"$HOST\" 2>/dev/null)\")\nif [ \"$VOL_REAL\" = yes ] && [ \"$ISOLATE\" != yes ] && { [ \"$HOST_REAL\" = no ] || [ \"$VOL_EXP\" -gt \"$HOST_EXP\" ]; }; then\n cp -a \"$VOL\" \"$HOST\" && chmod 600 \"$HOST\" && EXTRACTED=yes\nelif [ \"$HOST_REAL\" = yes ] && { [ \"$VOL_REAL\" = no ] || [ \"$HOST_EXP\" -gt \"$VOL_EXP\" ]; }; then\n cp -a \"$HOST\" \"$VOL\" && chown 1000:1000 \"$VOL\" && chmod 600 \"$VOL\" && SEEDED=yes && VOL_REAL=yes\nfi\necho \"EXTRACTED=$EXTRACTED SEEDED=$SEEDED VOLREAL=$VOL_REAL\"\n`;\n\n/**\n * Bidirectionally sync the box's `.credentials.json` with the host backup,\n * newest `claudeAiOauth.expiresAt` wins:\n *\n * - volume blob is real, newer than the backup (or the backup isn't real), and\n * the box is **not** isolate → copy it OUT to {@link CREDENTIALS_BACKUP_FILE}\n * (the usual case: the volume is the live copy the in-box claude refreshes).\n * - host backup is real and newer than the volume's (or the volume has no\n * credentials at all) → copy it IN. Seeds a fresh isolate box or a recreated\n * shared volume, and repairs a volume whose copy was rotated dead by another\n * box while this one sat idle.\n * - otherwise → noop.\n *\n * Isolate boxes are read-seed only — never extract — so N isolate boxes can't\n * race on the single host backup.\n *\n * Best-effort: any failure resolves to `{ direction: 'noop' }` and never\n * throws into a box operation.\n */\nexport async function syncClaudeCredentials(\n spec: AgentVolumeChoice,\n opts: { image: string; isolate: boolean },\n): Promise<SyncClaudeCredentialsResult> {\n try {\n await mkdir(STATE_DIR, { recursive: true });\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${spec.volume}:/dst`,\n '-v',\n `${STATE_DIR}:/host-state`,\n '-e',\n `ISOLATE=${opts.isolate ? 'yes' : 'no'}`,\n opts.image,\n 'sh',\n '-c',\n SYNC_SCRIPT,\n ]);\n const result = parseSyncResult(stdout);\n // The helper runs as root; re-assert 0600 from the host side so the backup\n // is owner-only regardless of how the bind mount maps ownership.\n if (result.direction === 'extracted') {\n await chmod(CREDENTIALS_BACKUP_FILE, 0o600).catch(() => {});\n }\n return result;\n } catch {\n return { direction: 'noop', volumeHasCredentials: false };\n }\n}\n","// The box state store is provider-neutral and lives in @agentbox/sandbox-core\n// so cloud providers share it. The record TYPES live in @agentbox/core. Both\n// are re-exported here so existing `@agentbox/sandbox-docker` consumers keep\n// importing them from the same place.\nexport {\n STATE_DIR,\n STATE_FILE,\n allocateProjectIndex,\n autoPickProjectBox,\n findBox,\n readState,\n recordBox,\n recordLastAgent,\n removeBoxRecord,\n reserveProjectIndex,\n resolveBoxRef,\n writeState,\n} from '@agentbox/sandbox-core';\nexport type { BoxRecord, FindBoxResult, GitWorktreeRecord, StateFile } from '@agentbox/core';\n","import { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { seedAgentsVolume } from '@agentbox/sandbox-core';\nimport { ensureVolume, volumeExists } from '../../docker.js';\nimport { createDockerSyncTransport } from '../sync-transport.js';\n\n/**\n * The shared `~/.agents` directory — the cross-agent \"Agent Skills\" location\n * (`~/.agents/skills/<name>`, managed by the open skills installer). Codex\n * discovers skills from here directly (not just `~/.codex/skills`), and the\n * per-agent `~/.codex/skills/<x>` symlinks point back into it\n * (`../../.agents/skills/<x>`). We mount it into the box so the in-box agents\n * see the same skill set the host does.\n *\n * Unlike claude/codex this holds no auth — it's skills only — but it's synced\n * the same host-authoritative way and shares one volume across boxes.\n */\nexport const SHARED_AGENTS_VOLUME = 'agentbox-agents-config';\n\n/** Where the agents volume is mounted in the box. */\nconst CONTAINER_AGENTS_DIR = '/home/vscode/.agents';\n\nexport interface AgentsConfigSpec {\n /** Resolved Docker volume name mounted at /home/vscode/.agents. */\n volume: string;\n}\n\n/** Always the shared volume — `~/.agents` is skills-only, so per-box isolation\n * buys nothing (no auth to keep separate). */\nexport function resolveAgentsVolume(): AgentsConfigSpec {\n return { volume: SHARED_AGENTS_VOLUME };\n}\n\nexport interface EnsureAgentsVolumeOptions {\n /**\n * When true and the host's ~/.agents exists, rsync host -> volume on every\n * call. Additive (no `--delete`): host files win on overlap.\n */\n syncFromHost: boolean;\n /** Image used by the throwaway sync helper container (the box image). */\n image: string;\n}\n\nexport interface EnsureAgentsVolumeResult {\n /** True only the very first time the volume is created (on this host). */\n created: boolean;\n /** True when the rsync helper ran (syncFromHost was true AND host ~/.agents existed). */\n synced: boolean;\n}\n\n/**\n * Ensure the agents-config volume exists, then (when {@link\n * EnsureAgentsVolumeOptions.syncFromHost} is true and the host has a `~/.agents`)\n * rsync host -> volume via a throwaway helper container. Mirrors\n * {@link import('./codex.js').ensureCodexVolume}.\n *\n * `--copy-unsafe-links` dereferences a skill's symlinks that point outside\n * `~/.agents` into real files in the volume; broken / out-of-tree symlinks are\n * `--exclude`d (via {@link findUnsyncableSymlinks}) so the sync can't abort with\n * \"symlink has no referent\".\n */\nexport async function ensureAgentsVolume(\n spec: AgentsConfigSpec,\n opts: EnsureAgentsVolumeOptions,\n): Promise<EnsureAgentsVolumeResult> {\n const existed = await volumeExists(spec.volume);\n await ensureVolume(spec.volume);\n const created = !existed;\n\n // The host→volume rsync (symlink handling, `--copy-unsafe-links`, the\n // no-host-dir writable-chown fallback) is the shared skills concern, driven\n // through the transport's throwaway rsync-helper container. `container: ''`\n // because the seed needs only the helper image, not a running box.\n const transport = createDockerSyncTransport({ container: '', image: opts.image });\n const { synced } = await seedAgentsVolume({\n transport,\n volume: spec.volume,\n hostAgents: join(homedir(), '.agents'),\n syncFromHost: opts.syncFromHost,\n });\n return { created, synced };\n}\n\nexport interface AgentsMountResult {\n /** Docker -v spec strings to append to runBox(extraVolumes). */\n extraVolumes: string[];\n /** The resolved volume name (for BoxRecord). */\n volumeName: string;\n}\n\nexport function buildAgentsMounts(spec: AgentsConfigSpec): AgentsMountResult {\n return {\n extraVolumes: [`${spec.volume}:${CONTAINER_AGENTS_DIR}`],\n volumeName: spec.volume,\n };\n}\n","import { execa, type Result } from 'execa';\n\nexport interface DockerExecResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport type ContainerRuntimeState = 'running' | 'paused' | 'stopped' | 'missing';\n\nexport async function dockerInfo(): Promise<void> {\n const result: Result = await execa('docker', ['info'], { reject: false });\n if (result.exitCode !== 0) {\n throw new Error(\n `docker info failed (exit ${String(result.exitCode)}). Is the Docker daemon running?\\n${String(result.stderr)}`,\n );\n }\n}\n\n/**\n * Engine-agnostic resource ceilings. Memory in bytes, cpus fractional, disk a\n * raw engine-native size string. `null`/absent = unlimited.\n */\nexport interface BoxLimitSpec {\n memoryBytes?: number | null;\n cpus?: number | null;\n pidsLimit?: number | null;\n disk?: string | null;\n}\n\nexport interface RunBoxSpec {\n name: string;\n image: string;\n extraVolumes?: string[];\n env?: Record<string, string>;\n limits?: BoxLimitSpec;\n /**\n * docker `-p` mappings to forward host ports into the container. `hostPort: 0`\n * lets Docker pick a free ephemeral port; resolve it back with\n * {@link publishedHostPort}. `hostIp` defaults to all interfaces — pin it to\n * `127.0.0.1` for loopback-only exposure.\n */\n portMappings?: Array<{ hostPort: number; containerPort: number; hostIp?: string }>;\n}\n\nexport async function runBox(spec: RunBoxSpec): Promise<string> {\n const args: string[] = [\n 'run',\n '-d',\n '--name',\n spec.name,\n '--hostname',\n spec.name,\n '--cap-add=SYS_ADMIN',\n // dockerd inside the box (always-on, see launchDockerdDaemon) needs\n // NET_ADMIN to set up its bridge + iptables NAT for inner containers.\n // seccomp:unconfined is required because the default profile blocks\n // syscalls (notably keyctl, clone3 in some kernels) that nested containers\n // need. Both are scoped to the outer box's namespaces — inner containers\n // can't escape it. We still avoid --privileged for cloud portability.\n '--cap-add=NET_ADMIN',\n // /dev/fuse + SYS_ADMIN + apparmor:unconfined used to be required for the\n // outer /workspace FUSE overlay. That overlay is gone, but they're still\n // load-bearing for the *inner* dockerd's storage driver, which\n // agentbox-dockerd-start selects at runtime: SYS_ADMIN lets it `mount -t\n // overlay` for the preferred kernel-native overlay2 driver, and /dev/fuse\n // + SYS_ADMIN + apparmor:unconfined are needed for the fuse-overlayfs\n // fallback (used where overlay2's runtime probe fails).\n '--device=/dev/fuse',\n '--security-opt=apparmor:unconfined',\n '--security-opt=seccomp=unconfined',\n // cgroup v2 + DinD: with --cgroupns=host (the OrbStack default) the\n // outer container sees the host's read-only cgroup hierarchy at\n // /sys/fs/cgroup, so the inner dockerd can't `mkdir /sys/fs/cgroup/docker`\n // for its own slice and inner `docker run` fails with \"read-only file\n // system\". Private gives the box its own writable cgroup namespace; runc\n // creates the docker slice there and inner containers nest under it.\n '--cgroupns=private',\n // Make the host reachable from inside the container at the well-known DNS\n // name host.docker.internal. Docker Desktop / OrbStack ship this alias by\n // default; on Linux native Docker it requires this explicit flag (no-op\n // on the macOS engines). Boxes use it to reach the host relay process.\n '--add-host=host.docker.internal:host-gateway',\n ];\n // Nested AgentBox-in-AgentBox dev only: the outer sandbox lacks\n // CAP_SYS_PTRACE, so the inner dockerd can't bind-mount /proc/<pid>/ns/net\n // for a non-root container init (image default USER is vscode → uid 1000).\n // Forcing init to uid 0 makes init's /proc readable by daemon (same uid) so\n // netns setup succeeds. Gated on AGENTBOX=1 so normal-host runs are\n // unaffected. shell/exec flows pass --user explicitly (CONTAINER_USER),\n // so this only changes which uid the supervisor + service tree run as\n // inside a nested box.\n if (process.env.AGENTBOX === '1') {\n args.push('--user', '0');\n }\n const lim = spec.limits;\n if (lim) {\n if (lim.memoryBytes && lim.memoryBytes > 0) {\n args.push('--memory', String(Math.floor(lim.memoryBytes)));\n }\n if (lim.cpus && lim.cpus > 0) {\n args.push('--cpus', String(lim.cpus));\n }\n if (lim.pidsLimit && lim.pidsLimit > 0) {\n args.push('--pids-limit', String(Math.floor(lim.pidsLimit)));\n }\n // Best-effort: a no-op on overlay2 / the macOS engines. createBox() drops\n // this on those drivers (and warns) so `docker run` doesn't hard-error.\n if (lim.disk) {\n args.push('--storage-opt', `size=${lim.disk}`);\n }\n }\n for (const v of spec.extraVolumes ?? []) {\n args.push('-v', v);\n }\n for (const pm of spec.portMappings ?? []) {\n const host = pm.hostIp ? `${pm.hostIp}:${String(pm.hostPort)}` : String(pm.hostPort);\n args.push('-p', `${host}:${String(pm.containerPort)}`);\n }\n for (const [k, val] of Object.entries(spec.env ?? {})) {\n args.push('-e', `${k}=${val}`);\n }\n args.push(spec.image, 'sleep', 'infinity');\n\n const { stdout } = await execa('docker', args);\n return stdout.trim();\n}\n\n/**\n * The engine's storage driver (`overlay2`, `fuse-overlayfs`, `btrfs`, …).\n * `--storage-opt size=` is only enforced by devicemapper/btrfs/zfs/windowsfilter\n * — a no-op everywhere the macOS engines run. Empty string on probe failure.\n */\nexport async function dockerStorageDriver(): Promise<string> {\n const result = await execa('docker', ['info', '--format', '{{.Driver}}'], { reject: false });\n if (result.exitCode !== 0) return '';\n return (result.stdout ?? '').trim();\n}\n\nexport async function execInBox(\n container: string,\n cmd: string[],\n opts: { user?: string; detach?: boolean; timeoutMs?: number } = {},\n): Promise<DockerExecResult> {\n const args: string[] = ['exec'];\n if (opts.detach) args.push('-d');\n if (opts.user) args.push('--user', opts.user);\n args.push(container, ...cmd);\n const result = await execa('docker', args, {\n reject: false,\n ...(opts.timeoutMs ? { timeout: opts.timeoutMs } : {}),\n });\n return {\n exitCode: result.exitCode ?? -1,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n };\n}\n\nexport async function removeContainer(container: string): Promise<void> {\n await execa('docker', ['rm', '-f', container], { reject: false });\n}\n\nexport async function removeVolume(name: string): Promise<void> {\n await execa('docker', ['volume', 'rm', name], { reject: false });\n}\n\n/**\n * Best-effort `docker image rm`. Returns true when the image was actually\n * removed, false when it was already absent (or removal failed). `-f` is\n * passed by default so a stale tagged image with no live containers goes away\n * even if other tags point at the same layers.\n */\nexport async function removeImage(ref: string, opts: { force?: boolean } = {}): Promise<boolean> {\n const args = ['image', 'rm'];\n if (opts.force !== false) args.push('-f');\n args.push(ref);\n const result = await execa('docker', args, { reject: false });\n return result.exitCode === 0;\n}\n\nexport async function containerExists(name: string): Promise<boolean> {\n const result = await execa('docker', ['container', 'inspect', '--format', '{{.Id}}', name], {\n reject: false,\n });\n return result.exitCode === 0;\n}\n\nexport async function volumeExists(name: string): Promise<boolean> {\n const result = await execa('docker', ['volume', 'inspect', name], { reject: false });\n return result.exitCode === 0;\n}\n\nexport async function ensureVolume(name: string): Promise<void> {\n if (await volumeExists(name)) return;\n await execa('docker', ['volume', 'create', name]);\n}\n\nexport async function networkExists(name: string): Promise<boolean> {\n const result = await execa('docker', ['network', 'inspect', name], { reject: false });\n return result.exitCode === 0;\n}\n\nexport async function ensureNetwork(name: string): Promise<void> {\n if (await networkExists(name)) return;\n await execa('docker', ['network', 'create', name]);\n}\n\nexport async function removeNetwork(name: string): Promise<void> {\n await execa('docker', ['network', 'rm', name], { reject: false });\n}\n\nexport async function containerIsRunning(name: string): Promise<boolean> {\n return (await inspectContainerStatus(name)) === 'running';\n}\n\nexport async function pauseContainer(name: string): Promise<void> {\n await execa('docker', ['pause', name]);\n}\n\nexport async function unpauseContainer(name: string): Promise<void> {\n await execa('docker', ['unpause', name]);\n}\n\nexport async function stopContainer(name: string): Promise<void> {\n await execa('docker', ['stop', name]);\n}\n\nexport async function startContainer(name: string): Promise<void> {\n await execa('docker', ['start', name]);\n}\n\nexport async function inspectContainerStatus(name: string): Promise<ContainerRuntimeState> {\n const result = await execa('docker', ['inspect', '--format', '{{.State.Status}}', name], {\n reject: false,\n });\n if (result.exitCode !== 0) return 'missing';\n const status = (result.stdout ?? '').trim();\n switch (status) {\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\nexport async function inspectContainer(name: string): Promise<unknown | null> {\n const result = await execa('docker', ['inspect', name], { reject: false });\n if (result.exitCode !== 0) return null;\n try {\n const parsed = JSON.parse(result.stdout ?? 'null') as unknown[];\n return Array.isArray(parsed) ? (parsed[0] ?? null) : null;\n } catch {\n return null;\n }\n}\n\nexport async function inspectVolumeMountpoint(name: string): Promise<string | null> {\n const result = await execa('docker', ['volume', 'inspect', '--format', '{{.Mountpoint}}', name], {\n reject: false,\n });\n if (result.exitCode !== 0) return null;\n return (result.stdout ?? '').trim() || null;\n}\n\nconst AGENTBOX_PREFIX = 'agentbox-';\n\nexport async function listAgentboxContainers(): Promise<string[]> {\n const result = await execa(\n 'docker',\n ['ps', '-a', '--filter', `name=^${AGENTBOX_PREFIX}`, '--format', '{{.Names}}'],\n { reject: false },\n );\n if (result.exitCode !== 0) return [];\n return (result.stdout ?? '')\n .split('\\n')\n .map((s) => s.trim())\n .filter((s) => s.startsWith(AGENTBOX_PREFIX));\n}\n\n/**\n * Resolve the host port Docker assigned to a `-p hostPort:containerPort` mapping\n * that used `hostPort=0`. Returns null when the port isn't published or the\n * container is gone. `docker port <name> 6080/tcp` prints e.g.\n * `127.0.0.1:54321` (one line per binding); we take the first.\n */\nexport async function publishedHostPort(\n container: string,\n containerPort: number,\n): Promise<number | null> {\n const result = await execa('docker', ['port', container, `${String(containerPort)}/tcp`], {\n reject: false,\n });\n if (result.exitCode !== 0) return null;\n const first = (result.stdout ?? '').split('\\n')[0]?.trim();\n if (!first) return null;\n const m = /:(\\d+)$/.exec(first);\n return m ? Number(m[1]) : null;\n}\n\nexport async function listAgentboxVolumes(): Promise<string[]> {\n const result = await execa(\n 'docker',\n ['volume', 'ls', '--filter', `name=^${AGENTBOX_PREFIX}`, '--format', '{{.Name}}'],\n { reject: false },\n );\n if (result.exitCode !== 0) return [];\n return (result.stdout ?? '')\n .split('\\n')\n .map((s) => s.trim())\n .filter((s) => s.startsWith(AGENTBOX_PREFIX));\n}\n","/**\n * The docker implementations of the `SyncTransport` seam (`@agentbox/core`).\n *\n * Two of them, over one body:\n *\n * - **container mode** (`createDockerSyncTransport`) — `docker exec`/`cp`\n * against a RUNNING box. Needs only a container name, so it works at create\n * time before a full `BoxRecord` exists.\n * - **volume mode** (`createDockerVolumeSyncTransport`) — a throwaway helper\n * container with the box's config volume bind-mounted AT ITS BOX PATH, so a\n * caller writes the same box-absolute paths either way and the box does not\n * have to be running. This is what the per-agent pulls need: they are\n * documented as working against a stopped box, which is why each of them\n * used to hand-roll its own `docker run -v` instead of using the transport.\n *\n * The two differ ONLY in how a command reaches the box filesystem — the tar\n * flags, the exclude handling and the ownership rules are written once here.\n * `applyTarball` reproduces `copyHostEnvFilesToBox`'s extract exactly.\n */\n\nimport { createReadStream } from 'node:fs';\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type {\n PushOptions,\n SyncExecOptions,\n SyncExecResult,\n SyncTransport,\n TransportCaps,\n VolumeHostSource,\n} from '@agentbox/core';\n\nexport interface DockerSyncTransportInit {\n /** Target container name (running, overlay mounted). */\n container: string;\n /** Image for the throwaway rsync helper container (`seedVolumeFromHost`). */\n image?: string;\n}\n\nexport interface DockerVolumeSyncTransportInit {\n /** The docker volume standing in for the box filesystem. */\n volume: string;\n /**\n * Where that volume is mounted inside a real box (`/home/vscode/.claude`).\n *\n * Load-bearing: the helper container mounts it at the SAME path, so every\n * box-absolute path a caller passes resolves identically in both modes. Take\n * it from the registry (`staticPaths[0].boxDir`), never a literal.\n */\n mountPath: string;\n /** Image the helper container runs (needs `tar`, and `rsync` for seeding). */\n image: string;\n}\n\n/**\n * macOS `tar` writes an AppleDouble `._name` sidecar per entry unless this is\n * set, and those land in the box as garbage files (and made a one-entry push\n * fail outright, since the sidecar is extracted too).\n */\nconst HOST_TAR_ENV = { ...process.env, COPYFILE_DISABLE: '1' };\n\nconst DOCKER_CAPS: TransportCaps = {\n persistentVolumes: true,\n helperContainer: true,\n ephemeralFs: false,\n};\n\n/** How a command reaches the box filesystem. The only thing the modes differ in. */\ninterface DockerRunner {\n /** Full `docker` argv running `cmd` against the box filesystem. */\n argv(cmd: string[], opts?: RunnerOptions): string[];\n /**\n * `docker cp` argv, or null when the mode has no cp (volume mode: there is no\n * container to address). Callers fall back to a tar stream.\n */\n cpIn(hostPath: string, boxPath: string): string[] | null;\n cpOut(boxPath: string, hostPath: string): string[] | null;\n /**\n * Who runs a tar extract.\n *\n * Container mode pins the box uid, because the box's own dirs are already\n * owned by it. A helper container has no such luxury: the volume's dirs are\n * root-owned, so a `--user 1000` extract fails with \"Permission denied\" —\n * found by round-tripping a real volume, not by reading. Volume mode extracts\n * as root and chowns after, exactly as the hand-rolled agent containers did.\n */\n extractUser(uid: number): string;\n /** True when a write must be chowned afterwards (volume mode). */\n chownAfterWrite: boolean;\n}\n\ninterface RunnerOptions extends SyncExecOptions {\n /** Keep stdin open (`-i`) for a streamed tarball. */\n stdin?: boolean;\n /** Mount the box filesystem read-only. Volume mode only; ignored on exec. */\n readOnly?: boolean;\n}\n\nfunction containerRunner(container: string): DockerRunner {\n return {\n argv(cmd, opts) {\n const pre: string[] = ['exec'];\n if (opts?.stdin) pre.push('-i');\n if (opts?.user) pre.push('--user', opts.user);\n if (opts?.cwd) pre.push('-w', opts.cwd);\n for (const [k, v] of Object.entries(opts?.env ?? {})) pre.push('-e', `${k}=${v}`);\n return [...pre, container, ...cmd];\n },\n cpIn: (hostPath, boxPath) => ['cp', hostPath, `${container}:${boxPath}`],\n cpOut: (boxPath, hostPath) => ['cp', `${container}:${boxPath}`, hostPath],\n extractUser: (uid) => `${uid}:${uid}`,\n chownAfterWrite: false,\n };\n}\n\nfunction volumeRunner(init: DockerVolumeSyncTransportInit): DockerRunner {\n return {\n argv(cmd, opts) {\n const pre: string[] = ['run', '--rm'];\n if (opts?.stdin) pre.push('-i');\n // Default to root: the helper has no box user session and every write\n // here is followed by an explicit chown, exactly as the hand-rolled\n // per-agent containers did.\n pre.push('--user', opts?.user ?? '0');\n if (opts?.cwd) pre.push('-w', opts.cwd);\n for (const [k, v] of Object.entries(opts?.env ?? {})) pre.push('-e', `${k}=${v}`);\n pre.push('-v', `${init.volume}:${init.mountPath}${opts?.readOnly ? ':ro' : ''}`);\n return [...pre, init.image, ...cmd];\n },\n // No container to address; the transport falls back to a tar stream.\n cpIn: () => null,\n cpOut: () => null,\n extractUser: () => '0',\n chownAfterWrite: true,\n };\n}\n\nfunction makeTransport(runner: DockerRunner, image: string | undefined): SyncTransport {\n const transport: SyncTransport = {\n caps: DOCKER_CAPS,\n\n async exec(cmd: string[], opts?: SyncExecOptions): Promise<SyncExecResult> {\n const r = await execa('docker', runner.argv(cmd, opts), { reject: false });\n return {\n exitCode: typeof r.exitCode === 'number' ? r.exitCode : 1,\n stdout: String(r.stdout ?? ''),\n stderr: String(r.stderr ?? ''),\n };\n },\n\n async applyTarball(hostTarPath: string, boxDestDir: string, opts?: PushOptions): Promise<void> {\n const uid = opts?.uid ?? 1000;\n const tarArgs = ['tar', '-xf', '-', '-C', boxDestDir];\n if (opts?.noSamePerms) tarArgs.push('--no-same-permissions', '--no-same-owner', '-m');\n // Always pin the extract user explicitly (`--user <uid>:<uid>`), incl.\n // `0:0` for root — omitting it would run as the image's default USER\n // (vscode), which is wrong for a root-owned carry extract.\n const args = runner.argv(tarArgs, { stdin: true, user: runner.extractUser(uid) });\n const r = await execa('docker', args, {\n input: createReadStream(hostTarPath),\n reject: false,\n });\n if (r.exitCode !== 0) {\n throw new Error(\n `docker tar extract into ${boxDestDir} failed: ${String(r.stderr).slice(0, 300)}`,\n );\n }\n if (runner.chownAfterWrite && uid !== 0) {\n await transport.exec(['chown', '-R', `${uid}:${uid}`, boxDestDir], { user: '0' });\n }\n },\n\n async pushTree(hostSrcDir: string, boxDestDir: string, opts?: PushOptions): Promise<void> {\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-pushtree-'));\n const localTar = join(stage, 'tree.tar');\n try {\n const packArgs = ['-C', hostSrcDir];\n for (const ex of opts?.exclude ?? []) packArgs.push(`--exclude=${ex}`);\n packArgs.push('-cf', localTar, '.');\n const packed = await execa('tar', packArgs, { reject: false, env: HOST_TAR_ENV });\n if (packed.exitCode !== 0) {\n throw new Error(\n `tar pack of ${hostSrcDir} failed: ${String(packed.stderr).slice(0, 300)}`,\n );\n }\n await transport.applyTarball(localTar, boxDestDir, opts);\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n },\n\n async pushFile(hostSrcPath: string, boxDestPath: string, opts?: PushOptions): Promise<void> {\n const cp = runner.cpIn(hostSrcPath, boxDestPath);\n if (cp) {\n const r = await execa('docker', cp, { reject: false });\n if (r.exitCode !== 0) {\n throw new Error(\n `docker cp into ${boxDestPath} failed: ${String(r.stderr).slice(0, 300)}`,\n );\n }\n } else {\n // No cp in volume mode: stream a one-entry tarball instead. `-C` on the\n // host side plus the basename keeps the archive path relative, so the\n // extract lands the file at exactly `boxDestPath`.\n const dir = boxDestPath.slice(0, boxDestPath.lastIndexOf('/')) || '/';\n const base = boxDestPath.slice(boxDestPath.lastIndexOf('/') + 1);\n const hostDir = hostSrcPath.slice(0, hostSrcPath.lastIndexOf('/')) || '.';\n const hostBase = hostSrcPath.slice(hostSrcPath.lastIndexOf('/') + 1);\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-pushfile-'));\n const localTar = join(stage, 'file.tar');\n try {\n const packed = await execa(\n 'tar',\n ['-C', hostDir, '-cf', localTar, `--transform=s|^${hostBase}$|${base}|`, hostBase],\n { reject: false, env: HOST_TAR_ENV },\n );\n if (packed.exitCode !== 0) {\n // BSD tar has no --transform; fall back to a plain pack + rename.\n await execa('tar', ['-C', hostDir, '-cf', localTar, hostBase], {\n reject: false,\n env: HOST_TAR_ENV,\n });\n await transport.applyTarball(localTar, dir, opts);\n if (hostBase !== base) {\n await transport.exec(['mv', `${dir}/${hostBase}`, boxDestPath], { user: '0' });\n }\n } else {\n await transport.applyTarball(localTar, dir, opts);\n }\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n }\n if (opts?.uid !== undefined && opts.uid !== 0) {\n await transport.exec(['chown', `${opts.uid}:${opts.uid}`, boxDestPath], { user: '0' });\n }\n if (opts?.mode !== undefined) {\n await transport.exec(['chmod', opts.mode.toString(8), boxDestPath], { user: '0' });\n }\n },\n\n async pullTree(\n boxSrcDir: string,\n hostDestDir: string,\n opts?: { exclude?: string[] },\n ): Promise<void> {\n const tarArgs = ['tar', '-C', boxSrcDir];\n for (const ex of opts?.exclude ?? []) tarArgs.push(`--exclude=${ex}`);\n tarArgs.push('-cf', '-', '.');\n const packed = await execa('docker', runner.argv(tarArgs, { readOnly: true }), {\n encoding: 'buffer',\n reject: false,\n });\n if (packed.exitCode !== 0) {\n throw new Error(\n `docker tar of ${boxSrcDir} failed: ${String(packed.stderr).slice(0, 300)}`,\n );\n }\n await execa('tar', ['-xf', '-', '-C', hostDestDir], {\n input: packed.stdout as Buffer,\n reject: false,\n });\n },\n\n async pullFile(boxSrcPath: string, hostDestPath: string): Promise<void> {\n const cp = runner.cpOut(boxSrcPath, hostDestPath);\n if (cp) {\n const r = await execa('docker', cp, { reject: false });\n if (r.exitCode !== 0) {\n throw new Error(`docker cp from ${boxSrcPath} failed: ${String(r.stderr).slice(0, 300)}`);\n }\n return;\n }\n // Volume mode: stream the single entry out through tar, preserving mode\n // (a `cat` redirect would not — `auth.json` has to stay 0600).\n const dir = boxSrcPath.slice(0, boxSrcPath.lastIndexOf('/')) || '/';\n const base = boxSrcPath.slice(boxSrcPath.lastIndexOf('/') + 1);\n const packed = await execa(\n 'docker',\n runner.argv(['tar', '-C', dir, '-cf', '-', base], { readOnly: true }),\n { encoding: 'buffer', reject: false },\n );\n if (packed.exitCode !== 0) {\n throw new Error(\n `docker tar of ${boxSrcPath} failed: ${String(packed.stderr).slice(0, 300)}`,\n );\n }\n const hostDir = hostDestPath.slice(0, hostDestPath.lastIndexOf('/')) || '.';\n const hostBase = hostDestPath.slice(hostDestPath.lastIndexOf('/') + 1);\n await execa('tar', ['-xf', '-', '-C', hostDir], {\n input: packed.stdout as Buffer,\n reject: false,\n });\n if (hostBase !== base) {\n await execa('mv', [join(hostDir, base), hostDestPath], { reject: false });\n }\n },\n\n async readText(boxPath: string): Promise<string | null> {\n const r = await execa('docker', runner.argv(['cat', boxPath], { readOnly: true }), {\n reject: false,\n });\n if (r.exitCode !== 0) return null;\n return String(r.stdout ?? '');\n },\n\n async ensureVolume(name: string): Promise<{ volumeId: string }> {\n await execa('docker', ['volume', 'create', name], { reject: false });\n return { volumeId: name };\n },\n\n async seedVolumeFromHost(volume: string, sources: VolumeHostSource[]): Promise<void> {\n if (!image) throw new Error('seedVolumeFromHost requires an image');\n const args = ['run', '--rm', '--user', '0', '-v', `${volume}:/dst`];\n const steps: string[] = [];\n sources.forEach((src, i) => {\n const mount = `/src-${String(i)}`;\n args.push('-v', `${src.hostDir}:${mount}:ro`);\n const dest = src.destSubpath ? `/dst/${src.destSubpath}` : '/dst';\n const rsync = ['rsync', '-a'];\n if (src.copyUnsafeLinks) rsync.push('--copy-unsafe-links');\n if (src.update) rsync.push('--update');\n for (const inc of src.include ?? []) rsync.push(`--include=${inc}`);\n for (const ex of src.exclude ?? []) rsync.push(`--exclude=${ex}`);\n rsync.push(`${mount}/`, `${dest}/`);\n steps.push(`mkdir -p ${dest} && ${rsync.join(' ')}`);\n });\n steps.push('chown -R 1000:1000 /dst');\n args.push(image, 'sh', '-c', steps.join(' && '));\n const r = await execa('docker', args, { reject: false });\n if (r.exitCode !== 0) {\n throw new Error(`seedVolumeFromHost(${volume}) failed: ${String(r.stderr).slice(0, 300)}`);\n }\n },\n };\n\n return transport;\n}\n\nexport function createDockerSyncTransport(init: DockerSyncTransportInit): SyncTransport {\n return makeTransport(containerRunner(init.container), init.image);\n}\n\n/**\n * A `SyncTransport` over a docker VOLUME rather than a running container.\n *\n * The box need not exist. Used by the per-agent pulls, which have always been\n * documented as working against a stopped box — each of them used to reach for\n * `docker run -v` directly, which is how three of them ended up with three\n * different inventory dialects and only one of them preserving `auth.json`'s\n * 0600.\n */\nexport function createDockerVolumeSyncTransport(\n init: DockerVolumeSyncTransportInit,\n): SyncTransport {\n return makeTransport(volumeRunner(init), init.image);\n}\n\n/** Exported for the argv tests — the two modes must stay path-compatible. */\nexport const __testing = { containerRunner, volumeRunner };\n","import { mkdir, readFile, readdir, stat } from 'node:fs/promises';\nimport { createHash } from 'node:crypto';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { execa } from 'execa';\nimport { sanitizeMnemonic } from '@agentbox/config';\nimport {\n hostOpenCommand,\n makeSyncContext,\n pushEnvFiles,\n planCarryEntry,\n buildWorkspaceListScript,\n parseWorkspaceList,\n rsyncPullToHost,\n workspaceExcludes,\n BOX_HOME,\n ENV_PRUNE_DIRS,\n} from '@agentbox/sandbox-core';\nimport { normalizeAgentStatus } from '@agentbox/core';\nimport type { ResolvedCarryEntry } from '@agentbox/core';\nimport type { BoxStatus } from '@agentbox/ctl';\nimport { streamTarPipe } from '../box-cp.js';\nimport { execInBox } from '../docker.js';\nimport { createDockerSyncTransport } from './sync-transport.js';\nimport type { BoxRecord } from '../state.js';\n\n// Env/config-file sync moved to the shared concern (`@agentbox/sandbox-core`'s\n// sync/concerns/env). Re-exported here so existing importers (wizard,\n// download*, the scan test) keep their `@agentbox/sandbox-docker` import site.\nexport {\n DEFAULT_ENV_PATTERNS,\n scanHostEnvFiles,\n buildHostEnvFindArgs,\n} from '@agentbox/sandbox-core';\n\nexport type DockerEngine = 'orbstack' | 'docker-desktop' | 'other';\n\n/** In-container path bind-mounted to the per-box host export dir by createBox. */\nexport const CONTAINER_EXPORT_MERGED = '/host-export';\n\nexport interface HostPaths {\n /** Per-box runtime dir on host, e.g. ~/.agentbox/boxes/<id>. */\n boxDir: string;\n /** Snapshot target for the merged /workspace view (rsync'd in by `refreshExport`). */\n mergedExport: string;\n}\n\nlet cachedEngine: DockerEngine | null = null;\nlet engineOverride: DockerEngine | null = null;\n\n/**\n * The user's `engine.kind` pin, when it is not `auto`. Read here rather than\n * pushed in from the CLI entrypoint: the hub creates boxes and mints their\n * URLs too, and a pin only the CLI honored was a pin the boxes ignored. Loaded\n * from `process.cwd()` for parity with every other config read; `engine.kind`\n * is a host-level setting, so in practice that resolves to the global layer.\n */\nasync function pinnedEngine(): Promise<DockerEngine | null> {\n try {\n const { loadEffectiveConfig } = await import('@agentbox/config');\n const loaded = await loadEffectiveConfig(process.cwd());\n const kind = loaded.effective.engine.kind;\n return kind === 'auto' ? null : kind;\n } catch {\n return null; // a broken config must not break box lifecycle; `agentbox config` reports it\n }\n}\n\n/**\n * Which docker engine this host runs, deciding the host-side conventions that\n * differ between them (a box's `.orb.local` URL, Portless, volume paths).\n * `docker info --format '{{.OperatingSystem}}'` returns strings like \"OrbStack\"\n * or \"Docker Desktop\" — the only two that matter on macOS. An `engine.kind`\n * pin wins over the probe.\n *\n * Resolved ONCE per process. Switching engines is a thing people do about\n * never, so the cost of noticing (a `docker info` on a live timer, in every\n * process that touches docker) is not worth paying; the long-lived processes —\n * `agentbox hub`, `agentbox relay` — pick up a switch when they are restarted,\n * which is also what makes their answer stable for as long as they run.\n */\nexport async function detectEngine(): Promise<DockerEngine> {\n if (engineOverride !== null) return engineOverride;\n if (cachedEngine !== null) return cachedEngine;\n const pinned = await pinnedEngine();\n if (pinned !== null) {\n cachedEngine = pinned;\n return cachedEngine;\n }\n const result = await execa('docker', ['info', '--format', '{{.OperatingSystem}}'], {\n reject: false,\n });\n const os = (result.stdout ?? '').trim().toLowerCase();\n if (os.includes('orbstack')) cachedEngine = 'orbstack';\n else if (os.includes('docker desktop')) cachedEngine = 'docker-desktop';\n else cachedEngine = 'other';\n return cachedEngine;\n}\n\n/**\n * Pin the engine for the rest of the process, bypassing both the config pin and\n * the `docker info` probe. Tests only — the user-facing pin is `engine.kind`,\n * which {@link detectEngine} reads itself. `null` clears the pin and the cache.\n */\nexport function setEngineOverride(engine: DockerEngine | null): void {\n engineOverride = engine;\n cachedEngine = null;\n}\n\n/** @deprecated alias for `setEngineOverride`; kept so existing tests don't churn. */\nexport function __setEngineForTesting(engine: DockerEngine | null): void {\n setEngineOverride(engine);\n}\n\n/**\n * The active Docker context name — `docker context show` (which honors the\n * `DOCKER_CONTEXT` / `DOCKER_HOST` overrides and `~/.docker/config.json`'s\n * `currentContext`). Embedded in the VS Code attached-container URI so the\n * Dev Containers extension talks to the same daemon agentbox used — without\n * it, switching engines (OrbStack ⇄ Docker Desktop) makes the extension probe\n * the wrong daemon. Best-effort: returns undefined if the probe fails.\n */\nexport async function getDockerContext(): Promise<string | undefined> {\n const result = await execa('docker', ['context', 'show'], { reject: false });\n if (result.exitCode !== 0) return undefined;\n const ctx = (result.stdout ?? '').trim();\n return ctx.length > 0 ? ctx : undefined;\n}\n\nexport const BOXES_ROOT = join(homedir(), '.agentbox', 'boxes');\n\n/** Box-identity subset every dir helper accepts. Structurally compatible with\n * `BoxRecord`, but only the fields the segment needs. `projectIndex` is the\n * 1-based per-project number (`agentbox list`'s `N` column); when present, it\n * appears between the id and the mnemonic so dir listings sort cleanly within\n * a project and the segment matches `agentbox <cmd> <n>` intuitively. Legacy\n * (pre-feature) boxes lack it and keep the original `<id>-<mnemonic>` shape.\n */\nexport interface BoxDirRef {\n id: string;\n name: string;\n projectIndex?: number;\n}\n\n/** On-disk dir segment for a box: `<id>-<n>-<mnemonic>` (or `<id>-<mnemonic>` legacy). */\nexport function boxDirSegment(box: BoxDirRef): string {\n const mnemonic = sanitizeMnemonic(box.name);\n const n = box.projectIndex;\n if (typeof n === 'number' && Number.isFinite(n) && n > 0) {\n return `${box.id}-${String(n)}-${mnemonic}`;\n }\n return `${box.id}-${mnemonic}`;\n}\n\nexport function boxRunDirFor(box: BoxDirRef): string {\n return join(BOXES_ROOT, boxDirSegment(box));\n}\n\n/**\n * Per-box durable status file. The host relay writes it (atomic tmp+rename)\n * when the in-box daemon pushes a `box-status` snapshot; it persists here on\n * the host fs even while the box is paused/stopped. Path must stay in sync\n * with `boxStatusPathFor` in @agentbox/relay's status-store.\n */\nexport function boxStatusPathFor(box: BoxDirRef): string {\n return join(boxRunDirFor(box), 'status.json');\n}\n\n/**\n * Read the persisted box status, or null when there is none (box predates the\n * feature, relay never received a push, corrupt JSON, or a future-incompatible\n * schema). Never throws — callers fall back to live/“unknown”.\n *\n * The agent map is reconstructed on read. The relay normalizes at ingestion, so\n * a freshly-written file already has one — but a file written by an older relay\n * is still sitting on disk for every box that existed before this build, and it\n * carries only the named `claude`/`codex`/`opencode` blocks.\n */\nexport async function readBoxStatus(box: BoxDirRef): Promise<BoxStatus | null> {\n try {\n const raw = await readFile(boxStatusPathFor(box), 'utf8');\n const parsed = JSON.parse(raw) as BoxStatus;\n if (parsed.schema !== 1) return null;\n const agents = normalizeAgentStatus(parsed);\n return Object.keys(agents).length > 0 ? { ...parsed, agents } : parsed;\n } catch {\n return null;\n }\n}\n\n/**\n * Host path to a subpath inside an OrbStack-managed named volume.\n *\n * OrbStack exposes named volumes at `~/OrbStack/docker/volumes/<name>/` —\n * NO `_data` wrapper. `docker volume inspect` reports the in-VM mountpoint\n * instead, which isn't reachable from macOS. Returns the path regardless of\n * whether it exists; callers stat it themselves. Used by claude's plugin-cache\n * pre-scan to find host-visible package.jsons on OrbStack.\n */\nexport function orbstackVolumePath(volume: string, ...sub: string[]): string {\n return join(homedir(), 'OrbStack', 'docker', 'volumes', volume, ...sub);\n}\n\nexport async function getHostPaths(\n record: Pick<BoxRecord, 'id' | 'name' | 'projectIndex'>,\n): Promise<HostPaths> {\n const boxDir = boxRunDirFor(record);\n return {\n boxDir,\n mergedExport: join(boxDir, 'workspace'),\n };\n}\n\nexport interface RefreshOptions {\n /** When true, include /workspace/node_modules in the merged export. Off by default. */\n includeNodeModules?: boolean;\n}\n\nexport interface RefreshResult {\n /** Host path that now reflects the box's current state. */\n hostPath: string;\n /** True when an rsync copy actually ran (always true today; kept for callers). */\n copied: boolean;\n /** True when the box predates the /host-export bind and we used the tar-pipe fallback. */\n usedFallback: boolean;\n}\n\nasync function hasContainerPath(container: string, path: string): Promise<boolean> {\n const probe = await execInBox(container, ['test', '-d', path], { user: 'root' });\n return probe.exitCode === 0;\n}\n\n/**\n * Refresh the per-box merged host export (~/.agentbox/boxes/<id>/workspace) so\n * Finder sees the box's current `/workspace`. /workspace lives in the\n * container's writable layer and is invisible to macOS directly, so we always\n * have to copy it out. Prefers rsync via the /host-export bind-mount; falls\n * back to a `tar | tar` pipe through `docker exec` for boxes that predate the\n * bind.\n */\n/**\n * What the box→scratch mirror leaves behind, as rsync/tar `--exclude` patterns.\n *\n * THE INVARIANT: the mirror must be a SUPERSET of the selection. A superset\n * costs nothing — `rsync --files-from` simply ignores the extra files — while a\n * subset is fatal, because a selected path that is not in the mirror makes rsync\n * exit 23 and takes the whole download with it. That is exactly what happened\n * when a repo did not gitignore `node_modules`: git listed it, this mirror had\n * dropped it.\n *\n * So the mirror may keep on copying `.git`, `media/`, state dirs and sqlite\n * files that the selection then drops — but it may only drop `node_modules` when\n * the selection drops it too, which is why both sides now read the same flag\n * through this one function.\n */\nexport function exportMirrorExcludes(opts: RefreshOptions = {}): string[] {\n return opts.includeNodeModules ? [] : ['node_modules'];\n}\n\nexport async function refreshExport(\n record: Pick<BoxRecord, 'id' | 'name' | 'projectIndex' | 'container'>,\n opts: RefreshOptions = {},\n): Promise<RefreshResult> {\n const paths = await getHostPaths(record);\n const mirrorExcludes = exportMirrorExcludes(opts);\n await mkdir(paths.mergedExport, { recursive: true });\n\n const bindAvailable = await hasContainerPath(record.container, CONTAINER_EXPORT_MERGED);\n if (bindAvailable) {\n const args = ['rsync', '-a', '--delete'];\n for (const e of mirrorExcludes) args.push(`--exclude=${e}`);\n args.push('/workspace/', `${CONTAINER_EXPORT_MERGED}/`);\n const r = await execInBox(record.container, args, { user: 'root' });\n if (r.exitCode !== 0) {\n throw new ExportError(`rsync into ${CONTAINER_EXPORT_MERGED} failed`, r.stdout, r.stderr);\n }\n return { hostPath: paths.mergedExport, copied: true, usedFallback: false };\n }\n\n // Fallback for pre-existing boxes: stream a tar through docker exec into the\n // host target. Slower and skips the in-place delete that rsync gives us, but\n // it works without recreating the container.\n const excludes = mirrorExcludes.map((e) => `--exclude=${e}`);\n const result = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'root',\n record.container,\n 'tar',\n '-cf',\n '-',\n ...excludes,\n '-C',\n '/workspace',\n '.',\n ],\n { reject: false, encoding: 'buffer' },\n );\n if (result.exitCode !== 0) {\n throw new ExportError(\n `tar from /workspace failed`,\n '',\n typeof result.stderr === 'string'\n ? result.stderr\n : (result.stderr as Buffer).toString('utf8'),\n );\n }\n const extract = await execa('tar', ['-xf', '-', '-C', paths.mergedExport], {\n input: result.stdout as Buffer,\n reject: false,\n });\n if (extract.exitCode !== 0) {\n throw new ExportError('tar extract on host failed', extract.stdout, extract.stderr);\n }\n return { hostPath: paths.mergedExport, copied: true, usedFallback: true };\n}\n\n/**\n * Build the in-box `find` argv that enumerates env/config files by basename\n * glob, pruning `ENV_PRUNE_DIRS`. `-printf '%P\\0'` emits NUL-delimited paths\n * already relative to /workspace (so they feed rsync --files-from --from0\n * directly, exactly like `git ls-files -z`).\n */\nfunction buildEnvFindArgs(patterns: string[]): string[] {\n const nameGroup = (names: string[]): string[] => {\n const out: string[] = [];\n names.forEach((n, i) => {\n if (i > 0) out.push('-o');\n out.push('-name', n);\n });\n return out;\n };\n return [\n 'find',\n '/workspace',\n '(',\n '-type',\n 'd',\n '(',\n ...nameGroup(ENV_PRUNE_DIRS),\n ')',\n '-prune',\n ')',\n '-o',\n '(',\n '-type',\n 'f',\n '(',\n ...nameGroup(patterns),\n ')',\n '-printf',\n '%P\\\\0',\n ')',\n ];\n}\n\nexport interface CopyHostEnvOptions {\n /** Target container name (must be running with the overlay mounted). */\n container: string;\n /** Absolute host workspace dir — the same dir that maps to /workspace. */\n workspaceDir: string;\n /** Basename globs to copy (normally DEFAULT_ENV_PATTERNS). */\n patterns: string[];\n onLog?: (line: string) => void;\n}\n\n/**\n * Copy the host's env/config files (selected by `patterns`, gitignore ignored)\n * into the running box's `/workspace`. The reverse of `pullToHost`'s env\n * segment. Writes land in the overlay's writable upper layer (the container is\n * up + mounted at call time), so they survive pause/stop/start.\n *\n * Best-effort: a tar/exec failure or an empty match set logs and returns the\n * count rather than throwing — a missing secret shouldn't abort an otherwise\n * healthy box. Files extract as uid 1000 so they're owned by `vscode` like the\n * rest of /workspace.\n */\nexport async function copyHostEnvFilesToBox(opts: CopyHostEnvOptions): Promise<{ copied: number }> {\n // Thin wrapper over the shared env concern: same host-side find + tar pack,\n // with the docker transport's `applyTarball` reproducing the exact\n // `docker exec -i --user 1000:1000 tar -xf - -C /workspace` extract.\n const ctx = makeSyncContext({\n boxName: '',\n boxId: '',\n provider: 'docker',\n hostWorkspace: opts.workspaceDir,\n onLog: opts.onLog,\n });\n const transport = createDockerSyncTransport({ container: opts.container });\n return pushEnvFiles(ctx, transport, opts.patterns);\n}\n\nexport interface CopyHostFilesOptions {\n /** Target container name (must be running). */\n container: string;\n /** Absolute host workspace dir — the same dir that maps to /workspace. */\n workspaceDir: string;\n /** Relative paths (to workspaceDir) to copy. NUL-safe; no glob expansion. */\n files: string[];\n onLog?: (line: string) => void;\n}\n\n/**\n * Sibling to `copyHostEnvFilesToBox` that skips the `find` scan and trusts a\n * pre-vetted file list (e.g. the user's multiselect picks from the wizard).\n * Same tar-pipe body: tar reads the NUL-delimited list on stdin and pipes into\n * `docker exec tar -x`. Best-effort error handling — a tar/exec failure logs\n * and returns the count rather than throwing.\n */\nexport async function copyHostFilesToBox(opts: CopyHostFilesOptions): Promise<{ copied: number }> {\n const log = opts.onLog ?? (() => {});\n // Normalise — drop any leading \"./\" so the in-container extract lands at the\n // right path, and drop empties so a stray trailing NUL doesn't become `tar: ''`.\n const list = opts.files.map((p) => p.replace(/^\\.\\//, '')).filter((p) => p.length > 0);\n if (list.length === 0) return { copied: 0 };\n\n const packed = await execa('tar', ['-C', opts.workspaceDir, '--null', '-T', '-', '-cf', '-'], {\n input: list.join('\\0'),\n encoding: 'buffer',\n reject: false,\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs.\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n if (packed.exitCode !== 0) {\n log(`warning: env-file tar pack failed: ${String(packed.stderr).slice(0, 300)}`);\n return { copied: 0 };\n }\n const extract = await execa(\n 'docker',\n ['exec', '-i', '--user', '1000:1000', opts.container, 'tar', '-xf', '-', '-C', '/workspace'],\n { input: packed.stdout as Buffer, reject: false },\n );\n if (extract.exitCode !== 0) {\n log(`warning: env-file copy into box failed: ${String(extract.stderr).slice(0, 300)}`);\n return { copied: 0 };\n }\n return { copied: list.length };\n}\n\nexport interface PullOptions {\n /** Default true. When false, skip git ls-files and use the static exclude-list. */\n respectGitignore?: boolean;\n /** Default false. When true, keep node_modules — in BOTH git and exclude-list mode. */\n includeNodeModules?: boolean;\n /** Paths the user declined; dropped before copying. */\n skipPaths?: readonly string[];\n /**\n * Where the files land. Defaults to `record.workspacePath` — the user's own\n * working dir, which is what a plain `download` means.\n *\n * `download --backup` overrides it to point at\n * `<project>/.agentbox/bots/<bot>/<stamp>/workspace`. The cloud pull\n * (`pullWorkspaceToHost`) has always taken this as a parameter; this side had\n * it wired to the record, which is the only reason the two paths could not\n * share a caller.\n */\n destDir?: string;\n /** Default false. Skip the initial refreshExport — pull whatever's already in the scratch dir. */\n noRefresh?: boolean;\n /** Default false. Run rsync with --dry-run; return the change list without writing. */\n dryRun?: boolean;\n /**\n * Extra env/config files to pull, selected by these basename globs via an\n * in-box `find` (heavy dirs pruned). Composes WITH gitignore selection: the\n * rsync file list is the union of the git-tracked set (unless\n * respectGitignore is false) and these matches. Empty/undefined = no env\n * segment.\n */\n envPatterns?: string[];\n}\n\nexport interface PullResult {\n /** Absolute host path the pull targeted (`destDir`, else record.workspacePath). */\n hostPath: string;\n /** Per-file rsync change list (itemized `-i` lines, transfers/deletes only). */\n changes: string[];\n /** True when an actual write happened. False on dry-run. */\n applied: boolean;\n /** True when gitignore-mode was used (vs. the fallback exclude-list). */\n usedGitignore: boolean;\n /** Selected paths that were not in the staged copy — reported, not fatal. */\n missing: string[];\n}\n\n/**\n * Reverse of `refreshExport`: bring the box's merged `/workspace` view back\n * into the user's actual host working directory (`record.workspacePath`).\n *\n * Two-stage: (1) `refreshExport` materializes `/workspace` in the per-box\n * scratch dir (`~/.agentbox/boxes/<id>/workspace`) — `/workspace` lives in\n * the container's writable layer, invisible to macOS directly; (2) a\n * host-side rsync copies scratch → `workspacePath`.\n *\n * Filtering: by default we ask git *inside the box* which files it would\n * track (`git ls-files --cached --others --exclude-standard`) so build dirs and\n * gitignored secrets never leak back. Non-git workspaces (or\n * `respectGitignore: false`) fall back to a static `--exclude` list.\n * `node_modules` is dropped in BOTH modes unless `includeNodeModules` says\n * otherwise — the claim that git mode alone kept it out only held for repos that\n * gitignore it, and a repo that does not used to fail the pull outright.\n *\n * Never passes `--delete`: files that exist on the host but not in the box\n * are preserved. Removals are the user's call.\n */\nexport async function pullToHost(\n record: Pick<BoxRecord, 'id' | 'name' | 'projectIndex' | 'container' | 'workspacePath'>,\n opts: PullOptions = {},\n): Promise<PullResult> {\n const paths = await getHostPaths(record);\n\n let scratchDir: string;\n if (opts.noRefresh) {\n scratchDir = paths.mergedExport;\n await mkdir(scratchDir, { recursive: true });\n } else {\n const refreshed = await refreshExport(record, {\n includeNodeModules: opts.includeNodeModules,\n });\n scratchDir = refreshed.hostPath;\n }\n\n // The rsync file list is the union of up to two independent NUL-delimited\n // segments: the PRIMARY selection (git-tracked when /workspace is a repo, else\n // the exclude-list `find`) and the env-pattern one (gitignore bypassed). Both\n // segments come from the box, so what lands on the host is what the box has.\n //\n // The primary segment is built by the shared `buildWorkspaceListScript` — the\n // same script the cloud pull runs — so a non-git workspace gets the same\n // exclude defaults (live databases, `media/`, agent state dirs) on every\n // provider instead of docker's old bare `--exclude=.git,node_modules`.\n const excludes = workspaceExcludes({ includeNodeModules: opts.includeNodeModules });\n const listed = await execInBox(\n record.container,\n [\n 'bash',\n '-c',\n buildWorkspaceListScript({\n respectGitignore: opts.respectGitignore,\n excludes,\n includeNodeModules: opts.includeNodeModules,\n }),\n ],\n { user: 'root' },\n );\n if (listed.exitCode !== 0) {\n throw new ExportError('workspace file list in box failed', listed.stdout, listed.stderr);\n }\n const primary = parseWorkspaceList(listed.stdout);\n const selected = new Set(primary.paths);\n const usedGitignore = primary.mode === 'git';\n\n if (opts.envPatterns && opts.envPatterns.length > 0) {\n const found = await execInBox(record.container, buildEnvFindArgs(opts.envPatterns), {\n user: 'root',\n });\n if (found.exitCode !== 0) {\n throw new ExportError('find env files in box failed', found.stdout, found.stderr);\n }\n for (const p of found.stdout.split('\\0')) {\n if (p.length > 0) selected.add(p);\n }\n }\n const fileList = selected.size > 0 ? [...selected].join('\\0') : null;\n\n const destDir = opts.destDir ?? record.workspacePath;\n const { changes, applied, missing } = await rsyncPullToHost({\n scratchDir,\n destDir,\n fileList,\n excludes,\n dryRun: opts.dryRun,\n skipPaths: opts.skipPaths,\n });\n return { hostPath: destDir, changes, applied, usedGitignore, missing };\n}\n\nexport interface OpenOptions extends RefreshOptions {\n /** When true, skip rsync and just open whatever's already on disk. */\n noRefresh?: boolean;\n /** When true, refresh as usual but don't launch macOS `open` on the resulting path. */\n noOpen?: boolean;\n}\n\nexport interface OpenResult {\n hostPath: string;\n copied: boolean;\n usedFallback: boolean;\n engine: DockerEngine;\n}\n\n/**\n * Refresh the merged export (unless suppressed) and launch the macOS `open`\n * command on it. Returns the host path that was opened.\n *\n * Set `noOpen: true` to refresh and return the path without launching\n * Finder — used by `agentbox open --path` so scripted callers get a fresh\n * path in one call.\n */\nexport async function openInFinder(\n record: Pick<BoxRecord, 'id' | 'name' | 'projectIndex' | 'container'>,\n opts: OpenOptions,\n): Promise<OpenResult> {\n const engine = await detectEngine();\n let hostPath: string;\n let copied = false;\n let usedFallback = false;\n\n if (opts.noRefresh) {\n const paths = await getHostPaths(record);\n hostPath = paths.mergedExport;\n await mkdir(hostPath, { recursive: true });\n } else {\n const refreshed = await refreshExport(record, opts);\n hostPath = refreshed.hostPath;\n copied = refreshed.copied;\n usedFallback = refreshed.usedFallback;\n }\n\n if (!opts.noOpen) {\n const opened = await execa(hostOpenCommand(), [hostPath], { reject: false });\n if (opened.exitCode !== 0) {\n throw new ExportError(`open ${hostPath} failed`, opened.stdout, opened.stderr);\n }\n }\n\n return { hostPath, copied, usedFallback, engine };\n}\n\nexport class ExportError extends Error {\n constructor(\n message: string,\n public readonly stdout: string,\n public readonly stderr: string,\n ) {\n super(`${message}${stderr ? `: ${stderr.trim()}` : ''}`);\n this.name = 'ExportError';\n }\n}\n\nexport interface CopyCarryOptions {\n /** Running container name. */\n container: string;\n /** Resolved + approved carry entries. */\n entries: ResolvedCarryEntry[];\n onLog?: (line: string) => void;\n}\n\nexport interface CopyCarryResult {\n copied: number;\n errors: string[];\n /** Audit summary for BoxRecord.carry. `hash` is the host source content hash at copy time. */\n applied: Array<{ src: string; dest: string; bytes: number; hash?: string }>;\n}\n\n/**\n * Content hash of a carry source, used by the on-start resync to re-copy only\n * entries whose host source changed. Files hash their bytes; dirs hash a\n * deterministic manifest of (relpath, size, mtime). Returns undefined on a read\n * error (treated as \"changed\" so a re-copy is attempted). `missing` → undefined.\n */\nexport async function carrySourceHash(entry: ResolvedCarryEntry): Promise<string | undefined> {\n if (entry.kind === 'missing') return undefined;\n try {\n if (entry.kind === 'file') {\n return createHash('sha256')\n .update(await readFile(entry.absSrc))\n .digest('hex');\n }\n // Hash file *content* (not mtime) so a touch with identical content doesn't\n // trigger a spurious re-copy. Skip the same paths the copy step excludes so\n // the hash tracks only what actually lands in the box (and so resync isn't\n // dragged through heavy excluded subtrees like node_modules).\n const exclude = entry.exclude ?? [];\n const h = createHash('sha256');\n const walk = async (dir: string, rel: string): Promise<void> => {\n const names = (await readdir(dir)).sort();\n for (const name of names) {\n const relPath = rel ? `${rel}/${name}` : name;\n if (carryRelExcluded(relPath, exclude)) continue;\n const abs = join(dir, name);\n const st = await stat(abs);\n if (st.isDirectory()) {\n h.update(`d\\0${relPath}\\n`);\n await walk(abs, relPath);\n } else {\n h.update(`f\\0${relPath}\\0`);\n h.update(await readFile(abs));\n h.update('\\n');\n }\n }\n };\n await walk(entry.absSrc, '');\n return h.digest('hex');\n } catch {\n return undefined;\n }\n}\n\n/**\n * Mirror the tar `--exclude` patterns on `entry.exclude` for the source-hash\n * walk so it tracks the same fileset the copy step packs. Bare names (and the\n * `*/name` form `toTarExcludes` emits) match a path component; richer globs are\n * matched against the full relpath.\n */\nfunction carryRelExcluded(relPath: string, patterns: string[]): boolean {\n if (patterns.length === 0) return false;\n const segs = relPath.split('/');\n for (const p of patterns) {\n const isGlob = p.includes('*') || p.includes('?');\n if (!isGlob) {\n if (segs.includes(p)) return true;\n } else if (p.startsWith('*/') && !/[*?/]/.test(p.slice(2))) {\n if (segs.includes(p.slice(2))) return true;\n } else {\n const re = new RegExp(\n `^${p\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.')}$`,\n );\n if (re.test(relPath)) return true;\n }\n }\n return false;\n}\n\n/**\n * Apply the `carry:` block: copy each host path to its declared in-box dest.\n * Per-entry tar pipe (not muxed onto one stream) because each entry has its\n * own dest. `~/` in `absDest` is expanded inside the container via `$HOME` —\n * never on the host — so the box's vscode home (`/home/vscode`) is the\n * reference, not the user's macOS home.\n *\n * Files: tar a single regular file (preserves mode) and extract at the parent\n * of dest, renamed to the basename of dest. Dirs: tar the directory contents\n * (after `cd src`) and extract into the dest path (which is created with\n * `mkdir -p`). Both extracts pass `--no-same-permissions --no-same-owner` so\n * macOS attrs don't leak in; a recursive `chmod` runs when `mode` is set.\n *\n * `missing` entries (optional + absent on host) are silently skipped.\n * Per-entry failures are recorded in `errors` and the function returns rather\n * than throwing — the box stays usable; the caller logs the misses.\n */\nexport async function copyCarryPathsToBox(opts: CopyCarryOptions): Promise<CopyCarryResult> {\n const log = opts.onLog ?? (() => {});\n let copied = 0;\n const errors: string[] = [];\n const applied: CopyCarryResult['applied'] = [];\n\n for (const [i, entry] of opts.entries.entries()) {\n const where = `carry[${String(i)}] \"${entry.rawSrc}\"`;\n if (entry.kind === 'missing') {\n log(`${where}: skipped (missing on host, optional)`);\n continue;\n }\n try {\n await copyOneEntry(opts.container, entry);\n copied += 1;\n applied.push({\n src: entry.absSrc,\n dest: entry.absDest,\n bytes: entry.bytes ?? 0,\n hash: await carrySourceHash(entry),\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n errors.push(`${where}: ${msg}`);\n log(`${where}: failed: ${msg}`);\n }\n }\n\n return { copied, errors, applied };\n}\n\nasync function copyOneEntry(container: string, entry: ResolvedCarryEntry): Promise<void> {\n // Shared, byte-for-byte carry decisions (~/ expansion, file-vs-dir, exclude,\n // owner/mode defaults, rename-needed, parent-chain-needed) — see\n // `@agentbox/sandbox-core`'s files concern. `~/` is expanded host-side, NOT\n // inside the box's shell, so we never depend on the executing user's $HOME\n // (which is /root when we `--user 0:0` below).\n const plan = planCarryEntry(entry);\n if (!plan) return; // missing (optional + absent on host)\n const {\n boxDest,\n parentDir,\n exclude,\n chownArgs,\n mode,\n fileBase,\n renameNeeded,\n parentChainNeeded,\n } = plan;\n\n // Pre-create the dest's parent dir. Run as root so destinations outside\n // /home/vscode work; we re-chown to vscode if the dest is in $HOME.\n const mkdir = await execa(\n 'docker',\n ['exec', '--user', '0:0', container, 'mkdir', '-p', parentDir],\n { reject: false },\n );\n if (mkdir.exitCode !== 0) {\n throw new Error(`mkdir -p ${parentDir} failed: ${String(mkdir.stderr).slice(0, 300)}`);\n }\n\n if (!plan.isDir) {\n // `docker cp` cannot write into the bind-mounted /workspace (it fails with a\n // tar \"read/write on closed pipe\"). Stream the file through `docker exec\n // tar -x` instead — that extracts from *inside* the container, through the\n // normal filesystem, exactly like the dir path below. tar archives by the\n // source basename, so rename in-box afterwards when the dest name differs.\n const srcDir = dirname(entry.absSrc);\n const [packed, extract] = await streamTarPipe(\n 'tar',\n ['-C', srcDir, '-cf', '-', fileBase],\n 'docker',\n [\n 'exec',\n '-i',\n '--user',\n '0:0',\n container,\n 'tar',\n '-xf',\n '-',\n '-C',\n parentDir,\n '--no-same-permissions',\n '--no-same-owner',\n '-m',\n ],\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs.\n { ...process.env, COPYFILE_DISABLE: '1' },\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack failed: ${String(packed.stderr).slice(0, 300)}`);\n }\n if (extract.exitCode !== 0) {\n throw new Error(`tar extract failed: ${String(extract.stderr).slice(0, 300)}`);\n }\n if (renameNeeded) {\n const mv = await execa(\n 'docker',\n ['exec', '--user', '0:0', container, 'mv', '-f', `${parentDir}/${fileBase}`, boxDest],\n { reject: false },\n );\n if (mv.exitCode !== 0) {\n throw new Error(`rename to ${boxDest} failed: ${String(mv.stderr).slice(0, 300)}`);\n }\n }\n } else {\n // Tar the directory contents (cd in + tar .) so they extract at the\n // dest without a duplicated basename layer. --no-same-permissions /\n // --no-same-owner so macOS attrs don't leak into the linux box.\n // Stream the tarball straight into the box (see streamTarPipe — a buffered\n // round-trip hits execa's 100 MB maxBuffer and silently fails on any\n // sizable carry source). `exclude` drops heavy/regenerable subtrees.\n const excludeArgs = exclude.map((p) => `--exclude=${p}`);\n const [packed, extract] = await streamTarPipe(\n 'tar',\n ['-C', entry.absSrc, '-cf', '-', ...excludeArgs, '.'],\n 'docker',\n [\n 'exec',\n '-i',\n '--user',\n '0:0',\n container,\n 'tar',\n '-xf',\n '-',\n '-C',\n boxDest,\n '--no-same-permissions',\n '--no-same-owner',\n '-m',\n ],\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs.\n { ...process.env, COPYFILE_DISABLE: '1' },\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack failed: ${String(packed.stderr).slice(0, 300)}`);\n }\n if (extract.exitCode !== 0) {\n throw new Error(`tar extract failed: ${String(extract.stderr).slice(0, 300)}`);\n }\n }\n\n if (mode) {\n const chmod = await execa(\n 'docker',\n ['exec', '--user', '0:0', container, 'chmod', '-R', mode, boxDest],\n { reject: false },\n );\n if (chmod.exitCode !== 0) {\n throw new Error(`chmod failed: ${String(chmod.stderr).slice(0, 300)}`);\n }\n }\n\n // Always chown explicitly so the result is predictable across providers.\n // Default targets the box user via `--reference=/home/vscode` (uid 1000 here,\n // but the plan is shared with providers where it isn't); `user: 0` lands\n // explicit root:root. (The explicit chown matters for docker regardless —\n // without it the host's macOS uid/gid leaks through into the container.)\n const chown = await execa(\n 'docker',\n ['exec', '--user', '0:0', container, 'chown', '-R', ...chownArgs, boxDest],\n { reject: false },\n );\n if (chown.exitCode !== 0) {\n throw new Error(`chown failed: ${String(chown.stderr).slice(0, 300)}`);\n }\n\n // Parent-chain chown: `mkdir -p` above ran as root, so any new dirs\n // between $HOME and dirname(boxDest) are root-owned even though the\n // leaf is now uid-owned. Walk back up to $HOME (exclusive) and chown\n // each. Only walk when dest is under $HOME — for destinations like\n // /etc/* or /opt/*, leave system parents alone.\n if (parentChainNeeded) {\n const safeDest = boxDest.replace(/'/g, `'\\\\''`);\n const script =\n `set -e; parent=\"$(dirname '${safeDest}')\"; ` +\n `while [ \"$parent\" != \"${BOX_HOME}\" ] && [ \"$parent\" != \"/\" ]; do ` +\n `chown ${chownArgs.join(' ')} \"$parent\"; ` +\n `parent=\"$(dirname \"$parent\")\"; ` +\n `done`;\n const chownParents = await execa(\n 'docker',\n ['exec', '--user', '0:0', container, 'bash', '-c', script],\n { reject: false },\n );\n if (chownParents.exitCode !== 0) {\n throw new Error(`chown parents failed: ${String(chownParents.stderr).slice(0, 300)}`);\n }\n }\n}\n","/**\n * Docker provider's symmetric host↔box file-copy primitives. Mirrors\n * `cloud-cp.ts` in `@agentbox/sandbox-cloud` so both providers expose the same\n * `uploadPath` / `downloadPath` capability.\n *\n * `docker cp` can't see through the `/workspace` overlay mount AgentBox boxes\n * set up (the file lands in the image layer beneath the mount and is invisible\n * to the running container). Everything goes through `docker exec tar`, which\n * runs inside the container's mount namespace — same mounts the in-box agent\n * sees.\n */\n\nimport { existsSync, mkdirSync, renameSync, statSync } from 'node:fs';\nimport { basename, dirname, posix, resolve } from 'node:path';\nimport { execa } from 'execa';\nimport type { BoxRecord } from '@agentbox/core';\n\n/** In-box home for the agent user; boxes always run as `vscode` (uid 1000). */\nconst BOX_HOME = '/home/vscode';\n\nfunction posixDirname(p: string): string {\n return posix.dirname(p) || '/';\n}\n\n/**\n * `execa({ encoding: 'buffer' })` returns stderr as a `Buffer`; `String(buf)`\n * on Node 20+ stringifies it as a comma-joined byte list, so error messages\n * come out as e.g. `116,97,114,…` instead of text. Decode explicitly.\n */\nfunction asText(s: string | Uint8Array | undefined): string {\n if (s === undefined) return '';\n if (typeof s === 'string') return s;\n return Buffer.from(s).toString('utf8');\n}\n\nexport interface BoxCpResult {\n finalPath: string;\n /** Non-fatal warning the caller may want to surface (e.g. chown failed). */\n warn?: string;\n}\n\n/** `--exclude=<pat>` args for each tar pattern (already expanded by the caller). */\nfunction tarExcludeArgs(exclude: string[] | undefined): string[] {\n return (exclude ?? []).map((p) => `--exclude=${p}`);\n}\n\n/**\n * Stream a tar producer into a tar consumer without buffering. execa buffers\n * each subprocess' stdout into memory by default and caps it at 100 MB\n * (`maxBuffer`), which silently kills the producer (\"tar: Write error\") on any\n * sizable copy — so we disable stdout buffering on the producer and pipe the\n * raw stream into the consumer's stdin. stderr stays buffered for diagnostics.\n * Returns both results; callers check exit codes producer-first.\n */\ninterface ProcOutcome {\n exitCode: number | undefined;\n stderr: string | Uint8Array | undefined;\n}\n\nexport async function streamTarPipe(\n producerFile: string,\n producerArgs: string[],\n consumerFile: string,\n consumerArgs: string[],\n producerEnv?: NodeJS.ProcessEnv,\n): Promise<[ProcOutcome, ProcOutcome]> {\n const producer = execa(producerFile, producerArgs, {\n reject: false,\n buffer: { stdout: false },\n ...(producerEnv ? { env: producerEnv } : {}),\n });\n const consumer = execa(consumerFile, consumerArgs, {\n reject: false,\n buffer: { stdout: false },\n });\n producer.stdout?.pipe(consumer.stdin!);\n const [p, c] = await Promise.all([producer, consumer]);\n return [\n { exitCode: p.exitCode, stderr: p.stderr },\n { exitCode: c.exitCode, stderr: c.stderr },\n ];\n}\n\nasync function uploadOneToBox(\n box: BoxRecord,\n hostSrc: string,\n boxDst: string,\n exclude?: string[],\n): Promise<BoxCpResult> {\n const srcAbs = resolve(hostSrc);\n if (!existsSync(srcAbs)) throw new Error(`source not found: ${hostSrc}`);\n const srcBasename = basename(srcAbs);\n const srcParent = dirname(srcAbs);\n\n // Decide box parent dir + final name (docker cp semantics):\n // - trailing `/` → dst is a directory; src lands as <dst>/<srcBasename>\n // - dst exists as a dir in box → same\n // - else dst is the full target path; rename during extraction\n let boxParent: string;\n let finalName: string;\n if (boxDst.endsWith('/')) {\n boxParent = boxDst.replace(/\\/+$/, '') || '/';\n finalName = srcBasename;\n } else {\n const isDir = await execa('docker', ['exec', box.container, 'test', '-d', boxDst], {\n reject: false,\n });\n if (isDir.exitCode === 0) {\n boxParent = boxDst.replace(/\\/+$/, '') || '/';\n finalName = srcBasename;\n } else {\n boxParent = posixDirname(boxDst);\n finalName = posix.basename(boxDst);\n }\n }\n const finalPath = boxParent === '/' ? `/${finalName}` : `${boxParent}/${finalName}`;\n\n const mk = await execa(\n 'docker',\n ['exec', '--user', 'root', box.container, 'mkdir', '-p', boxParent],\n { reject: false },\n );\n if (mk.exitCode !== 0) {\n throw new Error(`mkdir -p ${boxParent} in box failed: ${asText(mk.stderr).slice(0, 300)}`);\n }\n\n // Stream the tarball straight from host `tar` into the box's `tar -xf -`\n // instead of buffering it (see streamTarPipe — execa's 100 MB maxBuffer\n // otherwise silently fails large copies with \"tar: Write error\").\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs.\n const [packed, extracted] = await streamTarPipe(\n 'tar',\n ['-C', srcParent, '-cf', '-', ...tarExcludeArgs(exclude), srcBasename],\n 'docker',\n ['exec', '-i', '--user', 'root', box.container, 'tar', '-xf', '-', '-C', boxParent],\n { ...process.env, COPYFILE_DISABLE: '1' },\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack failed: ${asText(packed.stderr).slice(0, 300)}`);\n }\n if (extracted.exitCode !== 0) {\n throw new Error(`tar extract in box failed: ${asText(extracted.stderr).slice(0, 300)}`);\n }\n\n if (finalName !== srcBasename) {\n const initial = boxParent === '/' ? `/${srcBasename}` : `${boxParent}/${srcBasename}`;\n const mv = await execa(\n 'docker',\n ['exec', '--user', 'root', box.container, 'mv', initial, finalPath],\n { reject: false },\n );\n if (mv.exitCode !== 0) {\n throw new Error(\n `rename ${initial} -> ${finalPath} in box failed: ${asText(mv.stderr).slice(0, 300)}`,\n );\n }\n }\n\n const chown = await execa(\n 'docker',\n ['exec', '--user', 'root', box.container, 'chown', '-R', '1000:1000', finalPath],\n { reject: false },\n );\n if (chown.exitCode !== 0) {\n return {\n finalPath,\n warn: `chown ${finalPath} to vscode (uid 1000) failed; ownership inside the box may be root.`,\n };\n }\n\n // Parent-chain chown: `mkdir -p` ran as root, so any new dirs between $HOME\n // and the landed path are root-owned. When the dest is under the box home,\n // walk back up to $HOME (exclusive) and chown each so the agent (vscode) can\n // write siblings — e.g. session-teleport lands a rollout under\n // `~/.codex/sessions/YYYY/MM/DD/` and Codex must then create its\n // `state_*.sqlite` index in that subtree. Non-fatal (matches the warn-only\n // policy of the chown above).\n // Strictly *under* home (trailing segment) — never `=== BOX_HOME`, else the\n // walk's `dirname` would be `/home` and could reassign `/home` itself.\n if (finalPath.startsWith(BOX_HOME + '/')) {\n const walk = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'root',\n box.container,\n 'sh',\n '-c',\n `parent=$(dirname \"$1\"); ` +\n `while [ \"$parent\" != \"$2\" ] && [ \"$parent\" != \"/\" ]; do ` +\n `chown 1000:1000 \"$parent\" || true; ` +\n `parent=$(dirname \"$parent\"); ` +\n `done`,\n 'sh',\n finalPath,\n BOX_HOME,\n ],\n { reject: false },\n );\n if (walk.exitCode !== 0) {\n return {\n finalPath,\n warn: `chown of parent dirs under ${BOX_HOME} failed; some may remain root-owned.`,\n };\n }\n }\n return { finalPath };\n}\n\nasync function downloadOneFromBox(\n box: BoxRecord,\n boxSrc: string,\n hostDst: string,\n exclude?: string[],\n): Promise<BoxCpResult> {\n const srcBasename = posix.basename(boxSrc);\n const srcParent = posixDirname(boxSrc);\n\n const dstAbs = resolve(hostDst);\n let hostParent: string;\n let finalName: string;\n const dstExists = existsSync(dstAbs);\n if (hostDst.endsWith('/') || (dstExists && statSync(dstAbs).isDirectory())) {\n hostParent = dstAbs;\n finalName = srcBasename;\n } else {\n hostParent = dirname(dstAbs);\n finalName = basename(dstAbs);\n }\n mkdirSync(hostParent, { recursive: true });\n const finalPath = posix.join(hostParent, finalName);\n\n // Stream box `tar` → host `tar -xf -` (see streamTarPipe for why we don't buffer).\n const [packed, extracted] = await streamTarPipe(\n 'docker',\n [\n 'exec',\n box.container,\n 'tar',\n '-C',\n srcParent,\n '-cf',\n '-',\n ...tarExcludeArgs(exclude),\n srcBasename,\n ],\n 'tar',\n ['-xf', '-', '-C', hostParent],\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack in box failed: ${asText(packed.stderr).slice(0, 300)}`);\n }\n if (extracted.exitCode !== 0) {\n throw new Error(`tar extract on host failed: ${asText(extracted.stderr).slice(0, 300)}`);\n }\n\n if (finalName !== srcBasename) {\n renameSync(posix.join(hostParent, srcBasename), finalPath);\n }\n return { finalPath };\n}\n\n/** `docker exec test -d` — true when `p` is a directory inside the box. */\nasync function boxIsDir(container: string, p: string): Promise<boolean> {\n const r = await execa('docker', ['exec', container, 'test', '-d', p], { reject: false });\n return r.exitCode === 0;\n}\n\n/**\n * Resolve the box-side destination *directory* for a multi-source copy. With\n * ≥2 sources the destination must be a directory (POSIX `cp`/`scp`): a trailing\n * `/` says so explicitly (and we `mkdir -p` it), otherwise it must already be a\n * directory in the box.\n */\nasync function resolveBoxDestDir(box: BoxRecord, boxDst: string): Promise<string> {\n if (boxDst.endsWith('/')) return boxDst.replace(/\\/+$/, '') || '/';\n if (await boxIsDir(box.container, boxDst)) return boxDst.replace(/\\/+$/, '') || '/';\n throw new Error(\n `cannot copy multiple sources to '${boxDst}': destination is not a directory (add a trailing slash, e.g. ${boxDst}/)`,\n );\n}\n\n/** Group paths by their parent dir so one `tar` invocation packs each group. */\nfunction groupByParent(\n paths: string[],\n dir: (p: string) => string,\n base: (p: string) => string,\n): Map<string, string[]> {\n const groups = new Map<string, string[]>();\n for (const p of paths) {\n const parent = dir(p);\n const arr = groups.get(parent);\n if (arr) arr.push(base(p));\n else groups.set(parent, [base(p)]);\n }\n return groups;\n}\n\n/**\n * Copy one or more host sources into the box. A single source keeps full\n * `docker cp` semantics (rename if the dest is a file path); ≥2 sources land\n * under a destination directory (one `tar` per distinct source parent).\n */\nexport async function uploadToBox(\n box: BoxRecord,\n hostSrcs: string[],\n boxDst: string,\n exclude?: string[],\n): Promise<BoxCpResult> {\n if (hostSrcs.length === 1) return uploadOneToBox(box, hostSrcs[0]!, boxDst, exclude);\n\n const absSrcs = hostSrcs.map((s) => {\n const a = resolve(s);\n if (!existsSync(a)) throw new Error(`source not found: ${s}`);\n return a;\n });\n const boxDir = await resolveBoxDestDir(box, boxDst);\n\n const mk = await execa(\n 'docker',\n ['exec', '--user', 'root', box.container, 'mkdir', '-p', boxDir],\n { reject: false },\n );\n if (mk.exitCode !== 0) {\n throw new Error(`mkdir -p ${boxDir} in box failed: ${asText(mk.stderr).slice(0, 300)}`);\n }\n\n for (const [parent, basenames] of groupByParent(absSrcs, dirname, basename)) {\n const [packed, extracted] = await streamTarPipe(\n 'tar',\n ['-C', parent, '-cf', '-', ...tarExcludeArgs(exclude), ...basenames],\n 'docker',\n ['exec', '-i', '--user', 'root', box.container, 'tar', '-xf', '-', '-C', boxDir],\n { ...process.env, COPYFILE_DISABLE: '1' },\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack failed for ${parent}: ${asText(packed.stderr).slice(0, 300)}`);\n }\n if (extracted.exitCode !== 0) {\n throw new Error(`tar extract in box failed: ${asText(extracted.stderr).slice(0, 300)}`);\n }\n }\n\n // chown each landed entry (never `chown -R` the whole dest dir — that would\n // re-own pre-existing siblings the copy never touched).\n let warn: string | undefined;\n for (const a of absSrcs) {\n const landed = boxDir === '/' ? `/${basename(a)}` : `${boxDir}/${basename(a)}`;\n const chown = await execa(\n 'docker',\n ['exec', '--user', 'root', box.container, 'chown', '-R', '1000:1000', landed],\n { reject: false },\n );\n if (chown.exitCode !== 0) {\n warn = `chown under ${boxDir} to vscode (uid 1000) failed; ownership inside the box may be root.`;\n }\n }\n // Parent-chain chown of the dest dir itself + ancestors back to $HOME (see\n // uploadOneToBox for the rationale). Skipped for system / /workspace dests.\n if (boxDir.startsWith(BOX_HOME + '/')) {\n const walk = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'root',\n box.container,\n 'sh',\n '-c',\n `parent=\"$1\"; ` +\n `while [ \"$parent\" != \"$2\" ] && [ \"$parent\" != \"/\" ]; do ` +\n `chown 1000:1000 \"$parent\" || true; ` +\n `parent=$(dirname \"$parent\"); ` +\n `done`,\n 'sh',\n boxDir,\n BOX_HOME,\n ],\n { reject: false },\n );\n if (walk.exitCode !== 0) {\n warn = warn ?? `chown of parent dirs under ${BOX_HOME} failed; some may remain root-owned.`;\n }\n }\n return warn ? { finalPath: `${boxDir}/`, warn } : { finalPath: `${boxDir}/` };\n}\n\n/**\n * Copy one or more box sources to the host. A single source keeps full\n * `docker cp` semantics; ≥2 sources land under a destination directory (one\n * `tar` per distinct source parent).\n */\nexport async function downloadFromBox(\n box: BoxRecord,\n boxSrcs: string[],\n hostDst: string,\n exclude?: string[],\n): Promise<BoxCpResult> {\n if (boxSrcs.length === 1) return downloadOneFromBox(box, boxSrcs[0]!, hostDst, exclude);\n\n const dstAbs = resolve(hostDst);\n const dstExists = existsSync(dstAbs);\n if (!hostDst.endsWith('/') && !(dstExists && statSync(dstAbs).isDirectory())) {\n throw new Error(\n `cannot copy multiple sources to '${hostDst}': destination is not a directory (add a trailing slash, e.g. ${hostDst}/)`,\n );\n }\n mkdirSync(dstAbs, { recursive: true });\n\n for (const [parent, basenames] of groupByParent(boxSrcs, posixDirname, posix.basename)) {\n const [packed, extracted] = await streamTarPipe(\n 'docker',\n [\n 'exec',\n box.container,\n 'tar',\n '-C',\n parent,\n '-cf',\n '-',\n ...tarExcludeArgs(exclude),\n ...basenames,\n ],\n 'tar',\n ['-xf', '-', '-C', dstAbs],\n );\n if (packed.exitCode !== 0) {\n throw new Error(\n `tar pack in box failed for ${parent}: ${asText(packed.stderr).slice(0, 300)}`,\n );\n }\n if (extracted.exitCode !== 0) {\n throw new Error(`tar extract on host failed: ${asText(extracted.stderr).slice(0, 300)}`);\n }\n }\n return { finalPath: dstAbs };\n}\n","import { execa } from 'execa';\nimport type { GitWorktreeRecord } from '@agentbox/core';\nimport { execInBox } from '../docker.js';\nimport type { DetectedGitRepo } from '../git-worktree.js';\nimport { GitWorktreeError } from '../git-worktree.js';\n// The box-wins classifier + the resync orchestration moved to the provider-\n// neutral git/workspace concern in @agentbox/sandbox-core; the resync runs\n// against a `WorkspaceResyncPorts` this file supplies. The host-side ports are\n// the shared `makeHostGitPorts()` (host git is provider-neutral); only the\n// box-side ports are docker-specific here. `classifyUntrackedOverlay` is\n// re-exported so the docker test is untouched.\nimport {\n classifyUntrackedOverlay,\n dropHostOnlyPaths,\n makeHostGitPorts,\n resyncWorkspace,\n seedExcludeTarArgs,\n} from '@agentbox/sandbox-core';\nimport type { RepoResyncResult, WorkspaceResyncPorts } from '@agentbox/core';\nexport { classifyUntrackedOverlay };\nexport type { RepoResyncResult };\n\n/**\n * Root for per-box git-worktree directories inside the container. Each box\n * registers its worktree at a unique subpath here so the host main repo's\n * worktree registry can list multiple concurrent boxes without path\n * collision; `/workspace` is then a symlink to the per-box dir. Lives under\n * the vscode user's home so it's writable without sudo. Exported for the\n * fs-safe path helper.\n */\nexport const WORKTREE_ROOT = '/home/vscode/.agentbox-worktrees';\n\n/** Sanitize a branch name into an FS-safe path segment. */\nexport function fsSafeBranch(branch: string): string {\n return branch.replace(/[^A-Za-z0-9._-]+/g, '_');\n}\n\n/**\n * Per-box per-repo path at which `git worktree add` registers the worktree\n * inside the container. The agent's working tree path stays `/workspace`\n * (root) / `/workspace/<sub>` (nested) via symlinks created after the add.\n * Unique because the branch name carries the box name, so the host main\n * repo never sees a path collision when multiple boxes from the same\n * project run concurrently.\n */\nexport function gitWorktreePathFor(branch: string): string {\n return `${WORKTREE_ROOT}/${fsSafeBranch(branch)}`;\n}\n\n/**\n * Per-repo carry-over captured on the host before the container starts. The\n * host runs the `git stash create` + `ls-files --others` here against the\n * user's main checkout, then `seedWorkspace` replays both inside the box.\n *\n * `stashSha` and the untracked tarball are stored in the shared `.git/`\n * object database (stash) and as a buffer (untracked) so the container can\n * apply them after `git worktree add` runs against the bind-mounted `.git`.\n */\nexport interface RepoCarryOver {\n repo: DetectedGitRepo;\n /**\n * Agent-visible container path of the worktree (`/workspace` for root,\n * `/workspace/<sub>` for nested). After seedWorkspace runs this is a\n * symlink to `gitWorktreePath`.\n */\n containerPath: string;\n /**\n * Real container path where git registered the worktree\n * (`/home/vscode/.agentbox-worktrees/<fsSafeBranch>`). Per-box unique, so\n * concurrent boxes from the same project don't collide in the host main\n * repo's worktree registry.\n */\n gitWorktreePath: string;\n /** Branch name to pass to `git worktree add -b`. */\n branch: string;\n /** Stash-commit SHA (`git stash create`); null when the host main was clean. */\n stashSha: string | null;\n /**\n * NUL-separated list of repo-relative untracked paths. We tar these up\n * host-side and pipe them in inside seedWorkspace. Empty when no untracked\n * files.\n */\n untrackedNul: string;\n /** Host dir to tar from (== repo.hostMainRepo, kept here so seedWorkspace doesn't need to know about the repo shape). */\n hostSource: string;\n /**\n * Reuse the existing branch `<branch>` instead of forking a fresh one:\n * `git worktree add <wt> <branch>` (no `-b`, no base ref). Set by the\n * `--use-branch` path for the root repo. When unset/false the worktree is\n * created with `-b <branch>` from `fromBranch ?? HEAD` (the default fork).\n */\n reuseBranch?: boolean;\n}\n\n/**\n * Collect host-side state for each detected repo so it can be replayed\n * inside the container by `seedWorkspace`. Pure of any docker calls — every\n * shell-out is host git.\n *\n * Branch picking is left to the caller (so it can be allocated before\n * `docker run` and recorded on the BoxRecord regardless of how the rest of\n * create proceeds).\n */\nexport async function collectRepoCarryOver(\n repo: DetectedGitRepo,\n branch: string,\n containerPath: string,\n gitWorktreePath: string,\n): Promise<RepoCarryOver> {\n // `stash create` writes a stash commit without touching the working tree or\n // stash list; empty output = clean. The commit lands in the host's `.git/`\n // object DB, which is bind-mounted into the container — so the in-box\n // worktree can `stash apply <sha>` against it.\n const stash = await execa('git', ['-C', repo.hostMainRepo, 'stash', 'create'], { reject: false });\n const stashSha = stash.exitCode === 0 ? stash.stdout.trim() || null : null;\n\n const untracked = await execa(\n 'git',\n ['-C', repo.hostMainRepo, 'ls-files', '--others', '--exclude-standard', '-z'],\n { reject: false },\n );\n // Host-only dirs stripped here rather than at the tar: this list is also\n // replayed by the resync path, and `.agentbox/` is never the box's business.\n const untrackedNul = untracked.exitCode === 0 ? dropHostOnlyPaths(untracked.stdout) : '';\n\n return {\n repo,\n containerPath,\n gitWorktreePath,\n branch,\n stashSha,\n untrackedNul,\n hostSource: repo.hostMainRepo,\n };\n}\n\nexport interface SeedWorkspaceOptions {\n container: string;\n /** Repos with collected carry-over, in DAG order: root first, nested after. */\n repos: RepoCarryOver[];\n /**\n * Base ref each worktree is forked from. `undefined` (default) → `HEAD`.\n * Caller validates host-side; passed verbatim to `git worktree add`. Set\n * by `agentbox create --from-branch <ref>` so the box can start from main\n * (or any ref) instead of whatever the host happens to have checked out.\n */\n fromBranch?: string;\n onLog?: (line: string) => void;\n}\n\n/**\n * docker exec helper that throws GitWorktreeError on non-zero exit. `cwd`\n * defaults to `/` so callers that intentionally rebind `/workspace` (the\n * image's WORKDIR) don't get hit by \"chdir failed: no such file or directory\"\n * on the next exec.\n */\nasync function dexec(\n container: string,\n argv: string[],\n user: 'vscode' | 'root' = 'vscode',\n cwd: string = '/',\n): Promise<void> {\n const r = await execa('docker', ['exec', '-w', cwd, '--user', user, container, ...argv], {\n reject: false,\n });\n if (r.exitCode !== 0) {\n throw new GitWorktreeError(`${argv.join(' ')} failed: ${r.stderr || r.stdout}`);\n }\n}\n\n/**\n * Minimum shape `bindWorktrees` needs — keeps the helper independent of\n * the `RepoCarryOver` / `GitWorktreeRecord` types so both `seedWorkspace`\n * (after creation) and `startBox` (after `docker start`) can call it.\n */\nexport interface WorktreeBindSpec {\n kind: 'root' | 'nested';\n containerPath: string;\n gitWorktreePath: string;\n}\n\n/**\n * Apply the `/workspace` (and `/workspace/<sub>`) bind mounts that expose\n * each per-box git worktree at its canonical agent path.\n *\n * Idempotent for `startBox` re-runs: if the target is already a mountpoint\n * we unmount it first. Root bind first so the nested mount points (created\n * by the root worktree's `worktree add`) exist before we cover them.\n *\n * The mount runs as `root` because `mount(2)` requires `CAP_SYS_ADMIN` —\n * which we already grant the outer container for the in-box dockerd. The\n * bind itself respects file ownership on the source side (vscode-owned),\n * so subsequent in-container operations under `/workspace` work as vscode.\n */\n/**\n * Make the in-container parent directory of each bind-mounted `.git` owned by\n * `vscode`. Docker auto-creates the intermediate path for a bind mount\n * (e.g. `/Users/marco/Projects/Foo/` for a `.git` at `/Users/marco/Projects/Foo/.git`)\n * in the container's writable layer as `root:root 755`. The bind-mounted\n * `.git` itself keeps its host UIDs, but agents (turborepo, build caches,\n * etc.) often want to write *siblings* of `.git` at the project root —\n * `.turbo/`, `.next/`, scratch files — which fails as `vscode` if the parent\n * is root-owned. This flips just that parent dir's UID.\n *\n * NOT recursive on purpose: `chown -R` would descend into `.git` (the\n * bind-mount inode) and propagate ownership changes back to the host,\n * defeating the \"no host perms touched\" property.\n *\n * Best-effort: failures are logged, not thrown — the box still functions,\n * only sibling writes at the project root are affected.\n */\nexport async function chownGitBindParents(args: {\n container: string;\n hostMainRepos: string[];\n onLog?: (line: string) => void;\n}): Promise<void> {\n const log = args.onLog ?? (() => {});\n // Dedupe — nested-repo carry-overs can repeat hostMainRepo.\n const repos = Array.from(new Set(args.hostMainRepos));\n for (const repo of repos) {\n const result = await execInBox(args.container, ['chown', 'vscode:vscode', repo], {\n user: 'root',\n });\n if (result.exitCode === 0) {\n log(`chowned ${repo} to vscode:vscode (parent of bind-mounted .git)`);\n } else {\n const msg = (result.stderr || result.stdout || `exit ${result.exitCode}`).trim();\n log(`chown ${repo} failed (best-effort, ignoring): ${msg}`);\n }\n }\n}\n\nexport async function bindWorktrees(\n container: string,\n binds: WorktreeBindSpec[],\n onLog?: (line: string) => void,\n): Promise<void> {\n const log = onLog ?? (() => {});\n // Root first; nested mountpoints live inside the root worktree's tree so\n // the root bind has to be in place before we cover sub-paths.\n const ordered = [...binds].sort((a, b) =>\n a.kind === 'root' && b.kind !== 'root' ? -1 : a.kind !== 'root' && b.kind === 'root' ? 1 : 0,\n );\n for (const b of ordered) {\n // Best-effort unmount of any leftover bind at the target (idempotent for\n // startBox: container stop drops mounts, but a partial create might\n // leave one in place).\n await execa(\n 'docker',\n [\n 'exec',\n '-w',\n '/',\n '--user',\n 'root',\n container,\n 'sh',\n '-c',\n `mountpoint -q ${b.containerPath} && umount ${b.containerPath} || true`,\n ],\n { reject: false },\n );\n // For nested: parent must exist. The root bind exposes the root\n // worktree's tracked tree, which typically contains <sub>/, but if the\n // root .gitignores it or the nested repo is in a fresh path, mkdir is\n // needed.\n if (b.kind === 'nested') {\n await dexec(container, ['mkdir', '-p', ctParent(b.containerPath)], 'root');\n await dexec(container, ['mkdir', '-p', b.containerPath], 'root');\n }\n await dexec(container, ['mount', '--bind', b.gitWorktreePath, b.containerPath], 'root');\n log(`bind-mounted ${b.containerPath} <- ${b.gitWorktreePath}`);\n }\n}\n\n/**\n * Best-effort host-side `git lfs fetch` of the LFS objects reachable from\n * `baseRef`, BEFORE the in-box `git worktree add` checkout smudges them.\n *\n * Why host-side: the box has no access to the host's git credentials (the\n * git-shim only relays push/pull/fetch/clone, and git-lfs uses its own HTTP\n * transfer), so an in-box smudge of an object that isn't cached yet would\n * reach the network unauthenticated and fail. The host *does* have creds, and\n * `.git/lfs/objects/` is part of the bind-mounted `.git/` shared with the box.\n * So we fetch here, the objects land in the shared store, and the in-box\n * checkout resolves every object from cache with zero box network or creds.\n *\n * Quiet and safe: we first probe `git lfs ls-files` so the overwhelmingly\n * common non-LFS repo does nothing and logs nothing. Any failure (no git-lfs\n * on the host, no `origin`, offline, private without creds) is logged and\n * swallowed, so create proceeds and the in-box checkout still resolves\n * whatever is already cached. Mirrors the host-side, best-effort style of\n * `collectRepoCarryOver`.\n */\nasync function prefetchHostLfs(\n hostMainRepo: string,\n baseRef: string,\n log: (line: string) => void,\n): Promise<void> {\n // Probe whether this repo tracks anything with LFS (ls-files defaults to\n // HEAD). Empty output or a non-zero exit (no git-lfs binary, not LFS) → no\n // work to do, and crucially no log noise on the common non-LFS path.\n const tracked = await execa('git', ['-C', hostMainRepo, 'lfs', 'ls-files', '-n'], {\n reject: false,\n });\n if (tracked.exitCode !== 0 || tracked.stdout.trim().length === 0) return;\n\n // `origin` matches the convention used by from-branch.ts; a repo with a\n // differently-named remote just falls through to the best-effort skip below.\n const remote = 'origin';\n const fetched = await execa('git', ['-C', hostMainRepo, 'lfs', 'fetch', remote, baseRef], {\n reject: false,\n });\n if (fetched.exitCode === 0) {\n log(`prefetched git-lfs objects for ${baseRef} into shared .git/lfs (host ${remote})`);\n } else {\n const msg = (fetched.stderr || fetched.stdout || `exit ${String(fetched.exitCode ?? '?')}`)\n .trim()\n .split('\\n')[0];\n log(`git-lfs prefetch for ${baseRef} skipped (best-effort, continuing): ${msg}`);\n }\n}\n\n/**\n * Materialize each per-box git worktree *inside* the container against the\n * bind-mounted `.git/`, then replay the host's uncommitted state (stash +\n * untracked) into it. Runs as `vscode` (the in-container user) so files in\n * /workspace are owned by uid 1000.\n *\n * Layout: every worktree is registered at a per-box unique path under\n * `WORKTREE_ROOT` (`/home/vscode/.agentbox-worktrees/<fsSafeBranch>`), then\n * a `mount --bind` exposes it at `/workspace` (and `/workspace/<sub>` for\n * nested repos). The uniqueness is load-bearing — the host main repo's\n * worktree registry is keyed by absolute path, so multiple concurrent\n * boxes from the same project must register at *different* paths. They\n * share the object DB (the bind-mounted `.git/`) but have independent\n * HEAD/index in their own `.git/worktrees/<subdir>`.\n *\n * The bind mount (not a symlink) is intentional: getcwd() / realpath() /\n * git rev-parse --show-toplevel / Node's process.cwd() all return\n * `/workspace`. A symlink would leak the per-box physical path everywhere\n * tools canonicalize. Cost: the mount is per-container-namespace and\n * doesn't survive `docker stop`, so `startBox` re-binds via\n * {@link bindWorktrees}. Host's `git worktree list` will show each box's\n * registered path as `/home/vscode/.agentbox-worktrees/...` (container-only\n * — host marks it `prunable`, which is harmless).\n */\nexport async function seedWorkspace(opts: SeedWorkspaceOptions): Promise<void> {\n const log = opts.onLog ?? (() => {});\n\n // Ensure the per-box worktree root exists. Idempotent — multiple boxes\n // can be created in parallel against the same image.\n await dexec(opts.container, ['mkdir', '-p', WORKTREE_ROOT]);\n\n // Phase 1: register each worktree at its per-box unique path.\n // `fromBranch` (when set) overrides the default `HEAD` base ref for the\n // *root* repo only — the CLI's `--from-branch <ref>` is resolved against\n // the user's primary repo, and a nested submodule/monorepo-sub-repo will\n // almost never carry that same ref. Applying it uniformly would fail\n // `git worktree add` for nested repos that don't have `<ref>`, aborting\n // box creation. Mirrors the cloud path's behavior in\n // `packages/sandbox-cloud/src/workspace-seed.ts` (which only forwards\n // `fromBranch` to the root clone).\n for (const r of opts.repos) {\n const main = r.repo.hostMainRepo;\n const wt = r.gitWorktreePath;\n // reuse: check out the existing branch directly (`git worktree add <wt>\n // <branch>`). Git refuses if the host already has it checked out — that\n // stderr is surfaced verbatim below. fork (default): create a fresh\n // branch with `-b` from `fromBranch ?? HEAD` (root only; nested → HEAD).\n const baseRef = r.repo.kind === 'root' ? (opts.fromBranch ?? 'HEAD') : 'HEAD';\n // Pull the checkout's LFS objects into the shared (bind-mounted) .git/lfs\n // cache host-side first, so the in-box smudge below never reaches the\n // network without the host's credentials. Best-effort; never aborts.\n await prefetchHostLfs(main, baseRef, log);\n const addArgs = r.reuseBranch\n ? ['worktree', 'add', wt, r.branch]\n : ['worktree', 'add', '-b', r.branch, wt, baseRef];\n const add = await execa(\n 'docker',\n ['exec', '--user', 'vscode', opts.container, 'git', '-C', main, ...addArgs],\n { reject: false },\n );\n if (add.exitCode !== 0) {\n throw new GitWorktreeError(\n `git worktree add ${wt} (branch ${r.branch}) failed: ${add.stderr || add.stdout}`,\n );\n }\n log(`worktree ${wt} on branch ${r.branch} (host main ${main})`);\n\n // Boxes don't carry the user's signing keys, so commit.gpgsign=true on\n // the host would make every in-box `git commit` fail. Enable per-worktree\n // config on the main repo, then disable signing on just this worktree.\n await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'vscode',\n opts.container,\n 'git',\n '-C',\n main,\n 'config',\n 'extensions.worktreeConfig',\n 'true',\n ],\n { reject: false },\n );\n await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'vscode',\n opts.container,\n 'git',\n '-C',\n wt,\n 'config',\n '--worktree',\n 'commit.gpgsign',\n 'false',\n ],\n { reject: false },\n );\n }\n\n // Phase 2: bind each worktree onto its agent-visible /workspace path.\n await bindWorktrees(\n opts.container,\n opts.repos.map((r) => ({\n kind: r.repo.kind,\n containerPath: r.containerPath,\n gitWorktreePath: r.gitWorktreePath,\n })),\n log,\n );\n\n // Phase 3: replay host carry-over into each worktree (via the\n // /workspace[*] symlinks, so the agent sees the changes at the canonical\n // paths it expects).\n for (const r of opts.repos) {\n const ct = r.containerPath;\n if (r.stashSha) {\n const withIndex = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'vscode',\n opts.container,\n 'git',\n '-C',\n ct,\n 'stash',\n 'apply',\n '--index',\n r.stashSha,\n ],\n { reject: false },\n );\n if (withIndex.exitCode !== 0) {\n const noIndex = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'vscode',\n opts.container,\n 'git',\n '-C',\n ct,\n 'stash',\n 'apply',\n r.stashSha,\n ],\n { reject: false },\n );\n if (noIndex.exitCode !== 0) {\n log(\n `warning: stash apply failed in ${ct} (${withIndex.stderr || withIndex.stdout || 'no message'})`,\n );\n } else {\n log(`applied tracked changes (without index — staged state lost) in ${ct}`);\n }\n } else {\n log(`applied tracked changes from host main into ${ct}`);\n }\n }\n if (r.untrackedNul.length > 0) {\n const tarOut = await execa('tar', ['-C', r.hostSource, '--null', '-T', '-', '-cf', '-'], {\n input: r.untrackedNul.replace(/\\0$/, ''),\n encoding: 'buffer',\n reject: false,\n // COPYFILE_DISABLE: no macOS `._*` AppleDouble stubs in the box.\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n if (tarOut.exitCode !== 0) {\n log(`warning: tar of untracked files for ${r.repo.hostMainRepo} failed: ${tarOut.stderr}`);\n continue;\n }\n const tarIn = await execa(\n 'docker',\n ['exec', '-i', '--user', 'vscode', opts.container, 'tar', '-C', ct, '-xf', '-'],\n { input: tarOut.stdout as Buffer, reject: false },\n );\n if (tarIn.exitCode !== 0) {\n log(`warning: untracked-file copy into ${ct} failed: ${tarIn.stderr}`);\n } else {\n const count = r.untrackedNul.split('\\0').filter((s) => s.length > 0).length;\n log(`copied ${String(count)} untracked file(s) into ${ct}`);\n }\n }\n }\n}\n\n/**\n * One restored worktree's regeneration plan. A docker checkpoint bakes the\n * *source* box's branch + worktree path into the manifest, but neither its\n * `.git` worktree metadata (host-side, bind-mounted) nor its branch ref\n * (also host-side) is captured in the image. Restoring those verbatim is\n * unsafe — see {@link regenerateRestoredWorktrees}.\n */\nexport interface RestoreWorktreePlan {\n hostMainRepo: string;\n kind: 'root' | 'nested';\n /** Container path the baked content currently sits at (manifest's gitWorktreePath). */\n bakedGitWorktreePath: string;\n /** Fresh, per-box-unique branch (allocated host-side via pickFreshBranch). */\n freshBranch: string;\n /** Fresh, per-box-unique worktree path the baked content is renamed to. */\n freshGitWorktreePath: string;\n}\n\n/**\n * Re-attach each baked `/workspace` worktree to a FRESH per-box branch when\n * restoring from a checkpoint.\n *\n * A docker checkpoint bakes the source box's worktree *content* into the image\n * but not its `.git` worktree metadata (that lived on the host, bind-mounted)\n * nor its branch ref (also host-side). The manifest only records the source\n * branch + path. Reusing them verbatim is the shared-worktree bug: every box\n * from one checkpoint would share a single branch + index (commits clobber\n * each other; `index.lock` fights), and once the source box was destroyed its\n * host worktree metadata is pruned, leaving the baked `/workspace/.git` gitfile\n * dangling (\"fatal: not a git repository\").\n *\n * So per worktree we: rename the baked content dir to a fresh unique path (an\n * O(1) rename within the container's writable layer — no copy), mint a fresh\n * branch at the host's base ref, author fresh worktree metadata under the\n * bind-mounted host `.git/worktrees/`, repoint the worktree's gitfile at it,\n * and rebuild the index from the branch tip (working tree untouched, so the\n * baked deviations survive as uncommitted changes). Mirrors the manual repair\n * documented for the shared-worktree bug.\n *\n * Runs as `vscode` against the bind-mounted host `.git` (same as seedWorkspace).\n */\nexport async function regenerateRestoredWorktrees(opts: {\n container: string;\n plans: RestoreWorktreePlan[];\n /** Base ref for the *root* worktree's fresh branch (default HEAD). Nested → HEAD. */\n fromBranch?: string;\n onLog?: (line: string) => void;\n}): Promise<void> {\n const log = opts.onLog ?? (() => {});\n // Positional args ($1..$6) so paths/branches with odd chars never re-parse.\n const script = [\n 'set -e',\n 'OLD=\"$1\"; NEW=\"$2\"; MAIN=\"$3\"; BR=\"$4\"; BASE=\"$5\"; META=\"$6\"',\n // Rename baked content to the fresh unique path (rename, not copy).\n '[ \"$OLD\" = \"$NEW\" ] || mv \"$OLD\" \"$NEW\"',\n // Fresh branch at the base ref; -f is safe because pickFreshBranch already\n // guaranteed BR is unused on the host.\n 'git -C \"$MAIN\" branch -f \"$BR\" \"$BASE\"',\n // Author worktree metadata under the bind-mounted host .git.\n 'mkdir -p \"$META\"',\n 'printf \"../..\\\\n\" > \"$META/commondir\"',\n 'printf \"%s\\\\n\" \"$NEW/.git\" > \"$META/gitdir\"',\n 'printf \"ref: refs/heads/%s\\\\n\" \"$BR\" > \"$META/HEAD\"',\n // Point the worktree's gitfile at the fresh metadata dir.\n 'printf \"gitdir: %s\\\\n\" \"$META\" > \"$NEW/.git\"',\n // Reset tracked files to the fork base so the box starts CLEAN at the host\n // base ref — same git state as a fresh create. The baked tree was captured\n // on the source box's (possibly divergent/older) branch, so its tracked\n // deviations are staleness, not work; resetting drops that noise. The\n // gitignored warm artifacts (node_modules, .next, build caches) are\n // untouched by reset --hard — that warm state is the checkpoint's value.\n 'git -C \"$NEW\" reset -q --hard HEAD',\n // Boxes carry no signing key; mirror seedWorkspace's per-worktree config so\n // host commit.gpgsign=true doesn't break in-box commits. extensions.\n // worktreeConfig writes the SHARED (bind-mounted) .git/config, so concurrent\n // boxes race on .git/config.lock — retry through the contention rather than\n // aborting (best-effort, like seedWorkspace). The per-worktree gpgsign write\n // needs the extension enabled first, so it follows the retry.\n 'set +e',\n 'for i in 1 2 3 4 5 6 7 8; do git -C \"$MAIN\" config extensions.worktreeConfig true && break; sleep 0.25; done',\n 'git -C \"$NEW\" config --worktree commit.gpgsign false',\n 'exit 0',\n ].join('\\n');\n for (const p of opts.plans) {\n const baseRef = p.kind === 'root' ? (opts.fromBranch ?? 'HEAD') : 'HEAD';\n // Same as seedWorkspace: the restore script's `reset --hard HEAD` smudges\n // LFS files in-box, so pull their objects into the shared .git/lfs\n // host-side first. Best-effort; never aborts the restore.\n await prefetchHostLfs(p.hostMainRepo, baseRef, log);\n const metaDir = `${p.hostMainRepo}/.git/worktrees/${fsSafeBranch(p.freshBranch)}`;\n const r = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'vscode',\n opts.container,\n 'bash',\n '-c',\n script,\n 'bash',\n p.bakedGitWorktreePath,\n p.freshGitWorktreePath,\n p.hostMainRepo,\n p.freshBranch,\n baseRef,\n metaDir,\n ],\n { reject: false },\n );\n if (r.exitCode !== 0) {\n throw new GitWorktreeError(\n `regenerate worktree for ${p.freshBranch} failed: ${r.stderr || r.stdout}`,\n );\n }\n log(\n `restored worktree ${p.freshGitWorktreePath} on fresh branch ${p.freshBranch} (base ${baseRef})`,\n );\n }\n}\n\n/**\n * Tar-pipe a host source dir into the container's /workspace. Used for the\n * no-git case (no detected repos), and for the `--host-snapshot` flow where\n * the source is the APFS clone instead of the live workspace.\n *\n * Runs as uid:gid 1000:1000 so extracted files are owned by `vscode` (the\n * in-container user) — same convention as `copyHostEnvFilesToBox`.\n *\n * `seedExcludeTarArgs()` keeps the host's `.agentbox/` out: it is AgentBox's own\n * durable host dir (`download --backup` writes a bot's workspace and its gateway\n * identity there), and the box regenerates its own `/workspace/.agentbox` every\n * boot. Neither one is the other's business.\n */\nexport async function seedWorkspaceFromDir(opts: {\n container: string;\n hostSource: string;\n onLog?: (line: string) => void;\n}): Promise<void> {\n const log = opts.onLog ?? (() => {});\n const tarOut = await execa(\n 'tar',\n ['-C', opts.hostSource, ...seedExcludeTarArgs(), '-cf', '-', '.'],\n {\n encoding: 'buffer',\n reject: false,\n // COPYFILE_DISABLE stops macOS BSD tar emitting `._*` AppleDouble stubs,\n // which extract on Linux as literal junk in the box's /workspace.\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n },\n );\n if (tarOut.exitCode !== 0) {\n throw new GitWorktreeError(`tar of ${opts.hostSource} failed: ${tarOut.stderr}`);\n }\n const tarIn = await execa(\n 'docker',\n ['exec', '-i', '--user', '1000:1000', opts.container, 'tar', '-C', '/workspace', '-xf', '-'],\n { input: tarOut.stdout as Buffer, reject: false },\n );\n if (tarIn.exitCode !== 0) {\n throw new GitWorktreeError(`tar extract into /workspace failed: ${tarIn.stderr}`);\n }\n log(`seeded /workspace from ${opts.hostSource}`);\n}\n\n/**\n * Remove an in-container worktree from the host's main repo's worktree\n * registry. Called from `destroyBox` per registered worktree. The registered\n * path (`gitWorktreePath`) was a container-only path (under `WORKTREE_ROOT`),\n * so `git worktree remove` will see it as missing and we go straight to\n * `worktree prune` to drop the registry entry. Best-effort throughout.\n */\nexport async function removeInBoxWorktree(args: {\n hostMainRepo: string;\n gitWorktreePath: string;\n}): Promise<void> {\n const remove = await execa(\n 'git',\n ['-C', args.hostMainRepo, 'worktree', 'remove', '--force', args.gitWorktreePath],\n { reject: false },\n );\n if (remove.exitCode === 0) return;\n await execa('git', ['-C', args.hostMainRepo, 'worktree', 'prune'], { reject: false });\n}\n\nfunction ctParent(p: string): string {\n const i = p.lastIndexOf('/');\n return i <= 0 ? '/' : p.slice(0, i);\n}\n\nexport interface ResyncWorkspaceOptions {\n container: string;\n /** The box's recorded worktrees (root + nested). */\n worktrees: GitWorktreeRecord[];\n onLog?: (line: string) => void;\n}\n\n/** Split a `-z` (NUL-delimited) git output into non-empty entries. */\nfunction splitNul(s: string): string[] {\n return s.split('\\0').filter((p) => p.length > 0);\n}\n\n/**\n * Docker implementation of the workspace-resync ports (`@agentbox/core`): the\n * host-side git probes are the shared, provider-neutral `makeHostGitPorts()`\n * (host git is the host's own repo either way); the box-side ports run via\n * `docker exec --user vscode`. Every method reproduces the pre-refactor\n * `resyncWorkspaceFromHost` command byte-for-byte — the docker `.git/` bind\n * mount means the host branch ref is already present in the box (no fetch\n * needed).\n */\nexport function makeDockerResyncPorts(container: string): WorkspaceResyncPorts {\n return {\n ...makeHostGitPorts(),\n async boxGit(ct, args) {\n return execInBox(container, ['git', '-C', ct, ...args], { user: 'vscode' });\n },\n async probeUntrackedTokens(ct, relPaths) {\n // For each existing path emit `<token>\\0<path>\\0`: the file's sha256 (fed\n // on stdin so filenames with spaces/newlines are safe), or `-` for a\n // non-regular file. `ct` is $1 (never interpolated) so a worktree path\n // with spaces is safe; `bash` for `read -d ''` (NUL), which dash lacks.\n const probe = await execa(\n 'docker',\n [\n 'exec',\n '-i',\n '--user',\n 'vscode',\n container,\n 'bash',\n '-c',\n 'cd \"$1\" && while IFS= read -r -d \"\" f; do ' +\n 'if [ -f \"$f\" ] && [ ! -L \"$f\" ]; then ' +\n 'printf \"%s\\\\0%s\\\\0\" \"$(sha256sum < \"$f\" | cut -d\" \" -f1)\" \"$f\"; ' +\n 'elif [ -e \"$f\" ]; then printf \"%s\\\\0%s\\\\0\" \"-\" \"$f\"; fi; done',\n 'bash',\n ct,\n ],\n // NUL-TERMINATED, not merely NUL-joined: `read -r -d \"\"` treats an\n // unterminated tail as EOF, so the LAST path was never probed — and an\n // unprobed path reads as \"absent in the box\", which makes the overlay\n // overwrite a box file it should have kept.\n { input: relPaths.length === 0 ? '' : `${relPaths.join('\\0')}\\0`, reject: false },\n );\n // FAIL-CLOSED. A path missing from this map means \"the box does not have\n // it\", and the overlay acts on that by copying the host's file over. So a\n // probe that could not answer must NOT degrade to an empty map — that\n // reads as an empty box and overwrites everything the box holds. Same\n // class as the NUL-termination bug above: an unreadable answer is not an\n // empty answer.\n if (probe.exitCode !== 0) {\n throw new Error(\n `could not read ${ct} in the box (exit ${String(probe.exitCode)}): ` +\n `${probe.stderr || probe.stdout || 'no output'}\\n` +\n `Refusing to resync: without the box's file list every host file would ` +\n `look new and overwrite the box's version.`,\n );\n }\n const boxTokens = new Map<string, string>();\n const flat = splitNul(probe.stdout);\n for (let i = 0; i + 1 < flat.length; i += 2) {\n const token = flat[i];\n const path = flat[i + 1];\n if (token !== undefined && path !== undefined) boxTokens.set(path, token);\n }\n return boxTokens;\n },\n async applyTarToBox(ct, tar) {\n await execa(\n 'docker',\n ['exec', '-i', '--user', 'vscode', container, 'tar', '-C', ct, '-xf', '-'],\n { input: tar, reject: false },\n );\n },\n };\n}\n\n/**\n * Resync each box worktree with the host's current state (merge the host branch\n * into the box branch, overlay host uncommitted + untracked, box wins on\n * conflict). Thin docker wrapper: the provider-neutral `resyncWorkspace` concern\n * (`@agentbox/sandbox-core`) drives the orchestration through the docker resync\n * ports. Best-effort throughout — a failed step is logged and skipped rather\n * than aborting the box start.\n */\nexport async function resyncWorkspaceFromHost(\n opts: ResyncWorkspaceOptions,\n): Promise<RepoResyncResult[]> {\n return resyncWorkspace(opts.worktrees, makeDockerResyncPorts(opts.container), opts.onLog);\n}\n","// Host-side git-repo detection is provider-neutral (cloud boxes also seed from\n// git) and lives in @agentbox/sandbox-core. Re-exported here so existing\n// `@agentbox/sandbox-docker` consumers are unchanged.\nexport {\n detectGitRepos,\n GitWorktreeError,\n pickFreshBranch,\n type DetectedGitRepo,\n} from '@agentbox/sandbox-core';\n","import { mkdir, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, join, resolve } from 'node:path';\nimport { execa } from 'execa';\nimport { ConfigError, loadConfig } from '@agentbox/ctl';\nimport { skipWebProxyAlias } from './direct-web-url.js';\nimport {\n AGENT_SYNC_SPECS,\n borrowedCredentialCarry,\n findAgentSpec,\n makeSyncContext,\n relayPort,\n syncAgentboxSshConfig,\n withPerBoxCarry,\n type AgentSyncSpec,\n} from '@agentbox/sandbox-core';\nimport { DEFAULT_BOX_RELAY_PORT } from '@agentbox/relay';\nimport { loadEffectiveConfig } from '@agentbox/config';\nimport { makeDockerSync } from './sync/docker-sync.js';\nimport {\n buildAgentsMounts,\n resolveAgentsVolume,\n type AgentsMountResult,\n} from './sync/agents/skills.js';\nimport {\n type BoxLimitSpec,\n containerExists,\n dockerInfo,\n dockerStorageDriver,\n ensureVolume,\n publishedHostPort,\n runBox,\n} from './docker.js';\nimport { dockerVolumeName, launchDockerdDaemon } from './dockerd.js';\nimport { generateVncPassword, launchVncDaemon, VNC_CONTAINER_PORT } from './vnc.js';\nimport { setUpBoxSshd, SSH_CONTAINER_PORT } from './ssh.js';\nimport { WEB_CONTAINER_PORT } from './web.js';\nimport { detectGitRepos, pickFreshBranch } from './git-worktree.js';\nimport {\n bindWorktrees,\n chownGitBindParents,\n collectRepoCarryOver,\n gitWorktreePathFor,\n regenerateRestoredWorktrees,\n removeInBoxWorktree,\n seedWorkspace,\n seedWorkspaceFromDir,\n type RepoCarryOver,\n type RestoreWorktreePlan,\n} from './sync/in-box-git.js';\nimport {\n CONTAINER_EXPORT_MERGED,\n DEFAULT_ENV_PATTERNS,\n boxRunDirFor,\n copyHostFilesToBox,\n detectEngine,\n} from './sync/host-export.js';\nimport {\n detectPortless,\n portlessAlias,\n portlessBrowserEnv,\n portlessGetUrl,\n portlessStartHint,\n resolvePortlessHostStateDir,\n} from './portless.js';\nimport { DEFAULT_BOX_IMAGE, ensureImage } from './image.js';\nimport {\n readState,\n recordBox,\n removeBoxRecord,\n reserveProjectIndex,\n type BoxRecord,\n type GitWorktreeRecord,\n} from './state.js';\nimport { generateBoxId, type ResolvedCarryEntry, type ResyncResult } from '@agentbox/core';\nimport { createSnapshot, snapshotPathFor } from './snapshot.js';\nimport { resolveCheckpoint } from './checkpoint.js';\nimport { computeDockerContextFingerprint, readPreparedDockerState } from './prepared-state.js';\nimport { launchCtlDaemon } from './ctl.js';\nimport { writeBoxEnvFile } from './box-env.js';\nimport {\n requireAgentSyncModule,\n type AgentMountResult,\n type AgentVolumeChoice,\n} from './sync/agents/module.js';\nimport { resolveAgentIsolation } from './agent-isolation.js';\nimport { ensureHomeOwnedByVscode } from './home-ownership.js';\nimport {\n ensureRelay,\n generateRelayToken,\n registerBoxWithRelay,\n rehydrateRelayRegistry,\n} from './relay.js';\nimport {\n buildIdeMounts,\n cursorServerVolumeName,\n ensureIdeVolumes,\n repairIdeOwnership,\n vscodeServerVolumeName,\n} from './vscode.js';\n\nexport interface CreateBoxOptions {\n /**\n * `box.credentialSync` resolved by the caller (CLI flag override included).\n * Undefined → fall back to the local config load below.\n */\n credentialSync?: boolean;\n workspacePath: string;\n name?: string;\n /**\n * Basis for the default name when `name` is absent and `workspacePath` isn't a\n * meaningful identity — see {@link defaultBoxName}. Mirrors `nameBasis` on\n * `CreateBoxRequest`.\n */\n nameBasis?: string;\n /**\n * Take a `cp -c` APFS clone of the host workspace into\n * `~/.agentbox/snapshots/<id>/` before seeding `/workspace`. Stabilizes the\n * source of the tar pipe in the non-git case (and the untracked-file\n * pipe in the git case) against host edits during create. Effectively a\n * no-op when a git worktree is detected — the worktree's tracked content\n * comes from `.git`, not from a workspace copy.\n */\n useSnapshot: boolean;\n /**\n * Start the box from a project checkpoint (the `--snapshot <ref>` path).\n * Resolved against `projectRoot` (or `workspacePath` when unset). The\n * checkpoint is a local Docker *image* tag now; the box is created with\n * `docker run <ckpt-image>` and inherits a populated `/workspace`. No\n * `seedWorkspace` runs in this path.\n */\n checkpointRef?: string;\n /**\n * Base ref the box's per-box branch is forked from (default: HEAD). Caller\n * is responsible for validation + any required fetch beforehand. Accepts\n * any ref `git rev-parse` resolves; passed verbatim to `git worktree add`.\n */\n fromBranch?: string;\n /**\n * Reuse an existing branch (root repo only) instead of forking a fresh\n * `agentbox/<name>`. The root worktree is created with `git worktree add\n * <wt> <branch>` (no `-b`), so git fails fast if the host already has\n * `<useBranch>` checked out. No host stash / untracked carry-over is\n * replayed — the box gets the branch's committed tip. Nested repos keep\n * their per-box `agentbox/<name>--<sub>` branches. Mutually exclusive with\n * `fromBranch` (enforced by the CLI).\n */\n useBranch?: string;\n /**\n * When starting from a checkpoint, merge the host's current branch into the\n * restored worktree and overlay the host's uncommitted/untracked changes\n * (box wins on conflict). Defaults to true. No effect on a non-checkpoint\n * fresh create (which already forks from HEAD + carry-over).\n */\n resyncOnStart?: boolean;\n image?: string;\n /** Try the registry before building the base image. Defaults to true. */\n allowPull?: boolean;\n /** Registry repo for the base-image pull. Defaults to `BOX_IMAGE_REGISTRY`; empty disables. */\n imageRegistry?: string;\n onLog?: (line: string) => void;\n /**\n * Which agents this box is FOR. When set, it is authoritative: only these\n * agents get a config volume, a mount, a credential seed, or a home dir, so a\n * `agentbox claude` box carries no codex/opencode credentials at all.\n *\n * When absent, we fall back to the historical behaviour (mount whatever the\n * host happens to have) so any caller not yet passing a selection keeps\n * working. An agent left out is not lost — `ensureAgentInstalled` adds it to\n * a live box on demand.\n */\n agents?: string[];\n /**\n * Other agents' host logins seeded as model auth for a service agent, at\n * each lender's own credential path (`AgentSyncSpec.modelAuth`). Already\n * validated against the agent's declaration by the caller.\n */\n borrowCredentials?: string[];\n /**\n * Claude Code config volume. When omitted, defaults to `{ isolate: false }` —\n * every box mounts the shared `agentbox-claude-config` volume at\n * /home/vscode/.claude so auth / skills / plugins persist across boxes.\n */\n claudeConfig?: { isolate: boolean };\n /** Extra env vars forwarded to the container (merged on top of claude env forwarding). */\n claudeEnv?: Record<string, string>;\n /**\n * Codex CLI config volume. When provided (i.e. `agentbox codex`), the box\n * always mounts a synced `agentbox-codex-config` volume at /home/vscode/.codex.\n * When omitted, `createBox` still mounts it *if the host has a `~/.codex`*\n * (so a plain `agentbox create` for a Codex user gets a working box) — see\n * the codex block below. `isolate: true` opts into a per-box volume.\n */\n codexConfig?: { isolate: boolean };\n /**\n * OpenCode CLI config volume. When provided (i.e. `agentbox opencode`), the\n * box always mounts a synced `agentbox-opencode-config` volume. When omitted,\n * `createBox` still mounts it *if the host uses OpenCode* (`~/.config/opencode`\n * or `~/.local/share/opencode` exists). `isolate: true` opts into a per-box\n * volume. See the opencode block below.\n */\n opencodeConfig?: { isolate: boolean };\n /**\n * Per-agent config-volume options, keyed by agent id — the generic form of\n * the three named fields above, which stay for their existing callers and\n * win when both are given.\n *\n * This is what lets an agent outside the built-in three isolate its config:\n * `box.isolate<Agent>Config` is generated for EVERY agent in `AGENT_KINDS`,\n * so the key already existed for the demo agent and had nowhere to go.\n */\n agentConfig?: Record<string, { isolate?: boolean }>;\n /**\n * When true, run `npm install -g @playwright/cli@latest` inside the box after\n * `/workspace` is seeded. agent-browser is always installed in the image;\n * this flag adds the Playwright CLI on top for boxes that need it.\n */\n withPlaywright?: boolean;\n /**\n * When true, copy the host's env/config files (DEFAULT_ENV_PATTERNS basename\n * globs — `.env*`, `secrets.toml`, `agentbox.yaml`, ...) into the box's\n * /workspace after seeding, bypassing gitignore. The reverse of `pull env`.\n * One-shot at create time; the files persist in the container's writable\n * layer across pause/stop/start.\n */\n withEnv?: boolean;\n /**\n * Explicit relative-path file list to copy from `workspacePath` into the\n * box's /workspace after seeding (no glob expansion, no scan — the list is\n * pre-vetted, e.g. picked by the wizard's multiselect). Independent of\n * `withEnv`: if both are set, both run (idempotent on overlapping files).\n * One-shot at create time; persists across pause/stop/start.\n */\n envFilesToImport?: string[];\n /**\n * Pre-approved host→box file copies from `agentbox.yaml`'s `carry:` block.\n * Resolved + user-approved by the apps/cli layer (resolveCarry + the carry\n * prompt) before being threaded in here. Each entry is copied to its\n * declared `absDest` (NOT under /workspace) after env-file imports and\n * before the supervisor starts, so the first declared task can already\n * read e.g. `~/.agentbox/secrets.env`. Empty / undefined → no-op.\n */\n carry?: ResolvedCarryEntry[];\n /**\n * VNC stack (Xvnc on :1 + websockify serving noVNC on container :6080).\n * Defaults to enabled. The CLI exposes `--no-vnc` for opt-out. Disabling\n * skips port mapping + password generation + the in-container supervisor\n * launch; the apt-installed binaries stay in the image but are unused.\n */\n vnc?: { enabled: boolean };\n /**\n * Create this box as PERSISTENT (always-on). Absent → the effective\n * `box.persistent`. Mirrors `CreateBoxRequest.persistent`.\n */\n persistent?: boolean;\n /**\n * Docker-in-Docker. Always-on (the in-box dockerd is part of the box\n * surface). When `sharedCache` is true the per-box `agentbox-docker-<id>`\n * volume is replaced with the shared `agentbox-docker-cache` volume — image\n * layers persist across boxes (and `destroy`/`prune` won't remove it).\n */\n docker?: { sharedCache: boolean };\n /**\n * When true, register a Portless route (`portless alias <box-name> <webPort>`)\n * so the box web app is reachable at `https://<box-name>.localhost`. Only\n * acts on non-OrbStack engines (OrbStack already has `.orb.local`) and only\n * when Portless is installed on the host — best-effort, never fails create.\n */\n portless?: boolean;\n /**\n * Override for the host Portless state directory shared into the box (the\n * `portless.stateDir` config key). When unset, `createBox` resolves Portless's\n * own default. Only consulted when `portless` is true.\n */\n portlessStateDir?: string;\n /**\n * Absolute host path of the cwd's project at create time. When provided,\n * `createBox` stamps `projectRoot` + an allocated `projectIndex` on the\n * BoxRecord so the CLI can auto-pick / resolve by index. The CLI computes\n * this via `findProjectRoot(workspacePath)` from `@agentbox/config`; this\n * package stays free of the config dep. Omit for unowned boxes created\n * directly via the programmatic API.\n */\n projectRoot?: string;\n /**\n * Container resource ceilings (engine-agnostic: bytes / fractional cpus /\n * pid count / raw disk size string). Absent fields = unlimited. `disk` is\n * best-effort: dropped (with a warning via `onLog`) when the engine's\n * storage driver can't enforce `--storage-opt size=` (overlay2 / macOS).\n */\n limits?: BoxLimitSpec;\n}\n\nexport interface CreatedBox {\n record: BoxRecord;\n imageBuilt: boolean;\n /** Conflicts from the on-create resync (checkpoint-restore path). Absent when no resync ran. */\n resync?: ResyncResult;\n}\n\n/**\n * Compact the engine-applied limits into the BoxRecord shape: only fields that\n * actually constrain the box (>0 / non-empty). Returns undefined when nothing\n * was applied so legacy/unlimited boxes stay free of the field.\n */\nfunction persistableLimits(lim: BoxLimitSpec | undefined): BoxRecord['resourceLimits'] | undefined {\n if (!lim) return undefined;\n const out: NonNullable<BoxRecord['resourceLimits']> = {};\n if (lim.memoryBytes && lim.memoryBytes > 0) out.memoryBytes = Math.floor(lim.memoryBytes);\n if (lim.cpus && lim.cpus > 0) out.cpus = lim.cpus;\n if (lim.pidsLimit && lim.pidsLimit > 0) out.pidsLimit = Math.floor(lim.pidsLimit);\n if (lim.disk) out.disk = lim.disk;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Reduce an arbitrary token to the box-name charset. Not path-aware. */\nfunction sanitizeNameToken(raw: string): string {\n return raw\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^[-._]+|[-._]+$/g, '')\n .slice(0, 30)\n .replace(/[-._]+$/, '');\n}\n\nexport function sanitizeBasename(workspacePath: string): string {\n return sanitizeNameToken(basename(resolve(workspacePath)));\n}\n\n/**\n * `nameBasis` replaces the workspace basename when the caller knows the path\n * isn't a meaningful identity — a control box builds every box from a per-job\n * clone dir it then deletes, so without it the box is named after a directory\n * that no longer exists and says nothing about the project.\n */\nexport function defaultBoxName(workspacePath: string, id: string, nameBasis?: string): string {\n const base = nameBasis ? sanitizeNameToken(nameBasis) : sanitizeBasename(workspacePath);\n return base.length > 0 ? `${base}-${id}` : id;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Trust the (TLS) host Portless CA inside a docker box so the in-box VNC\n * browser (Chrome or Chromium) and Playwright accept `https://<name>.localhost`. The CA is the\n * host's, bind-mounted at /home/vscode/.portless/ca.pem (PORTLESS_STATE_DIR).\n * The baked `agentbox-portless-trust` helper installs it into the system store\n * + the vscode NSS db; we then drop a profile.d export of NODE_EXTRA_CA_CERTS\n * for Node-based agents. Best-effort: never throws.\n */\nasync function trustInBoxPortlessCa(container: string, log: (line: string) => void): Promise<void> {\n const script =\n 'agentbox-portless-trust /home/vscode/.portless/ca.pem >/dev/null 2>&1 || true; ' +\n \"echo 'export NODE_EXTRA_CA_CERTS=/usr/local/share/ca-certificates/agentbox-portless-ca.crt' \" +\n '> /etc/profile.d/agentbox-portless-ca.sh 2>/dev/null || true';\n const r = await execa('docker', ['exec', '--user', 'root', container, 'bash', '-lc', script], {\n reject: false,\n });\n if (r.exitCode === 0) log('portless: trusted host CA in box (system store + NSS)');\n else log('portless: in-box CA trust failed (best-effort) — in-box https may warn');\n}\n\n// ~/.claude and ~/.codex are intentionally NOT in this list: each lives in a\n// named volume (`agentbox-claude-config` / `agentbox-codex-config`, see\n// resolveClaudeVolume / resolveCodexVolume) so auth persists inside the\n// container without leaking host state. Only the remaining identity files are\n// bind-mounted from the host.\nasync function buildIdentityMounts(): Promise<string[]> {\n const home = homedir();\n const candidates: Array<{ src: string; dst: string; readOnly: boolean }> = [\n { src: join(home, '.gitconfig'), dst: '/home/vscode/.gitconfig', readOnly: true },\n ];\n const out: string[] = [];\n for (const c of candidates) {\n if (await pathExists(c.src)) {\n out.push(`${c.src}:${c.dst}${c.readOnly ? ':ro' : ''}`);\n }\n }\n return out;\n}\n\nexport async function createBox(opts: CreateBoxOptions): Promise<CreatedBox> {\n const log = opts.onLog ?? (() => {});\n const workspace = resolve(opts.workspacePath);\n if (!(await pathExists(workspace))) {\n throw new Error(`workspace does not exist: ${workspace}`);\n }\n\n // Pre-flight agentbox.yaml validation on the host so the user sees the real\n // ConfigError instead of an opaque \"socket did not appear\" timeout from the\n // detached daemon exec later. The daemon re-validates inside the box anyway\n // — defence in depth, and necessary because the file lives in the\n // container's writable layer and can be edited after create.\n const cfgPath = join(workspace, 'agentbox.yaml');\n if (await pathExists(cfgPath)) {\n try {\n const cfg = await loadConfig(cfgPath);\n log(`agentbox.yaml validated (${String(cfg.services.length)} service(s))`);\n } catch (err) {\n if (err instanceof ConfigError) {\n throw new Error(`agentbox.yaml validation failed:\\n ${err.message}`);\n }\n throw err;\n }\n }\n\n await dockerInfo();\n log('docker daemon reachable');\n\n // Checkpoint resolution happens *before* image ensure because a checkpoint\n // image replaces the base image as the docker-run base. resolveCheckpoint\n // returns null on miss; we error with the ref so the user can fix it.\n let checkpointImage: string | undefined;\n let checkpointSource: BoxRecord['checkpointSource'];\n let restoredWorktrees: GitWorktreeRecord[] | undefined;\n let resyncResult: ResyncResult | undefined;\n if (opts.checkpointRef) {\n const projectRootForCkpt = opts.projectRoot ?? workspace;\n const head = await resolveCheckpoint(projectRootForCkpt, opts.checkpointRef);\n if (!head) {\n throw new Error(`checkpoint not found: ${opts.checkpointRef}`);\n }\n checkpointImage = head.manifest.image;\n // Chain: head first then its parents (base-most last). For a flattened\n // checkpoint this collapses to a single-entry chain.\n const chain = [head.name, ...head.manifest.parents];\n checkpointSource = { ref: opts.checkpointRef, type: head.manifest.type, chain };\n // The source's per-worktree paths persisted on the manifest so we can\n // re-establish the /workspace bind mount(s) after `docker run` (docker\n // commit doesn't capture bind-mount content, so the image's /workspace\n // is empty until we re-bind).\n restoredWorktrees = head.manifest.worktrees;\n log(\n `starting from checkpoint ${opts.checkpointRef} (${head.manifest.type}, ${String(chain.length)} layer(s), image ${head.manifest.image})`,\n );\n\n // Stale-checkpoint warning: the checkpoint image replaces the base image\n // as the docker-run base, so any base-image update (a CLI upgrade, an\n // edit to `custom-system-CLAUDE.md`, etc.) is invisible inside a box\n // restored from a pre-update checkpoint. Compare the captured\n // fingerprint with the current prepared state and surface the\n // mismatch loudly. We never block — the user might intentionally pin\n // an old image — but they need to know.\n const ckptFingerprint = head.manifest.baseFingerprint;\n const ckptCliVersion = head.manifest.cliVersion ?? 'unknown';\n if (head.manifest.schema === 2) {\n log(\n `WARNING: checkpoint '${opts.checkpointRef}' was captured before checkpoint versioning landed.\\n` +\n ` Its base-image layers may be older than your current base image. If the box is missing\\n` +\n ` expected updates, remove the checkpoint with \\`agentbox checkpoint rm ${opts.checkpointRef}\\` and recreate it.`,\n );\n } else {\n const prepared = readPreparedDockerState();\n const currentFingerprint =\n prepared?.base?.contextSha256 ?? (await computeDockerContextFingerprint())?.contextSha256;\n if (ckptFingerprint && currentFingerprint && ckptFingerprint !== currentFingerprint) {\n log(\n `WARNING: checkpoint '${opts.checkpointRef}' was captured against an older base image.\\n` +\n ` captured: cli ${ckptCliVersion}, fingerprint ${ckptFingerprint.slice(0, 12)}\\n` +\n ` current : cli ${prepared?.base?.cliVersion ?? 'unknown'}, fingerprint ${currentFingerprint.slice(0, 12)}\\n` +\n ` The restored box will keep the old base layers and will NOT include base-image updates.\\n` +\n ` To pick up updates: \\`agentbox checkpoint rm ${opts.checkpointRef}\\` and recreate from a fresh box.`,\n );\n }\n }\n }\n\n // `opts.agents`, when given, is the authoritative selection: exactly those\n // agents are baked into the image and wired into the box. Without it we keep\n // the historical \"mount whatever the host has\" behaviour so un-migrated\n // callers still work.\n const selected = opts.agents ? new Set(opts.agents) : undefined;\n const wants = async (agent: string, hostHints: () => Promise<boolean>): Promise<boolean> =>\n selected ? selected.has(agent) : await hostHints();\n\n const baseRef = checkpointImage\n ? (opts.image ?? DEFAULT_BOX_IMAGE)\n : (opts.image ?? DEFAULT_BOX_IMAGE);\n // ensureImage only acts on the base image; checkpoint images are local-only\n // and must already exist (they were created by `agentbox checkpoint`). It\n // returns the VARIANT ref (`…:dev-claude`), which is what the box must run.\n const { ref: ensureRef, built } = await ensureImage(baseRef, {\n // `ensureImage`'s own decision lines already carry the `[image]` tag; only\n // docker's raw per-layer output needs it added, or they read `[image] [image] …`.\n onProgress: (line) => log(line.startsWith('[image]') ? line : `[image] ${line}`),\n allowPull: opts.allowPull,\n registry: opts.imageRegistry,\n ...(opts.agents ? { agents: opts.agents } : {}),\n });\n const imageRef = checkpointImage ?? ensureRef;\n log(built ? `built image ${ensureRef}` : `using cached image ${imageRef}`);\n\n // Bring up the host relay before the box so the box can post events\n // immediately on boot. Best-effort — a relay outage shouldn't block create.\n // Always re-push known box tokens after ensure: the relay's registry is\n // in-memory, so a daemon restart or `docker restart agentbox-relay` between\n // CLI invocations leaves it empty. Repushing is idempotent and cheap.\n let relayUp = false;\n try {\n await ensureRelay({ onLog: log });\n const existing = await readState();\n await rehydrateRelayRegistry(existing.boxes);\n relayUp = true;\n } catch (err) {\n log(`relay unavailable: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n const id = generateBoxId();\n const name = opts.name ?? defaultBoxName(workspace, id, opts.nameBasis);\n const containerName = `agentbox-${name}`;\n const createdAt = new Date().toISOString();\n if (await containerExists(containerName)) {\n throw new Error(`container ${containerName} already exists; remove it first`);\n }\n\n // Per-project monotonic index. Reserved *atomically* here (under the state\n // lock, persisting a minimal record that claims it) so it can flow into the\n // box / snapshot dir segments (`<id>-<n>-<mnemonic>`) and the\n // `AGENTBOX_PROJECT_INDEX` env var with no risk of a concurrent create\n // claiming the same number and forcing a later bump that would desync the\n // recorded index from the dir already created from it. The full record is\n // written over this reservation by the provisional + final recordBox below.\n // Pre-feature legacy boxes never pass `projectRoot`; those keep `projectIndex`\n // undefined and the dir segments fall back to `<id>-<mnemonic>`.\n let projectIndex: number | undefined;\n if (opts.projectRoot) {\n projectIndex = await reserveProjectIndex(\n { id, name, container: containerName, image: imageRef, workspacePath: workspace, createdAt },\n opts.projectRoot,\n );\n }\n\n // Repo detection + host-side carry-over capture. Branches are picked here\n // (against the host main repos' refs) so they're recorded on the BoxRecord\n // regardless of whether the in-container `git worktree add` succeeds later.\n // When restoring from a checkpoint, the source's per-worktree records are\n // restored from the manifest *here* (not after `docker run`) so the\n // `.git/` bind-mounts in `extraVolumes` know which host main repos to\n // wire up — without those binds the in-container `/workspace/.git` would\n // resolve to a path that doesn't exist in the new container.\n const repoCarryOvers: RepoCarryOver[] = [];\n const gitWorktreeRecords: GitWorktreeRecord[] = [];\n // Checkpoint restore: the manifest's worktree records carry the *source*\n // box's branch + path. Reusing them verbatim is the shared-worktree bug —\n // every box from one checkpoint would share a single branch + index, and the\n // baked /workspace/.git gitfile dangles once the source box's host worktree\n // metadata was pruned. So mint a FRESH per-box branch + unique worktree path\n // here (host-side, before docker run, like the non-checkpoint path) and\n // regenerate the in-box worktree over the baked content after run.\n const restoreWorktreePlans: RestoreWorktreePlan[] = [];\n if (checkpointImage && restoredWorktrees && restoredWorktrees.length > 0) {\n for (const w of restoredWorktrees) {\n const branchBase =\n w.kind === 'root'\n ? `agentbox/${name}`\n : `agentbox/${name}--${w.relPathFromWorkspace.replace(/[^A-Za-z0-9._-]+/g, '_')}`;\n const freshBranch = await pickFreshBranch(w.hostMainRepo, branchBase);\n const freshGitWorktreePath = gitWorktreePathFor(freshBranch);\n restoreWorktreePlans.push({\n hostMainRepo: w.hostMainRepo,\n kind: w.kind,\n bakedGitWorktreePath: w.gitWorktreePath,\n freshBranch,\n freshGitWorktreePath,\n });\n gitWorktreeRecords.push({\n kind: w.kind,\n hostMainRepo: w.hostMainRepo,\n containerPath: w.containerPath,\n gitWorktreePath: freshGitWorktreePath,\n branch: freshBranch,\n sanctionedBranch: freshBranch,\n relPathFromWorkspace: w.relPathFromWorkspace,\n });\n }\n }\n if (!checkpointImage) {\n const repos = await detectGitRepos(workspace);\n if (repos.length > 0) {\n log(\n `detected ${String(repos.length)} git repo(s): ` +\n repos\n .map((r) => `${r.kind}${r.relPathFromWorkspace ? '@' + r.relPathFromWorkspace : ''}`)\n .join(', '),\n );\n }\n for (const r of repos) {\n const containerPath =\n r.kind === 'root' ? '/workspace' : `/workspace/${r.relPathFromWorkspace}`;\n // --use-branch reuses the named branch for the *root* repo only: no\n // pickFreshBranch (we want the exact branch), no carry-over replay (the\n // user wants the branch's committed tip, not host uncommitted state).\n // Nested repos always fork their own per-box branch — the root's reused\n // branch won't exist in a nested repo.\n const reuseBranch = r.kind === 'root' && opts.useBranch !== undefined;\n if (reuseBranch) {\n const branch = opts.useBranch as string;\n const gitWorktreePath = gitWorktreePathFor(branch);\n repoCarryOvers.push({\n repo: r,\n containerPath,\n gitWorktreePath,\n branch,\n stashSha: null,\n untrackedNul: '',\n hostSource: r.hostMainRepo,\n reuseBranch: true,\n });\n gitWorktreeRecords.push({\n kind: r.kind,\n hostMainRepo: r.hostMainRepo,\n containerPath,\n gitWorktreePath,\n branch,\n sanctionedBranch: branch,\n relPathFromWorkspace: r.relPathFromWorkspace,\n });\n continue;\n }\n const branchBase =\n r.kind === 'root'\n ? `agentbox/${name}`\n : `agentbox/${name}--${r.relPathFromWorkspace.replace(/[^A-Za-z0-9._-]+/g, '_')}`;\n const branch = await pickFreshBranch(r.hostMainRepo, branchBase);\n const gitWorktreePath = gitWorktreePathFor(branch);\n const carry = await collectRepoCarryOver(r, branch, containerPath, gitWorktreePath);\n repoCarryOvers.push(carry);\n gitWorktreeRecords.push({\n kind: r.kind,\n hostMainRepo: r.hostMainRepo,\n containerPath,\n gitWorktreePath,\n branch,\n sanctionedBranch: branch,\n relPathFromWorkspace: r.relPathFromWorkspace,\n });\n }\n }\n\n // --host-snapshot: APFS clone the workspace into a per-box scratch dir.\n // Only the no-git, no-checkpoint path actually consumes the clone (as the\n // source of the tar pipe in seedWorkspaceFromDir). For the git path the\n // worktree content comes from `.git`'s object DB (bind-mounted) and the\n // untracked-file tar pipe reads from the live host main repo — neither\n // touches `snapshotDir`, so we skip it. For checkpoint restore there's no\n // seedWorkspace at all. Kept on the BoxRecord so destroyBox can clean it up.\n let snapshotDir: string | null = null;\n const snapshotIsUseful = !checkpointImage && repoCarryOvers.length === 0;\n if (opts.useSnapshot && snapshotIsUseful) {\n snapshotDir = snapshotPathFor({ id, name, projectIndex });\n log(`cloning workspace to ${snapshotDir} (APFS clone where available)`);\n const snap = await createSnapshot({ source: workspace, destination: snapshotDir });\n log(`pruned ${snap.prunedPaths.length} platform-dependent dirs from snapshot`);\n } else if (opts.useSnapshot && !checkpointImage) {\n log(\n 'skipping --host-snapshot: git worktree path reads content from .git, not from a workspace clone',\n );\n }\n\n await ensureIdeVolumes(id);\n const dockerCacheShared = opts.docker?.sharedCache === true;\n const dockerVolume = dockerVolumeName(id, dockerCacheShared);\n await ensureVolume(dockerVolume);\n log(\n `prepared volumes ${vscodeServerVolumeName(id)}, ${cursorServerVolumeName(id)}, ${dockerVolume}`,\n );\n const ide = buildIdeMounts(id);\n\n // Agent config volumes (claude/codex/agents/opencode). Each is\n // host-authoritative and additively synced from the host on every create (a\n // new login/skill/MCP on the host flows into the next box; box-only state like\n // session logs is preserved). `--isolate-<tool>-config` opts into a per-box\n // volume. Resolve the specs + want-conditionals here (one source of truth —\n // they also drive the mounts below), then walk the docker ProviderSync facade\n // to run the actual volume seeds + credential sync.\n // One entry per agent the registry knows, not three hand-written consts.\n //\n // The consts were the last per-agent table in the create path, and the demo\n // agent found it the way a canary should: `agentbox example` produced a box\n // with no config volume at all, silently, because there was no\n // `exampleSpec` for `wants()` to have an opinion about.\n //\n // The host HINT is what differs. `--agents` (or `agentbox <agent>`) is\n // authoritative when given; without it the historical behaviour is \"mount\n // whatever the host already has\", which for every agent means \"any of its\n // declared static paths exists\". Claude is the one exception and stays\n // explicit: it is mounted always, even on a host with no `~/.claude` yet,\n // because a first-run claude box has to have somewhere to put its login.\n // Isolation (shared volume vs per-box) is `resolveAgentIsolation`'s call:\n // per-agent from the options object, defaulting to the agent's own surface.\n const hostHasAnyStaticPath = async (spec: AgentSyncSpec): Promise<boolean> => {\n for (const path of spec.staticPaths) {\n if (await pathExists(join(homedir(), ...path.hostHomeRel))) return true;\n }\n return false;\n };\n const agentSpecs: Record<string, AgentVolumeChoice> = {};\n for (const spec of AGENT_SYNC_SPECS) {\n const wanted = await wants(spec.id, () =>\n spec.id === 'claude' ? Promise.resolve(true) : hostHasAnyStaticPath(spec),\n );\n if (!wanted) continue;\n agentSpecs[spec.id] = requireAgentSyncModule(spec.id).resolveVolume({\n isolate: resolveAgentIsolation(spec, opts, log),\n boxId: id,\n });\n }\n\n // Agents skills (~/.agents): mounted whenever the host has one; shared across\n // boxes (skills only, no auth). Codex discovers skills from ~/.agents/skills.\n const agentsSpec = (await pathExists(join(homedir(), '.agents')))\n ? resolveAgentsVolume()\n : undefined;\n // Walk the docker ProviderSync facade (see sync/docker-sync.ts for the full\n // per-op picture): seed every agent-config volume (claude static+skills+dynamic\n // +box-facts, codex hooks+AGENTS.override, opencode plugin) then sync the claude\n // credentials. The seeds run against throwaway helper containers + the box image\n // — the box container `containerName` doesn't exist yet, which is fine (those\n // ops don't touch it). Workspace *seed* + the mount building below stay here:\n // they're docker-specific, non-facade steps that feed `runBox`.\n const syncCtx = makeSyncContext({\n boxName: name,\n boxId: id,\n provider: 'docker',\n hostWorkspace: workspace,\n projectRoot: opts.projectRoot ?? workspace,\n onLog: log,\n });\n const sync = makeDockerSync({\n container: containerName,\n image: ensureRef,\n // Keyed by agent id, straight from the registry-derived map above: the sync\n // walks the registry, so an agent this file never names still gets its\n // volume seeded.\n agentSpecs,\n claudeIsolate: opts.claudeConfig?.isolate ?? false,\n agentsSpec,\n });\n await sync.seedAgentConfig(syncCtx);\n await sync.seedCredentials(syncCtx);\n\n // Container mounts, built from the same specs (pure). Through the registry, so\n // an agent contributes its mounts without this file naming it.\n // Mounts, from the same map. One loop, so an agent contributes its mounts\n // without this file naming it.\n const agentMounts: AgentMountResult[] = [];\n const configVolumes: Record<string, string> = {};\n for (const [agent, choice] of Object.entries(agentSpecs)) {\n agentMounts.push(requireAgentSyncModule(agent).buildMounts(choice, process.env));\n configVolumes[agent] = choice.volume;\n }\n // The three named fields are a DERIVED mirror of the map for older readers;\n // `agentConfigVolumes` is what a fourth or plugin agent lands in. This used to\n // narrow the map to these three and discard the rest, which is why every\n // consumer downstream had to guess with a `default:` arm.\n const claudeConfigVolume = configVolumes['claude'];\n const codexConfigVolume = configVolumes['codex'];\n const opencodeConfigVolume = configVolumes['opencode'];\n\n let agentsMounts: AgentsMountResult | undefined;\n let agentsConfigVolume: string | undefined;\n if (agentsSpec) {\n agentsMounts = buildAgentsMounts(agentsSpec);\n agentsConfigVolume = agentsSpec.volume;\n }\n\n const boxDir = boxRunDirFor({ id, name, projectIndex });\n const socketDir = join(boxDir, 'run');\n const socketPath = join(socketDir, 'ctl.sock');\n // Per-box host dir that `agentbox open` refreshes the merged /workspace\n // into. Bound in at create time so `docker exec rsync` can write straight\n // to the host filesystem — no container restart needed.\n const mergedExportDir = join(boxDir, 'workspace');\n await mkdir(socketDir, { recursive: true });\n await mkdir(mergedExportDir, { recursive: true });\n\n const extraVolumes = await buildIdentityMounts();\n for (const m of agentMounts) extraVolumes.push(...m.extraVolumes);\n if (agentsMounts) extraVolumes.push(...agentsMounts.extraVolumes);\n extraVolumes.push(...ide.extraVolumes);\n extraVolumes.push(`${socketDir}:/run/agentbox`);\n extraVolumes.push(`${mergedExportDir}:${CONTAINER_EXPORT_MERGED}`);\n // In-box dockerd's data root. Per-box (`agentbox-docker-<id>`, wiped on\n // destroy) by default; shared (`agentbox-docker-cache`, preserved) when\n // `box.dockerCacheShared` is set.\n extraVolumes.push(`${dockerVolume}:/var/lib/docker`);\n // Bind-mount each main repo's `.git/` at its identical absolute host path,\n // RW. The in-container `git worktree add` writes to <main>/.git/worktrees/\n // and the agent's commits write to refs/objects; both have to hit the same\n // path on host and inside the container so `git push` from the host main\n // repo sees the new commits without further sync.\n for (const w of gitWorktreeRecords) {\n extraVolumes.push(`${w.hostMainRepo}/.git:${w.hostMainRepo}/.git`);\n }\n\n // Portless: when enabled (and not OrbStack), (1) make the in-box browser\n // route the box's `<name>.localhost` URL out to the host proxy\n // (`portlessBrowserEnv`), and (2) bind-mount the host's Portless state dir so\n // the in-box `portless` CLI shares the host's route registry (discovery).\n // Best-effort; a missing host dir is created so the bind has a source.\n // PORTLESS_STATE_DIR pins both sides to the same path.\n const portlessEnv: Record<string, string> = {};\n if (opts.portless === true && (await detectEngine()) !== 'orbstack') {\n Object.assign(portlessEnv, portlessBrowserEnv(name, { mapTarget: 'host.docker.internal' }));\n try {\n const hostStateDir = await resolvePortlessHostStateDir(opts.portlessStateDir);\n await mkdir(hostStateDir, { recursive: true });\n const boxStateDir = '/home/vscode/.portless';\n extraVolumes.push(`${hostStateDir}:${boxStateDir}`);\n portlessEnv['PORTLESS_STATE_DIR'] = boxStateDir;\n } catch (err) {\n log(\n `portless: state-dir share skipped (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n }\n\n for (const v of extraVolumes) log(`mounting agent dir: ${v}`);\n\n // Resolve the per-box host-action auto-approve policy from config (workspace\n // > project > global). Read here, in the construction layer, so every\n // entrypoint (create/claude/codex/opencode/wizard/queued worker) gets the\n // same behavior without each caller threading the flag.\n const effectiveBoxCfg = (await loadEffectiveConfig(opts.projectRoot ?? workspace)).effective.box;\n const autoApproveHostActions = effectiveBoxCfg.autoApproveHostActions;\n const autoApproveSafeHostActions = effectiveBoxCfg.autoApproveSafeHostActions;\n // Persistent (always-on) boxes: resolved here so every entrypoint agrees, with\n // the caller's explicit `--persistent` winning over the config layers.\n const persistent = opts.persistent ?? effectiveBoxCfg.persistent;\n\n // Per-box bearer token for the host relay. Register *before* runBox so the\n // box's supervisor can post on boot. Skip if the relay isn't reachable —\n // the box still works, it just won't deliver events to the host.\n const relayToken = generateRelayToken();\n // Repo identity, so a thin client can map this box to a local project by\n // origin URL (cross-machine), not just by folder path — the registration-side\n // half of Step 4's box resolution. Best-effort: a box without a git origin\n // simply registers none.\n const originRepo = gitWorktreeRecords[0]?.hostMainRepo ?? opts.projectRoot ?? workspace;\n const originUrl = await execa('git', ['-C', originRepo, 'remote', 'get-url', 'origin'], {\n reject: false,\n })\n .then((r) => (r.exitCode === 0 ? r.stdout.trim() || undefined : undefined))\n .catch(() => undefined);\n if (relayUp) {\n try {\n await registerBoxWithRelay({\n boxId: id,\n token: relayToken,\n name,\n containerName,\n createdAt,\n projectIndex,\n worktrees: gitWorktreeRecords,\n autoApproveHostActions,\n autoApproveSafeHostActions,\n originUrl,\n agent: opts.agents?.[0],\n });\n log(`registered box token with relay`);\n } catch (err) {\n log(`relay register failed: ${err instanceof Error ? err.message : String(err)}`);\n relayUp = false;\n }\n }\n const relayEnv: Record<string, string> = relayUp\n ? {\n // The in-box ctl client always talks to its own in-box relay/forwarder\n // on AGENTBOX_BOX_RELAY_PORT (DEFAULT_BOX_RELAY_PORT, 8788). For docker\n // boxes the forwarder transparently proxies to the host relay at\n // host.docker.internal:<relay.port> (the matching `--add-host` is set in\n // runBox). The two ports stay distinct so :8787 inside the box remains\n // free for a nested agentbox to claim its own host relay.\n AGENTBOX_RELAY_URL: `http://127.0.0.1:${String(DEFAULT_BOX_RELAY_PORT)}`,\n AGENTBOX_RELAY_TOKEN: relayToken,\n AGENTBOX_HOST_RELAY_URL: `http://host.docker.internal:${String(relayPort())}`,\n }\n : {};\n\n // VNC stack defaults on; the CLI surfaces `--no-vnc` for opt-out. Generate\n // the password and the port mapping up front so they're baked into the\n // container's env + `-p` flags before `docker run` — both must be set at\n // create time (env survives stop/start; port mappings are immutable).\n const vncEnabled = opts.vnc?.enabled !== false;\n const vncPassword = vncEnabled ? generateVncPassword() : undefined;\n const vncEnv: Record<string, string> =\n vncEnabled && vncPassword ? { AGENTBOX_VNC_PASSWORD: vncPassword } : {};\n const vncPortMappings = vncEnabled\n ? [{ hostPort: 0, containerPort: VNC_CONTAINER_PORT, hostIp: '127.0.0.1' }]\n : [];\n\n // Reserve the web port unconditionally: `docker run -p` is immutable, but the\n // `expose:`-flagged service is usually only known after the in-box wizard\n // writes agentbox.yaml. The supervisor forwards :80 to it later; here we just\n // guarantee a published host port exists for whenever that happens.\n const webPortMappings = [{ hostPort: 0, containerPort: WEB_CONTAINER_PORT, hostIp: '127.0.0.1' }];\n\n // sshd is always-on: publish container :22 on an ephemeral loopback host port\n // so `agentbox open` (sshfs) and the Codex app can reach the box over SSH. Like\n // the web/VNC mappings this must be set at `docker run` (port maps are immutable)\n // and re-resolved on every start (the host port is reassigned).\n const sshPortMappings = [{ hostPort: 0, containerPort: SSH_CONTAINER_PORT, hostIp: '127.0.0.1' }];\n\n // Identity vars that make the box self-aware. `projectIndex` was allocated\n // earlier (right after `id`/`name`) so dir-segment helpers could see it; we\n // just read the binding here.\n const agentboxEnv: Record<string, string> = {\n AGENTBOX: '1',\n AGENTBOX_BOX_NAME: name,\n AGENTBOX_HOST_WORKSPACE: workspace,\n // Absent = enabled; the ctl credential watcher only checks for '0'. The\n // caller-resolved value wins (it sees CLI overrides like\n // --no-credential-sync that this function's own config load can't).\n ...((opts.credentialSync ?? effectiveBoxCfg.credentialSync) === false\n ? { AGENTBOX_CREDENTIAL_SYNC: '0' }\n : {}),\n ...(opts.projectRoot ? { AGENTBOX_PROJECT_ROOT: opts.projectRoot } : {}),\n ...(projectIndex !== undefined ? { AGENTBOX_PROJECT_INDEX: String(projectIndex) } : {}),\n };\n const boxEnvForFile: Record<string, string> = {\n AGENTBOX_BOX_ID: id,\n ...agentboxEnv,\n ...portlessEnv,\n };\n\n // `--storage-opt size=` is only enforced by devicemapper/btrfs/zfs.\n const appliedLimits: BoxLimitSpec | undefined = opts.limits;\n let effectiveLimits = appliedLimits;\n if (appliedLimits?.disk) {\n const driver = await dockerStorageDriver();\n if (!/^(devicemapper|btrfs|zfs|windowsfilter)$/.test(driver)) {\n log(\n `warning: --disk/box.disk is a no-op on this engine (storage-driver=${driver || 'unknown'}); ignoring`,\n );\n effectiveLimits = { ...appliedLimits, disk: null };\n }\n }\n\n // Everything about the box that's known before `docker run`. Recorded\n // provisionally right after the container starts (below) so a failure during\n // the rest of finalization (seed, ctl/vnc/dockerd launch, port publish,\n // portless) still leaves a state.json record — destroy/prune resolve the box\n // by its real name from state.json instead of relying on the orphan-container\n // fallback, and the late-known fields (ports, portless, carry) are merged in\n // by the final `recordBox` on success.\n const baseRecord: BoxRecord = {\n id,\n name,\n container: containerName,\n image: imageRef,\n workspacePath: workspace,\n snapshotDir,\n socketPath,\n claudeConfigVolume,\n codexConfigVolume,\n agentsConfigVolume,\n opencodeConfigVolume,\n agentConfigVolumes: configVolumes,\n vscodeServerVolume: vscodeServerVolumeName(id),\n cursorServerVolume: cursorServerVolumeName(id),\n relayToken: relayUp ? relayToken : undefined,\n gitWorktrees: gitWorktreeRecords.length > 0 ? gitWorktreeRecords : undefined,\n // The agent set this box was created FOR. Already used above to pick the\n // derived image variant; persisting it is what lets a later `checkpoint\n // create` record which agent the checkpoint carries. Distinct from\n // `lastAgent`, which tracks whichever agent most recently ran.\n ...(opts.agents && opts.agents.length > 0 ? { agents: [...opts.agents] } : {}),\n ...(opts.borrowCredentials && opts.borrowCredentials.length > 0\n ? { borrowedCredentials: [...opts.borrowCredentials] }\n : {}),\n withPlaywright: opts.withPlaywright ? true : undefined,\n withEnv: opts.withEnv ? true : undefined,\n autoApproveHostActions: autoApproveHostActions ? true : undefined,\n // Default on: persist only when explicitly disabled (mirrors the relay's\n // `!== false` read); an absent field on an older record stays relaxed.\n autoApproveSafeHostActions: autoApproveSafeHostActions === false ? false : undefined,\n persistent: persistent ? true : undefined,\n vncEnabled: vncEnabled ? true : undefined,\n vncContainerPort: vncEnabled ? VNC_CONTAINER_PORT : undefined,\n vncPassword: vncPassword,\n webContainerPort: WEB_CONTAINER_PORT,\n sshEnabled: true,\n sshContainerPort: SSH_CONTAINER_PORT,\n dockerVolume,\n dockerCacheShared: dockerCacheShared || undefined,\n projectRoot: opts.projectRoot,\n projectIndex,\n checkpointImage,\n checkpointSource,\n resourceLimits: persistableLimits(effectiveLimits),\n createdAt,\n };\n\n await runBox({\n name: containerName,\n image: imageRef,\n extraVolumes,\n limits: effectiveLimits,\n portMappings: [...vncPortMappings, ...webPortMappings, ...sshPortMappings],\n env: {\n AGENTBOX_BOX_ID: id,\n ...agentboxEnv,\n ...Object.assign({}, ...agentMounts.map((m) => m.env)),\n ...relayEnv,\n ...vncEnv,\n ...portlessEnv,\n ...(opts.claudeEnv ?? {}),\n },\n });\n log(`container ${containerName} started`);\n\n // Provisional registration: the box now exists, so persist it before the\n // remaining finalization steps. If create dies past this point, the record\n // (with the real name) is already in state.json for destroy/prune to find.\n await recordBox(baseRecord);\n\n // Flip the in-container parent dir of each bind-mounted `.git` to\n // vscode-owned. Docker auto-creates the intermediates (e.g. the project root\n // path that contains `.git`) as root:root 755 in the writable layer; without\n // this chown the agent can't write siblings of `.git` (`.turbo/`, `.next/`,\n // build caches) at the project root. Non-recursive — the bind-mounted `.git`\n // itself stays untouched (recursive chown would propagate to the host).\n if (gitWorktreeRecords.length > 0) {\n await chownGitBindParents({\n container: containerName,\n hostMainRepos: gitWorktreeRecords.map((w) => w.hostMainRepo),\n onLog: log,\n });\n }\n\n // /etc/agentbox/box.env: sourced by /etc/profile.d/agentbox.sh in login\n // shells (the docker-run env doesn't reach `agentbox shell <box>` cleanly\n // without it). Best-effort — env vars on the container are the primary\n // path; this file is for shells launched via tools that strip env.\n const boxEnv = await writeBoxEnvFile(containerName, boxEnvForFile);\n if (boxEnv.ok) log('wrote /etc/agentbox/box.env');\n else log(`writing /etc/agentbox/box.env failed: ${boxEnv.reason}`);\n\n // Re-own /home/vscode to vscode. Root-run exec steps (checkpoint cleanup,\n // dockerd setup) and boxes restored from a checkpoint can leave home-dir\n // files root-owned; the shell + agent run as vscode and would silently\n // fail to write them (e.g. dropped `.bash_history`). Best-effort.\n await ensureHomeOwnedByVscode(containerName);\n\n // Seed /workspace.\n // - Checkpoint restore: the image already has the source box's per-box\n // worktree dir populated; we only need to re-establish the bind mount\n // onto /workspace (docker commit doesn't capture bind-mount content).\n // - Git path: create in-container worktrees + bind + replay stash + untracked.\n // - No-git path: tar-pipe host workspace (or its APFS clone) into\n // /workspace (no bind — files live directly in the image's writable\n // layer at /workspace).\n if (!checkpointImage) {\n if (repoCarryOvers.length > 0) {\n try {\n await seedWorkspace({\n container: containerName,\n repos: repoCarryOvers,\n fromBranch: opts.fromBranch,\n onLog: log,\n });\n log('seeded /workspace from in-container git worktree(s)');\n } catch (err) {\n // --use-branch seed failures are almost always \"branch already used by\n // another worktree\" (the host has it checked out). There's nothing\n // useful to inspect, and a leftover container + worktree registration\n // would block the next attempt, so tear it down. Other seed failures\n // keep the existing inspect-on-failure behavior.\n if (opts.useBranch !== undefined) {\n log(`seedWorkspace failed for --use-branch ${opts.useBranch}; cleaning up the box`);\n await execa('docker', ['rm', '-f', containerName], { reject: false });\n // Drop the provisional record written after runBox so we don't leave\n // a dangling state.json entry pointing at the now-removed container.\n await removeBoxRecord(id);\n for (const w of gitWorktreeRecords) {\n await removeInBoxWorktree({\n hostMainRepo: w.hostMainRepo,\n gitWorktreePath: w.gitWorktreePath,\n });\n }\n } else {\n log(`seedWorkspace failed; leaving ${containerName} running so you can inspect it`);\n }\n throw err;\n }\n } else {\n const source = snapshotDir ?? workspace;\n await seedWorkspaceFromDir({ container: containerName, hostSource: source, onLog: log });\n }\n } else if (restoreWorktreePlans.length > 0) {\n // gitWorktreeRecords was populated above (pre-`docker run`) with FRESH\n // per-box branches/paths, so the .git bind-mounts in extraVolumes are\n // wired. The container is now running, so regenerate each baked worktree\n // onto its fresh branch (rename + fresh metadata + reindex), then apply the\n // /workspace bind mount(s) onto the fresh paths.\n await regenerateRestoredWorktrees({\n container: containerName,\n plans: restoreWorktreePlans,\n fromBranch: opts.fromBranch,\n onLog: log,\n });\n await bindWorktrees(\n containerName,\n gitWorktreeRecords.map((w) => ({\n kind: w.kind,\n containerPath: w.containerPath,\n gitWorktreePath: w.gitWorktreePath,\n })),\n log,\n );\n log('re-bound /workspace from checkpoint image (fresh per-box worktree)');\n // Each fresh branch was forked from the host's base ref, and\n // regenerateRestoredWorktrees already `reset --hard`ed the tracked tree to\n // it (the checkpoint's stale tracked deviations are dropped; gitignored warm\n // artifacts like node_modules are kept). Resync then merges the host's\n // current branch in + overlays the host's uncommitted/untracked changes, so\n // the box matches a fresh create from HEAD (box wins on conflict).\n if (opts.resyncOnStart !== false) {\n resyncResult = await sync.resyncWorkspace(syncCtx, gitWorktreeRecords);\n }\n } else {\n log('using /workspace from checkpoint image (no worktrees recorded; no rebind)');\n }\n\n await repairIdeOwnership(containerName);\n log('.vscode-server + .cursor-server ownership verified');\n\n if (opts.withEnv) {\n log('copying host env/config files into /workspace (--with-env)');\n const { copied } = await sync.seedEnvFiles(syncCtx, DEFAULT_ENV_PATTERNS);\n log(copied > 0 ? `copied ${String(copied)} env/config file(s)` : 'no env/config files found');\n }\n\n if (opts.envFilesToImport && opts.envFilesToImport.length > 0) {\n log(\n `copying ${String(opts.envFilesToImport.length)} selected env/config file(s) into /workspace`,\n );\n const { copied } = await copyHostFilesToBox({\n container: containerName,\n workspaceDir: workspace,\n files: opts.envFilesToImport,\n onLog: log,\n });\n if (copied !== opts.envFilesToImport.length) {\n log(\n `copied ${String(copied)}/${String(opts.envFilesToImport.length)} selected env/config file(s)`,\n );\n }\n }\n\n // carry: from agentbox.yaml — resolved and approved by the host CLI, then\n // threaded in here. Runs after the env-file copies and BEFORE the ctl daemon\n // launches, so the first supervisor task can already see e.g.\n // ~/.agentbox/secrets.env or a borrowed model login. It used to run after\n // the daemon, which raced a task that reads a carried file on first boot.\n let carrySummary: BoxRecord['carry'] | undefined;\n // The agent's own per-box files (a bot's channel tokens) join the user's\n // approved entries here, where the final box name exists — the source path is\n // keyed by it, which is what keeps two bots from sharing one token.\n const carryEntries = await withPerBoxCarry(\n opts.carry,\n (opts.agents ?? []).map((a) => findAgentSpec(a)),\n { boxName: syncCtx.boxName },\n log,\n );\n // A borrowed model login (`borrowCredentials`) is the same kind of thing as\n // a per-box channel token — a host file the agent asked for, landing 0600 at\n // a path it named — so it rides the same step. Validated by the caller.\n carryEntries.push(...(await borrowedCredentialCarry(opts.borrowCredentials ?? [], log)));\n if (carryEntries.length > 0) {\n log(`carry: copying ${String(carryEntries.length)} host path(s) into the box`);\n const result = await sync.applyCarry(syncCtx, carryEntries);\n log(`carry: copied ${String(result.copied)}/${String(carryEntries.length)} entry/entries`);\n for (const err of result.errors) log(`carry: ${err}`);\n if (result.applied.length > 0) {\n carrySummary = { count: result.applied.length, entries: result.applied };\n }\n }\n\n // dockerd: always-on, mirrors launchVncDaemon. Launched (and awaited ready)\n // BEFORE the ctl supervisor: the supervisor starts agentbox.yaml services as\n // soon as it's up, so a `docker run`/`docker compose` service must not race a\n // not-yet-ready /var/run/docker.sock. launchDockerdDaemon blocks until the\n // socket is accept()-able. Best-effort — a slow start shouldn't fail box\n // creation; `agentbox start` will relaunch on restart (the daemon dies with\n // the container). The storage driver is selected at runtime by\n // agentbox-dockerd-start (overlay2, with a fuse-overlayfs fallback) — see\n // /var/log/agentbox/dockerd.log inside the box.\n const dockerd = await launchDockerdDaemon(containerName);\n if (dockerd.up) {\n log(`dockerd up (data root=${dockerVolume})`);\n } else {\n log(`dockerd did not become ready: ${dockerd.reason}`);\n }\n\n const ctl = await launchCtlDaemon(containerName, socketPath);\n if (ctl.up) log('agentbox-ctl daemon up');\n else log(`agentbox-ctl daemon did not become reachable: ${ctl.reason}`);\n\n if (opts.withPlaywright) {\n log('installing @playwright/cli@latest (--with-playwright)');\n const result = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'root',\n containerName,\n 'bash',\n '-lc',\n 'npm install -g @playwright/cli@latest 2>&1',\n ],\n { reject: false },\n );\n for (const line of (result.stdout ?? '').split('\\n')) {\n if (line.trim().length > 0) log(`[playwright] ${line}`);\n }\n if (result.exitCode !== 0) {\n throw new Error(\n `failed to install @playwright/cli (exit ${String(result.exitCode)}): ${(result.stderr ?? '').toString().slice(0, 400)}`,\n );\n }\n log('@playwright/cli installed');\n }\n\n // VNC daemon (Xvnc + websockify). Best-effort, like launchCtlDaemon. The\n // host port mapping was wired into runBox above (hostPort=0 → random); we\n // resolve the assigned port here for storage. If the daemon fails to come\n // up we still record vncEnabled so `agentbox start` will retry the launch.\n let vncHostPort: number | null = null;\n if (vncEnabled) {\n const vnc = await launchVncDaemon(containerName);\n if (vnc.up) log('vnc stack up (Xvnc + websockify + noVNC)');\n else log(`vnc stack did not become reachable: ${vnc.reason}`);\n vncHostPort = await publishedHostPort(containerName, VNC_CONTAINER_PORT);\n if (vncHostPort) log(`vnc web on host 127.0.0.1:${String(vncHostPort)}`);\n }\n\n const webHostPort = await publishedHostPort(containerName, WEB_CONTAINER_PORT);\n if (webHostPort) {\n log(\n `web port reserved on host 127.0.0.1:${String(webHostPort)} ` +\n `(forwards to the web service once agentbox.yaml sets a service expose:)`,\n );\n }\n\n // sshd: mint the per-box key under the box dir's ssh/, install it into the\n // box's authorized_keys, launch sshd, resolve the loopback host port. The key\n // dir lives inside boxDir so `destroy` (which rm -rf's boxRunDirFor) wipes the\n // private key with it. Best-effort — a failed bring-up leaves the box usable\n // over `docker exec`, just without `agentbox open`/SSH.\n const ssh = await setUpBoxSshd(containerName, join(boxDir, 'ssh'), `agentbox-${name}-${id}`);\n if (ssh.up && ssh.sshHostPort) {\n log(`sshd up on host 127.0.0.1:${String(ssh.sshHostPort)} (loopback-only)`);\n } else {\n log(\n `sshd did not come up: ${ssh.reason ?? 'unknown'} (open/SSH unavailable; docker exec still works)`,\n );\n }\n\n // Portless: register `https://<box-name>.localhost -> 127.0.0.1:<webHostPort>`\n // and a parallel `https://vnc-<box-name>.localhost -> 127.0.0.1:<vncHostPort>`\n // for the noVNC viewer. Best-effort — Portless is user-installed and never\n // required; any failure here just leaves the box on its loopback URL.\n // Skipped on OrbStack (which already has <container>.orb.local).\n let portlessAliasName: string | undefined;\n let portlessUrl: string | undefined;\n let portlessVncAliasName: string | undefined;\n let portlessVncUrl: string | undefined;\n if (opts.portless === true && (webHostPort || (vncEnabled && vncHostPort))) {\n try {\n const engine = await detectEngine();\n if (engine === 'orbstack') {\n log('portless: skipped (OrbStack already provides <container>.orb.local)');\n } else {\n const portless = await detectPortless();\n if (!portless.installed) {\n log('portless not installed — run `npm install -g portless` for a <name>.localhost URL');\n } else {\n if (webHostPort && !skipWebProxyAlias(opts.agents, log)) {\n if (await portlessAlias(name, webHostPort)) {\n portlessAliasName = name;\n // Resolve the real URL from the proxy: scheme + port depend on how\n // the proxy was started (http://…:1355 no-TLS, or https://… on :443).\n portlessUrl = await portlessGetUrl(name);\n log(`portless alias ${portlessUrl} -> 127.0.0.1:${String(webHostPort)}`);\n // When the host proxy is TLS, the in-box VNC Chromium / Playwright\n // hit `https://<name>.localhost` (via host.docker.internal) and\n // reject the host's self-signed CA. The CA is already bind-mounted\n // at /home/vscode/.portless/ca.pem (PORTLESS_STATE_DIR); trust it\n // in the box (system store + vscode NSS db) and point Node at it.\n // agent-browser already gets IGNORE_HTTPS_ERRORS via portlessEnv;\n // this covers everything else. http (no-TLS :1355) has no cert.\n if (portlessUrl.startsWith('https://')) {\n await trustInBoxPortlessCa(containerName, log);\n }\n } else {\n log('portless alias failed (best-effort) — box still reachable on the loopback URL');\n }\n }\n if (vncEnabled && vncHostPort) {\n const vncAlias = `vnc-${name}`;\n if (await portlessAlias(vncAlias, vncHostPort)) {\n portlessVncAliasName = vncAlias;\n portlessVncUrl = await portlessGetUrl(vncAlias);\n log(`portless alias ${portlessVncUrl} -> 127.0.0.1:${String(vncHostPort)}`);\n } else {\n log(\n 'portless vnc alias failed (best-effort) — VNC still reachable on the loopback URL',\n );\n }\n }\n if (!portless.proxyRunning && (portlessAliasName || portlessVncAliasName)) {\n log(`portless proxy not running — start it with \\`${portlessStartHint()}\\``);\n }\n }\n }\n } catch (err) {\n log(`portless: ${err instanceof Error ? err.message : String(err)} (best-effort, ignored)`);\n }\n }\n\n // Final record: the provisional base plus the fields only known after the\n // container was up (published host ports, portless aliases, applied carry).\n const record: BoxRecord = {\n ...baseRecord,\n carry: carrySummary,\n vncHostPort: vncHostPort ?? undefined,\n webHostPort: webHostPort ?? undefined,\n sshHostPort: ssh.sshHostPort ?? undefined,\n // Only advertise an ssh-config alias when sshd actually bound (`up`). Docker\n // publishes the -p 0:22 host port regardless, so gating on the port alone\n // would point `~/.ssh/config` at a dead loopback port when sshd failed to\n // start. A later `start`/`open` re-runs setUpBoxSshd and records it once up.\n ssh:\n ssh.up && ssh.sshHostPort\n ? {\n host: '127.0.0.1',\n user: 'vscode',\n identityFile: ssh.identityFile,\n port: ssh.sshHostPort,\n }\n : undefined,\n portlessAlias: portlessAliasName,\n portlessUrl,\n portlessVncAlias: portlessVncAliasName,\n portlessVncUrl,\n };\n await recordBox(record);\n // Regenerate `~/.agentbox/ssh/config` so `ssh <box>`, `agentbox open` (sshfs)\n // and the Codex launcher have a live alias. Reads state.json (just written) —\n // best-effort, never fail create over the ssh-config write.\n if (record.ssh) {\n try {\n await syncAgentboxSshConfig();\n } catch (err) {\n log(\n `ssh-config sync failed (best-effort): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n return { record, imageBuilt: built, resync: resyncResult };\n}\n","import { agentsRejectProxyHeaders } from '@agentbox/sandbox-core';\n\n/**\n * Whether this box must publish its web port directly, with no reverse proxy.\n *\n * Decided inside the provider so every caller inherits it, the same shape as\n * {@link resolveAgentIsolation}. The mechanism is a subtraction rather than an\n * addition: skipping the Portless WEB alias is enough, because every producer\n * of a box's web URL already falls back to the directly published port when no\n * alias is registered, and the in-box browser falls back to the service's own\n * loopback port. Nothing downstream needs to know why.\n *\n * Reads `agents` — what the box was created FOR — never `lastAgent`; see\n * `agentsRejectProxyHeaders`.\n */\nexport function skipWebProxyAlias(\n agents: readonly string[] | undefined,\n log: (line: string) => void,\n): boolean {\n if (!agentsRejectProxyHeaders(agents)) return false;\n log(\n 'portless: web alias skipped — this box hosts a daemon that refuses proxied ' +\n 'requests, so its URL points at the published port directly',\n );\n return true;\n}\n","import { execInBox } from './docker.js';\n\nexport interface DockerdLaunchResult {\n up: boolean;\n reason?: string;\n}\n\n/**\n * Shared image-cache volume across boxes. When a box is created with\n * `dockerCacheShared=true`, its in-box dockerd's data root is this volume\n * instead of the per-box `agentbox-docker-<id>` volume. Mutually exclusive at\n * runtime: only one box can hold the lock on `/var/lib/docker` at a time —\n * dockerd's own boltdb lock will refuse a second start. This is a power-user\n * feature for users who run boxes serially and want pulled layers to persist\n * across recreations; documented as such on the CLI flag.\n */\nexport const SHARED_DOCKER_CACHE_VOLUME = 'agentbox-docker-cache';\n\nexport function dockerVolumeName(boxId: string, shared: boolean): string {\n return shared ? SHARED_DOCKER_CACHE_VOLUME : `agentbox-docker-${boxId}`;\n}\n\n/**\n * Spawn the in-container dockerd via `/usr/local/bin/agentbox-dockerd-start`\n * detached, then poll for `/var/run/docker.sock` to become accept()-able.\n * Best-effort, mirroring {@link launchVncDaemon} — failure is logged but\n * doesn't fail box creation. Default timeout 30s: first start has to\n * initialize iptables + the storage graphdriver, which is slower than the\n * VNC stack.\n */\nexport async function launchDockerdDaemon(\n container: string,\n timeoutMs = 30_000,\n): Promise<DockerdLaunchResult> {\n const result = await execInBox(container, ['/usr/local/bin/agentbox-dockerd-start'], {\n user: 'root',\n detach: true,\n });\n if (result.exitCode !== 0) {\n return { up: false, reason: `docker exec failed: ${result.stderr || result.stdout}` };\n }\n\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const probe = await execInBox(\n container,\n [\n 'bash',\n '-lc',\n '[ -S /var/run/docker.sock ] && docker -H unix:///var/run/docker.sock info >/dev/null 2>&1',\n ],\n { user: 'root' },\n );\n if (probe.exitCode === 0) return { up: true };\n await new Promise((r) => setTimeout(r, 200));\n }\n return { up: false, reason: `dockerd did not become ready within ${String(timeoutMs)}ms` };\n}\n","import { randomBytes } from 'node:crypto';\nimport { buildNoVncUrl, type BoxRecord, type Provider } from '@agentbox/core';\nimport { execInBox } from './docker.js';\nimport { detectEngine } from './sync/host-export.js';\n\nexport interface VncLaunchResult {\n up: boolean;\n reason?: string;\n}\n\n/**\n * Spawn the in-container VNC supervisor (`/usr/local/bin/agentbox-vnc-start`)\n * detached, then poll the container's TCP 6080 to confirm websockify is up.\n * Best-effort, mirroring {@link launchCtlDaemon} — failure is logged but\n * doesn't fail box creation. The password reaches the script through the\n * container's AGENTBOX_VNC_PASSWORD env, set at `docker run` time, so we don't\n * need `-e` on the exec (and the re-launch path on `agentbox start` works\n * without it too).\n */\nexport async function launchVncDaemon(\n container: string,\n timeoutMs = 5000,\n): Promise<VncLaunchResult> {\n const result = await execInBox(container, ['/usr/local/bin/agentbox-vnc-start'], {\n user: 'vscode',\n detach: true,\n });\n if (result.exitCode !== 0) {\n return { up: false, reason: `docker exec failed: ${result.stderr || result.stdout}` };\n }\n\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const probe = await execInBox(\n container,\n ['bash', '-lc', '(echo > /dev/tcp/127.0.0.1/6080) 2>/dev/null'],\n { user: 'vscode' },\n );\n if (probe.exitCode === 0) return { up: true };\n await new Promise((r) => setTimeout(r, 150));\n }\n return { up: false, reason: `websockify did not bind 6080 within ${String(timeoutMs)}ms` };\n}\n\nconst VNC_PASSWORD_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\n/**\n * 8-char password from a 62-symbol alphabet. The 8-char cap is a real RFB\n * protocol limit — VncAuth truncates at compare time, so longer passwords give\n * no security gain. 62^8 ≈ 47 bits; adequate for the loopback-bound surface\n * we expose (host port pinned to 127.0.0.1 + OrbStack's name-based routing,\n * neither of which is reachable from off-host without explicit tunnelling).\n */\nexport function generateVncPassword(): string {\n const bytes = randomBytes(8);\n let out = '';\n for (let i = 0; i < 8; i++) {\n out += VNC_PASSWORD_ALPHABET[bytes[i]! % VNC_PASSWORD_ALPHABET.length];\n }\n return out;\n}\n\n/**\n * Container port the VNC web client (noVNC) binds inside the box. Fixed today;\n * stored on BoxRecord for future-proofing if we ever support multiple displays.\n */\nexport const VNC_CONTAINER_PORT = 6080;\n\nexport interface VncViewerOptions {\n /** Docker only: prefer the raw `127.0.0.1:<host port>` URL over Portless/OrbStack. */\n loopback?: boolean;\n /** Cloud only: signed-URL lifetime in seconds (the provider's default when unset). */\n ttl?: number;\n}\n\nexport interface VncUrls {\n /** OrbStack name-based URL, e.g. http://agentbox-foo.orb.local:6080/... Present only on OrbStack hosts. */\n orbUrl?: string;\n /** Loopback URL via the auto-allocated host port, e.g. http://127.0.0.1:54321/... Present whenever vncHostPort is known. */\n loopbackUrl?: string;\n /** Portless URL, e.g. https://vnc-mybox.localhost/vnc.html?... Present when `portlessVncAlias` is set on the record. */\n portlessUrl?: string;\n}\n\n/**\n * Build the noVNC URLs for a box, given the box record + (host engine).\n * `engine === 'orbstack'` triggers the `<container>.orb.local:6080` route;\n * a stored Portless alias gives `vnc-<name>.localhost`; either engine\n * produces the loopback URL when the host port is resolved.\n * Returns an empty object when VNC isn't enabled or the password isn't known.\n */\nexport function buildVncUrls(\n record: {\n container?: string;\n vncEnabled?: boolean;\n vncHostPort?: number;\n vncContainerPort?: number;\n vncPassword?: string;\n portlessVncAlias?: string;\n portlessVncUrl?: string;\n },\n engine: 'orbstack' | 'docker-desktop' | 'other',\n): VncUrls {\n if (!record.vncEnabled || !record.vncPassword) return {};\n const containerPort = record.vncContainerPort ?? VNC_CONTAINER_PORT;\n const pw = record.vncPassword;\n const urls: VncUrls = {};\n if (engine === 'orbstack' && record.container) {\n urls.orbUrl = buildNoVncUrl(\n `http://${record.container}.orb.local:${String(containerPort)}`,\n pw,\n );\n }\n if (record.vncHostPort) {\n urls.loopbackUrl = buildNoVncUrl(`http://127.0.0.1:${String(record.vncHostPort)}`, pw);\n }\n if (record.portlessVncAlias) {\n urls.portlessUrl = buildNoVncUrl(\n record.portlessVncUrl ?? `https://${record.portlessVncAlias}.localhost`,\n pw,\n );\n }\n return urls;\n}\n\n/**\n * The host-openable noVNC viewer URL for ANY box — the one place that knows a\n * docker box's URL comes off its record while a cloud box's must be minted.\n *\n * Pure URL resolution: no lifecycle side effects, no in-box browser prep (the\n * callers layer those on). Cloud signed URLs expire, so this is called at click\n * time rather than persisted on the record.\n *\n * The docker branch can't go through `provider.resolveUrl({ kind: 'vnc' })` —\n * the docker provider ignores `kind` and always returns the box's *web* URL.\n */\nexport async function resolveVncViewerUrl(\n box: BoxRecord,\n provider: Provider,\n opts: VncViewerOptions = {},\n): Promise<string> {\n if (!box.vncEnabled) {\n throw new Error(`VNC is disabled for box ${box.name} — recreate without \\`--no-vnc\\``);\n }\n if (!box.vncPassword) {\n throw new Error(\n `box ${box.name} has no VNC password recorded — recreate it to enable the desktop`,\n );\n }\n\n if ((box.provider ?? 'docker') === 'docker') {\n const urls = buildVncUrls(box, await detectEngine());\n const resolved = opts.loopback\n ? urls.loopbackUrl\n : (urls.portlessUrl ?? urls.orbUrl ?? urls.loopbackUrl);\n if (!resolved) {\n throw new Error(`VNC URL unavailable for box ${box.name} — the daemon may not be up`);\n }\n return resolved;\n }\n\n const base = await provider.resolveUrl(box, {\n kind: 'vnc',\n ...(opts.ttl ? { ttl: opts.ttl } : {}),\n });\n return buildNoVncUrl(base, box.vncPassword);\n}\n","import { execa } from 'execa';\nimport { mintSshKey } from '@agentbox/sandbox-core';\nimport { execInBox, publishedHostPort } from './docker.js';\n\n/**\n * Container port the in-box sshd binds. Fixed; the host publishes it on an\n * ephemeral `127.0.0.1:<hostPort>` (`docker run -p 127.0.0.1:0:22`) so it's\n * loopback-only. Stored on the BoxRecord as `sshContainerPort` for symmetry\n * with the VNC/web ports.\n */\nexport const SSH_CONTAINER_PORT = 22;\n\nexport interface SshLaunchResult {\n up: boolean;\n reason?: string;\n}\n\n/**\n * Spawn the in-container sshd (`/usr/local/bin/agentbox-sshd-start`) detached as\n * root, then poll container TCP 22 to confirm it bound. Mirrors\n * {@link launchVncDaemon} — best-effort, failure is logged but doesn't fail box\n * creation, and it's idempotent so `agentbox start` can call it blindly. Runs\n * as root (sshd manages /run/sshd + host keys), unlike the vscode-run VNC stack.\n */\nexport async function launchSshdDaemon(\n container: string,\n timeoutMs = 5000,\n): Promise<SshLaunchResult> {\n const result = await execInBox(container, ['/usr/local/bin/agentbox-sshd-start'], {\n user: 'root',\n detach: true,\n });\n if (result.exitCode !== 0) {\n return { up: false, reason: `docker exec failed: ${result.stderr || result.stdout}` };\n }\n\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const probe = await execInBox(\n container,\n ['bash', '-lc', '(echo > /dev/tcp/127.0.0.1/22) 2>/dev/null'],\n { user: 'vscode' },\n );\n if (probe.exitCode === 0) return { up: true };\n await new Promise((r) => setTimeout(r, 150));\n }\n return { up: false, reason: `sshd did not bind 22 within ${String(timeoutMs)}ms` };\n}\n\n/**\n * Install `publicKey` as vscode's sole authorized_keys entry so the host's\n * per-box private key can SSH in. Written as root (chown to vscode, 0700 dir /\n * 0600 file) — mirrors {@link writeBoxEnvFile}. Overwrites rather than appends:\n * one box, one key, and a fresh key each create means no stale entries linger.\n */\nexport async function installAuthorizedKey(\n container: string,\n publicKey: string,\n): Promise<{ ok: true } | { ok: false; reason: string }> {\n const script =\n 'set -e; ' +\n 'install -d -m 700 -o vscode -g vscode /home/vscode/.ssh; ' +\n 'cat > /home/vscode/.ssh/authorized_keys; ' +\n 'chown vscode:vscode /home/vscode/.ssh/authorized_keys; ' +\n 'chmod 600 /home/vscode/.ssh/authorized_keys';\n const result = await execa(\n 'docker',\n ['exec', '--user', 'root', '-i', container, 'sh', '-c', script],\n { input: publicKey.endsWith('\\n') ? publicKey : `${publicKey}\\n`, reject: false },\n );\n if (result.exitCode !== 0) {\n return {\n ok: false,\n reason: `docker exec failed (exit ${String(result.exitCode)}): ${(result.stderr ?? '').toString().slice(0, 400)}`,\n };\n }\n return { ok: true };\n}\n\nexport interface BoxSshSetup {\n /** Ephemeral loopback host port Docker mapped to container :22, or null. */\n sshHostPort: number | null;\n /** Absolute path to the per-box private key (the ssh-config IdentityFile). */\n identityFile: string;\n up: boolean;\n reason?: string;\n}\n\n/**\n * End-to-end sshd bring-up for a box: mint (or reuse) the per-box key under\n * `sshDir`, install its public half into the box's authorized_keys, launch\n * sshd, and resolve the published loopback host port. Used on both create and\n * `agentbox start` — `mintSshKey` reuses an existing key and the install +\n * launch are idempotent, so the restart path just re-resolves the (reallocated)\n * host port. Best-effort: a failure surfaces via `up`/`reason`, never throws.\n */\nexport async function setUpBoxSshd(\n container: string,\n sshDir: string,\n comment: string,\n): Promise<BoxSshSetup> {\n const key = await mintSshKey(sshDir, comment);\n const installed = await installAuthorizedKey(container, key.publicKey);\n if (!installed.ok) {\n return {\n sshHostPort: null,\n identityFile: key.privatePath,\n up: false,\n reason: installed.reason,\n };\n }\n const launch = await launchSshdDaemon(container);\n const sshHostPort = await publishedHostPort(container, SSH_CONTAINER_PORT);\n return { sshHostPort, identityFile: key.privatePath, up: launch.up, reason: launch.reason };\n}\n","/**\n * The single container port AgentBox reserves + publishes for a box's web\n * service. The `-p 127.0.0.1:0:80` mapping is created unconditionally at\n * `create` (immutable after `docker run`); the in-box supervisor forwards :80\n * to the `expose:`-flagged service's port once `agentbox.yaml` is set. Mirrors\n * `VNC_CONTAINER_PORT`. Must equal `RESERVED_WEB_PORT` in @agentbox/ctl.\n */\nexport const WEB_CONTAINER_PORT = 80;\n","import { existsSync } from 'node:fs';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { connect } from 'node:net';\nimport { execa } from 'execa';\nimport type { CheckResult } from '@agentbox/sandbox-core';\n\n/**\n * Portless (https://portless.sh) — a host reverse-proxy that maps\n * `portless alias <name> <port>` to a stable https://<name>.localhost URL.\n *\n * AgentBox uses it to give a box a friendly web URL on the host. Two\n * providers consume these helpers today:\n * - sandbox-docker: aliases the docker port-published web port\n * (`<name>.localhost -> 127.0.0.1:<webHostPort>`). In-box browser\n * remaps `<name>.localhost` to `host.docker.internal` because the box\n * is in a separate net namespace.\n * - sandbox-hetzner: aliases the SSH-forwarded loopback port for the\n * remote VPS's WebProxy. In-box browser remaps to `127.0.0.1` because\n * the box (= VPS) has no separate net namespace.\n *\n * The file lives in sandbox-docker for historical reasons but is shared via\n * a re-export from `@agentbox/sandbox-cloud` (Phase 1 of the hetzner work).\n * The dep direction is `sandbox-cloud → sandbox-docker`, so this is the\n * canonical home; we can't move it the other way without cycle-fixing\n * package.json wiring.\n *\n * Portless is never bundled: AgentBox installs it and starts a proxy only on\n * the user's behalf — an explicit opt-in, or on demand once they have opted in\n * (`ensurePortlessProxy`, because a proxy does not survive a reboot while its\n * route registry does). Every function here is best-effort and must never\n * throw: a Portless failure degrades to the loopback URL.\n */\n\n/**\n * The Portless CLI surface AgentBox depends on. Pinned here so a rename in a\n * future Portless release is a one-line fix. Verified against portless 0.13.0.\n */\nconst PORTLESS_BIN = 'portless';\nconst SUB_VERSION = ['--version'];\nconst SUB_ALIAS = 'alias';\nconst SUB_ALIAS_REMOVE = '--remove';\nconst SUB_GET = 'get';\nconst SUB_SERVICE_INSTALL = ['service', 'install'];\nconst SUB_SERVICE_STATUS = ['service', 'status'];\nconst SUB_SERVICE_UNINSTALL = ['service', 'uninstall'];\n\n/**\n * Throwaway route name used only to ask Portless which scheme/port it serves on.\n * `portless get` answers for any name, registered or not, so this needs no\n * cleanup and never appears in `portless list`.\n */\nconst PORTLESS_PROBE_NAME = 'agentbox-probe';\n\n/**\n * Where Portless installs its macOS OS-startup service. Only used as a fallback\n * when `portless service status` output can't be parsed — the CLI prints this\n * exact path as \"Service entry\" (portless 0.13.0).\n */\nconst PORTLESS_LAUNCHD_PLIST = '/Library/LaunchDaemons/sh.portless.proxy.plist';\n\n/**\n * Port AgentBox starts the Portless proxy on when it sets one up itself.\n * A port >= 1024 needs no root (Portless's own documented no-sudo port);\n * combined with `--no-tls` the whole setup runs without a single prompt.\n */\nexport const PORTLESS_PROXY_PORT = 1355;\n\nexport interface PortlessState {\n /** `portless` resolved on PATH and answered `--version`. */\n installed: boolean;\n /** Portless version string, when installed. */\n version?: string;\n /**\n * A live proxy daemon was found. Note `portless alias` writes the route\n * regardless — the proxy only has to be up for the URL to actually resolve.\n * `false` also covers \"could not tell\".\n */\n proxyRunning: boolean;\n}\n\n/** Whether Portless's own OS-startup service is installed (`portless service`). */\nexport interface PortlessServiceState {\n /** A boot-time service is registered, so the proxy comes back after a reboot. */\n installed: boolean;\n /**\n * The registered service is crash-looping because another proxy already holds its\n * port (Portless's own \"already running on port … with a different config\" exit),\n * so it would NOT bring the proxy back after a reboot. Set only when detected.\n */\n failing?: boolean;\n}\n\n/** What the service writes, each launchd restart, when a proxy it did not start holds the port. */\nconst SERVICE_PORT_CONFLICT = /Proxy is already running on port \\d+/;\n\n/**\n * Whether a service log shows the port-conflict crash loop: the conflict is the last\n * thing written, and it was written recently (launchd's KeepAlive retries about every\n * 10s, so a live loop keeps the file fresh). `sinceMs` narrows it further to lines\n * written after a given moment — right after a re-install, an older loop's lines are\n * still fresh and must not count. Exported for tests.\n */\nexport function serviceLogShowsConflict(\n tail: string,\n mtimeMs: number,\n nowMs: number,\n sinceMs = 0,\n): boolean {\n if (mtimeMs < nowMs - 60_000 || mtimeMs <= sinceMs) return false;\n const lines = tail.trimEnd().split('\\n');\n const recent = lines.slice(-6).join('\\n');\n return SERVICE_PORT_CONFLICT.test(recent);\n}\n\nlet cached: PortlessState | null = null;\n\n/**\n * Probe the host for Portless. Cached per-process like `detectEngine` — the\n * install state cannot change mid-command and the proxy state is only used\n * for a soft hint.\n */\nexport async function detectPortless(): Promise<PortlessState> {\n if (cached !== null) return cached;\n try {\n const ver = await execa(PORTLESS_BIN, SUB_VERSION, { reject: false });\n if (ver.exitCode !== 0) {\n cached = { installed: false, proxyRunning: false };\n return cached;\n }\n cached = {\n installed: true,\n version: (ver.stdout ?? '').trim() || undefined,\n proxyRunning: await isProxyRunning(),\n };\n } catch {\n cached = { installed: false, proxyRunning: false };\n }\n return cached;\n}\n\n/**\n * Drop the per-process probe cache so the next `detectPortless()` re-probes.\n * Called after an install / proxy-start changes the host state, and by tests.\n */\nexport function resetPortlessCache(): void {\n cached = null;\n}\n\n/**\n * Register (or re-point) a static route so the proxy serves\n * https://<name>.localhost -> 127.0.0.1:<port>. Returns whether Portless\n * accepted it. The route is written even when the proxy is down.\n */\nexport async function portlessAlias(name: string, port: number): Promise<boolean> {\n try {\n const r = await execa(PORTLESS_BIN, [SUB_ALIAS, name, String(port)], { reject: false });\n return r.exitCode === 0;\n } catch {\n return false;\n }\n}\n\n/** Remove a static route registered by `portlessAlias`. */\nexport async function portlessUnalias(name: string): Promise<boolean> {\n try {\n const r = await execa(PORTLESS_BIN, [SUB_ALIAS, SUB_ALIAS_REMOVE, name], { reject: false });\n return r.exitCode === 0;\n } catch {\n return false;\n }\n}\n\n/** Compose the URL a static route named `name` is served at, given the proxy mode. */\nfunction composePortlessUrl(name: string, mode: { port: number; tls: boolean }): string {\n const scheme = mode.tls ? 'https' : 'http';\n const isDefaultPort = mode.tls ? mode.port === 443 : mode.port === 80;\n return `${scheme}://${name}.localhost${isDefaultPort ? '' : `:${String(mode.port)}`}`;\n}\n\n/**\n * Resolve the user-facing URL for a registered route. Falls back to the\n * deterministic `https://<name>.localhost` when `portless get` is unavailable\n * (proxy down, route not yet registered, Portless missing).\n *\n * `portless get` is **cwd-sensitive**: run from inside a git worktree it answers\n * with the worktree-scoped name it would give a dev server started there\n * (`https://<worktree>.<name>.localhost`), which is not the route\n * `portless alias` registered. AgentBox always asks about a static alias, so an\n * answer naming a different host is discarded and the URL is composed from the\n * proxy's actual scheme/port instead — otherwise the URL a box (or the hub) is\n * advertised on would depend on which directory the command ran from.\n */\nexport async function portlessGetUrl(name: string): Promise<string> {\n const expectedHost = `${name}.localhost`;\n try {\n const r = await execa(PORTLESS_BIN, [SUB_GET, name], { reject: false });\n const out = (r.stdout ?? '').trim();\n if (r.exitCode === 0 && /^https?:\\/\\//.test(out)) {\n const host = new URL(out).hostname;\n if (host === expectedHost) return out;\n }\n } catch {\n // fall through\n }\n const mode = await portlessConfiguredMode();\n return mode === null ? `https://${expectedHost}` : composePortlessUrl(name, mode);\n}\n\n/** Command the user should run to install Portless. */\nexport function portlessInstallHint(): string {\n return 'npm install -g portless';\n}\n\n/** Command the user should run to bring the Portless proxy up. */\nexport function portlessStartHint(): string {\n return 'portless proxy start';\n}\n\n/**\n * Command that makes the proxy survive a reboot. A manually started proxy dies\n * with the machine and nothing brings it back, which is the whole reason this\n * hint exists separately from `portlessStartHint`.\n */\nexport function portlessServiceHint(): string {\n return 'agentbox install portless';\n}\n\n/**\n * A `doctor` row (see `@agentbox/sandbox-core`'s `CheckResult`) for a provider\n * that benefits from a host Portless proxy — docker on plain Docker Desktop /\n * Linux engine (OrbStack serves `.orb.local` natively, so its `doctorChecks`\n * skips this) and hetzner (the SSH-forwarded loopback only becomes a\n * `<box>.localhost` alias with host Portless). Pure — the caller passes the\n * already-probed state so this stays offline and testable.\n */\nexport function portlessDoctorRow(\n state: PortlessState,\n service?: PortlessServiceState,\n): CheckResult {\n if (!state.installed) {\n return {\n label: 'portless',\n status: 'warn',\n detail: 'not installed — box web URLs fall back to raw loopback ports',\n hint: `recommended: \\`${portlessInstallHint()}\\` for https://<box>.localhost URLs`,\n };\n }\n if (!state.proxyRunning) {\n return {\n label: 'portless',\n status: 'warn',\n detail: 'installed, proxy not running',\n // The OS service is the hint that actually sticks: `proxy start` has to be\n // re-run after every reboot, which is how a host ends up here in the first\n // place. AgentBox also starts a proxy on demand, so this is a nudge, not a\n // blocker.\n hint: `make it permanent: \\`${portlessServiceHint()}\\` (or one-shot: \\`${portlessStartHint()}\\`)`,\n };\n }\n const running = state.version ? `running · v${state.version}` : 'running';\n if (service?.failing === true) {\n return {\n label: 'portless',\n status: 'warn',\n detail: `${running} · startup service failing (another proxy holds its port)`,\n hint: `repair it: \\`${portlessServiceHint()}\\` (stops the other proxy, asks for your password)`,\n };\n }\n if (service?.installed === false) {\n return {\n label: 'portless',\n status: 'ok',\n detail: `${running} · no OS service (won't survive a reboot)`,\n hint: `optional: \\`${portlessServiceHint()}\\` to start it at boot`,\n };\n }\n return { label: 'portless', status: 'ok', detail: running };\n}\n\nexport interface PortlessBrowserEnvOptions {\n /**\n * Where Chromium should resolve `<box-name>.localhost` to when running\n * inside the box. Docker boxes pass `host.docker.internal` (the host\n * gateway baked into every container's `/etc/hosts`). Hetzner boxes —\n * where the box *is* the VPS and WebProxy listens on the VPS's loopback —\n * pass `127.0.0.1`.\n */\n mapTarget: string;\n}\n\n/**\n * Box env that makes the in-box browser (agent-browser → Chromium) load the\n * box's Portless `<name>.localhost` URL via the *host* Portless proxy — so the\n * web app is reachable on the exact URL the host browser uses.\n *\n * Chromium hard-codes `*.localhost` → loopback and ignores `/etc/hosts`, so\n * `--host-resolver-rules` (passed through agent-browser's `AGENT_BROWSER_ARGS`)\n * remaps the box's hostname to `opts.mapTarget` — the address that, from\n * inside the box, actually reaches the host Portless proxy.\n * `IGNORE_HTTPS_ERRORS` covers a TLS host proxy whose self-signed CA the box\n * doesn't trust.\n */\nexport function portlessBrowserEnv(\n boxName: string,\n opts: PortlessBrowserEnvOptions,\n): Record<string, string> {\n return {\n AGENT_BROWSER_ARGS: `--host-resolver-rules=MAP ${boxName}.localhost ${opts.mapTarget}`,\n AGENT_BROWSER_IGNORE_HTTPS_ERRORS: '1',\n };\n}\n\n/** Install the Portless CLI globally (`npm install -g portless`). Never throws. */\nexport async function installPortless(): Promise<boolean> {\n try {\n const r = await execa('npm', ['install', '-g', 'portless'], { reject: false });\n return r.exitCode === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Start a Portless proxy with no TLS on a no-root port (`PORTLESS_PROXY_PORT` by\n * default) — `portless proxy start --no-tls -p <port>`. No sudo, no CA-trust\n * prompt. Idempotent: Portless reports \"already running\" (exit 0) if one is\n * already up. Never throws.\n *\n * `port` exists so a restart lands on the port this host is *already* configured\n * for: switching ports rewrites every `<box>.localhost` URL, which is exactly\n * what must not happen behind the user's back (see `ensurePortlessProxy`).\n */\nexport async function startPortlessProxy(port: number = PORTLESS_PROXY_PORT): Promise<boolean> {\n try {\n const r = await execa(PORTLESS_BIN, ['proxy', 'start', '--no-tls', '-p', String(port)], {\n reject: false,\n });\n return r.exitCode === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Absolute path to the `portless` binary. Needed because the macOS elevation\n * shell (`osascript … with administrator privileges`) runs with a minimal PATH\n * (`/usr/bin:/bin:/usr/sbin:/sbin`) that misses nvm / user npm prefixes where\n * `portless` usually lives. Falls back to the bare name when it can't resolve.\n */\nasync function resolvePortlessBin(): Promise<string> {\n try {\n // `command -v` resolves PATH the same way the shell would for the current\n // (login) environment, unlike the stripped-down elevated shell.\n const r = await execa('command', ['-v', PORTLESS_BIN], { reject: false, shell: true });\n const out = (r.stdout ?? '').trim();\n if (r.exitCode === 0 && out.startsWith('/')) return out;\n } catch {\n // fall through\n }\n return PORTLESS_BIN;\n}\n\n/** Result of a root proxy-start attempt. */\nexport type RootProxyStartResult =\n | 'started' // proxy is up on :443 (or was already)\n | 'cancelled' // user dismissed the elevation prompt — caller should fall back\n | 'failed'; // elevation ran but the proxy did not come up\n\n/** Quote a string for embedding inside an AppleScript double-quoted literal. */\nfunction escapeForAppleScript(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Single-quote a string for `/bin/sh`. Needed for the resolved portless path,\n * which can live under a home dir with spaces (`/Users/Jo Smith/.nvm/…`) that\n * the elevated shell would otherwise word-split. Single quotes survive the\n * outer AppleScript double-quoted literal untouched.\n */\nfunction shellSingleQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * Start the default Portless proxy — HTTPS on :443 — which requires root.\n * Portless self-elevates via its own `sudo`, so all we do is run\n * `portless proxy start && portless trust` once, as root, surfacing a single\n * password prompt. `trust` is bundled so the host browser trusts the\n * self-signed CA (otherwise 443 shows cert warnings); it is idempotent.\n *\n * On macOS the prompt is the native GUI dialog (`osascript … with administrator\n * privileges`); elsewhere we inherit the terminal so Portless's own `sudo`\n * prompt is answerable. Never throws. Returns `'cancelled'` when the user\n * dismisses the dialog so the caller can fall back to the no-root port.\n */\nexport async function startPortlessProxyRoot(): Promise<RootProxyStartResult> {\n const bin = await resolvePortlessBin();\n try {\n if (process.platform === 'darwin') {\n // Both commands run in one elevated shell so the user is asked once.\n const q = shellSingleQuote(bin);\n const shellCmd = `${q} proxy start && ${q} trust`;\n const script =\n `do shell script \"${escapeForAppleScript(shellCmd)}\" ` +\n `with administrator privileges ` +\n `with prompt \"AgentBox wants to start the Portless proxy on port 443.\"`;\n const r = await execa('osascript', ['-e', script], { reject: false });\n if (r.exitCode === 0) return 'started';\n // osascript reports \"User canceled. (-128)\" when the dialog is dismissed.\n if (/User canceled|-128/i.test(r.stderr ?? '')) return 'cancelled';\n return 'failed';\n }\n // Non-macOS: let Portless's own sudo prompt reach the terminal.\n const r = await execa(bin, ['proxy', 'start'], { reject: false, stdio: 'inherit' });\n if (r.exitCode !== 0) return 'failed';\n await execa(bin, ['trust'], { reject: false, stdio: 'inherit' });\n return 'started';\n } catch {\n return 'failed';\n }\n}\n\n/**\n * Whether Portless's OS-startup service is installed — the only thing that\n * brings the proxy back after a reboot. Parses `portless service status`, whose\n * output carries an `Installed: yes|no` line (portless 0.13.0); if that shape\n * ever changes, fall back to the macOS LaunchDaemon path the same command\n * prints. Never throws — an unreadable status reads as \"not installed\", which\n * only costs the user an extra nudge.\n */\nexport async function portlessServiceStatus(\n opts: { sinceMs?: number } = {},\n): Promise<PortlessServiceState> {\n try {\n const r = await execa(PORTLESS_BIN, SUB_SERVICE_STATUS, { reject: false });\n const stdout = r.stdout ?? '';\n const m = /^\\s*Installed:\\s*(yes|no)\\s*$/im.exec(stdout);\n if (m) {\n const installed = m[1]?.toLowerCase() === 'yes';\n if (!installed) return { installed };\n // \"Installed: yes\" plus \"Proxy on 443: responding\" can both be true while the\n // service itself crash-loops: the responding proxy is one it did not start. The\n // service log is the only place that says so.\n const dir = /^\\s*State directory:\\s*(.+?)\\s*$/im.exec(stdout)?.[1];\n if (dir && (await serviceLogFailing(join(dir, 'service.log'), opts.sinceMs))) {\n return { installed, failing: true };\n }\n return { installed };\n }\n } catch {\n // fall through to the filesystem probe\n }\n if (process.platform === 'darwin') return { installed: existsSync(PORTLESS_LAUNCHD_PLIST) };\n return { installed: false };\n}\n\nasync function serviceLogFailing(path: string, sinceMs?: number): Promise<boolean> {\n try {\n const st = await stat(path);\n const text = await readFile(path, 'utf8');\n return serviceLogShowsConflict(text.slice(-4000), st.mtimeMs, Date.now(), sinceMs);\n } catch {\n return false;\n }\n}\n\n/**\n * Install Portless's OS-startup service (`portless service install`) so the\n * proxy is up after every reboot, and trust its CA. Needs root — same elevation\n * shape as `startPortlessProxyRoot`, so the user is asked for a password once.\n *\n * Note the service runs Portless's *default* mode: HTTPS on :443. A host that\n * was on the no-root `:1355` proxy therefore moves to clean `https://<box>.localhost`\n * URLs. AgentBox re-resolves every URL through `portless get`, so that is a\n * display change rather than breakage — but it is user-visible, so callers\n * should say so before prompting.\n */\nexport async function installPortlessService(): Promise<RootProxyStartResult> {\n return (await installPortlessServiceDetailed()).result;\n}\n\n/**\n * `installPortlessService` plus the elevated shell's error text on failure, which the\n * bare result throws away — without it a failed install says nothing about why.\n */\nexport async function installPortlessServiceDetailed(): Promise<{\n result: RootProxyStartResult;\n detail?: string;\n}> {\n const bin = await resolvePortlessBin();\n try {\n if (process.platform === 'darwin') {\n const q = shellSingleQuote(bin);\n // A Portless proxy already on :443 that the service did not start (an older\n // `proxy start`, or an orphan of a previous service) keeps the new service from\n // binding: launchd then restarts it forever while that other proxy answers, so the\n // install looks fine and is not. Portless's own pre-install stop can miss one with\n // no pid file, so stop every Portless listener on the port first, as root, in the\n // same prompt. Only processes whose command names portless are touched.\n const stopListeners =\n 'for p in $(/usr/sbin/lsof -ti tcp:443 -sTCP:LISTEN); do ' +\n '/bin/ps -o command= -p $p | /usr/bin/grep -q portless && /bin/kill $p; done; ' +\n 'sleep 1';\n const shellCmd = `${stopListeners}; ${q} ${SUB_SERVICE_INSTALL.join(' ')} && ${q} trust`;\n const script =\n `do shell script \"${escapeForAppleScript(shellCmd)}\" ` +\n `with administrator privileges ` +\n `with prompt \"AgentBox wants to start the Portless proxy at login.\"`;\n const r = await execa('osascript', ['-e', script], { reject: false });\n if (r.exitCode === 0) return { result: 'started' };\n if (/User canceled|-128/i.test(r.stderr ?? '')) return { result: 'cancelled' };\n return { result: 'failed', detail: lastLine(r.stderr ?? '') };\n }\n const r = await execa(bin, SUB_SERVICE_INSTALL, { reject: false, stdio: 'inherit' });\n if (r.exitCode !== 0) return { result: 'failed' };\n await execa(bin, ['trust'], { reject: false, stdio: 'inherit' });\n return { result: 'started' };\n } catch (err) {\n return { result: 'failed', detail: err instanceof Error ? err.message : String(err) };\n }\n}\n\nfunction lastLine(text: string): string | undefined {\n // osascript prefixes the shell's output with \"0:12: execution error: \".\n const line = text\n .trim()\n .split('\\n')\n .pop()\n ?.replace(/^\\d+:\\d+: execution error: /, '')\n .trim();\n return line ? line : undefined;\n}\n\n/** Remove the OS-startup service. Never throws. */\nexport async function uninstallPortlessService(): Promise<boolean> {\n const bin = await resolvePortlessBin();\n try {\n if (process.platform === 'darwin') {\n const shellCmd = `${shellSingleQuote(bin)} ${SUB_SERVICE_UNINSTALL.join(' ')}`;\n const script =\n `do shell script \"${escapeForAppleScript(shellCmd)}\" with administrator privileges ` +\n `with prompt \"AgentBox wants to remove the Portless startup service.\"`;\n const r = await execa('osascript', ['-e', script], { reject: false });\n return r.exitCode === 0;\n }\n const r = await execa(bin, SUB_SERVICE_UNINSTALL, { reject: false, stdio: 'inherit' });\n return r.exitCode === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * The proxy mode this host is already configured for, or null when Portless has\n * never served anything here. Read from `portless get` (the persisted route\n * registry), so it survives the proxy dying — which is the whole point: it tells\n * us which mode to put *back*.\n */\nexport async function portlessConfiguredMode(): Promise<{ port: number; tls: boolean } | null> {\n try {\n const r = await execa(PORTLESS_BIN, [SUB_GET, PORTLESS_PROBE_NAME], { reject: false });\n const out = (r.stdout ?? '').trim();\n if (r.exitCode !== 0 || !/^https?:\\/\\//.test(out)) return null;\n const u = new URL(out);\n const tls = u.protocol === 'https:';\n const port = u.port ? Number.parseInt(u.port, 10) : tls ? 443 : 80;\n return Number.isFinite(port) ? { port, tls } : null;\n } catch {\n return null;\n }\n}\n\n/** Ports below 1024 can only be bound by root. */\nfunction needsRoot(port: number): boolean {\n return port < 1024;\n}\n\n/**\n * Make sure a Portless proxy is actually live, starting one if it isn't, and\n * return the resulting state.\n *\n * This exists because a proxy is not durable state: it dies on reboot, and\n * nothing (short of the OS service) brings it back — while the route registry\n * *is* durable, so `portless get` keeps answering with a URL that resolves to\n * nothing. Every AgentBox entry point that is about to hand out a\n * `<name>.localhost` URL should call this first.\n *\n * **It restarts the mode the host is already configured for, and never switches\n * modes on its own.** The scheme and port are part of the URL, and that URL is\n * shared: a cloud box mirrors the host proxy's mode inside the box, and\n * `agentbox.yaml` / env templates written against `{{AGENTBOX_BOX_HOST}}` spell\n * `https://<box>.localhost` by hand. Quietly coming back on `--no-tls -p 1355`\n * would leave the host serving one URL while the box, and everything written\n * against it, still expects another — the exact symmetry this integration exists\n * to provide.\n *\n * So when the configured mode needs root (:443, the clean HTTPS default) and we\n * are not allowed to ask for a password, this starts nothing and reports the\n * proxy as down; the caller points the user at `agentbox install portless`,\n * which fixes it permanently and without a prompt from then on. Never throws.\n */\nexport async function ensurePortlessProxy(\n opts: { allowRootPrompt?: boolean } = {},\n): Promise<PortlessState> {\n let state = await detectPortless();\n if (!state.installed || state.proxyRunning) return state;\n\n const mode = await portlessConfiguredMode();\n // Nothing configured yet (a host that has never run a proxy): the clean\n // HTTPS :443 mode is the one to aim for, same as the first-run opt-in.\n const wantsRoot = mode === null || needsRoot(mode.port);\n\n if (wantsRoot) {\n if (opts.allowRootPrompt !== true) return state; // caller warns; no silent downgrade\n await startPortlessProxyRoot();\n resetPortlessCache();\n state = await detectPortless();\n if (state.proxyRunning) return state;\n // Elevation refused or failed. Falling back to the no-root port is a mode\n // *change*, so it is only acceptable here: an interactive caller who has\n // just been told what is happening, on a host with no live URLs to break.\n }\n\n await startPortlessProxy(\n mode !== null && !needsRoot(mode.port) ? mode.port : PORTLESS_PROXY_PORT,\n );\n resetPortlessCache();\n return detectPortless();\n}\n\n/**\n * Candidate Portless state directories. `$PORTLESS_STATE_DIR` wins outright;\n * otherwise Portless keeps state in `~/.portless` — even for the root :443\n * proxy, whose `proxy.pid` there stays owned by the invoking user (verified\n * against portless 0.13.0). `/tmp/portless` is retained as a legacy fallback.\n */\nfunction portlessStateDirCandidates(): string[] {\n const env = process.env['PORTLESS_STATE_DIR'];\n if (env && env.trim().length > 0) return [env.trim()];\n return ['/tmp/portless', join(homedir(), '.portless')];\n}\n\n/**\n * Whether `pid` names a live process. `process.kill(pid, 0)` succeeds for a\n * process we own; it throws `EPERM` for one owned by another user (the proxy\n * runs as root when bound to :443 via sudo) — that still means it is alive.\n * Only `ESRCH` (\"no such process\") is a dead pid.\n */\nfunction pidAlive(pid: number): boolean {\n if (!Number.isFinite(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0); // signal 0 = existence/permission check only\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/** Read `<dir>/proxy.pid`, returning the pid or null when absent/garbage. */\nasync function readProxyPid(dir: string): Promise<number | null> {\n try {\n const raw = await readFile(join(dir, 'proxy.pid'), 'utf8');\n const pid = Number.parseInt(raw.trim(), 10);\n return Number.isFinite(pid) && pid > 0 ? pid : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The Portless state directory whose `proxy.pid` names a live process — i.e.\n * where the *running* proxy keeps its route registry. `null` when no proxy is\n * up. This is the authoritative way to pick between `/tmp/portless` and\n * `~/.portless` (they can both exist; only one has the live proxy).\n */\nasync function findLivePortlessStateDir(): Promise<string | null> {\n for (const dir of portlessStateDirCandidates()) {\n const pid = await readProxyPid(dir);\n if (pid !== null && pidAlive(pid)) return dir;\n }\n return null;\n}\n\n/**\n * Resolve the host Portless state directory to bind-mount into a box (so the\n * in-box `portless` CLI shares the host's route registry). Precedence:\n * 1. an explicit override — the `portless.stateDir` config key;\n * 2. `$PORTLESS_STATE_DIR`;\n * 3. the directory of the *running* proxy (authoritative);\n * 4. whichever of `~/.portless` / `/tmp/portless` already exists;\n * 5. `~/.portless` as the final fallback.\n * Does not create the directory.\n */\nexport async function resolvePortlessHostStateDir(override?: string): Promise<string> {\n if (override && override.trim().length > 0) return override.trim();\n const env = process.env['PORTLESS_STATE_DIR'];\n if (env && env.trim().length > 0) return env.trim();\n const live = await findLivePortlessStateDir();\n if (live) return live;\n const home = join(homedir(), '.portless');\n if (existsSync(home)) return home;\n if (existsSync('/tmp/portless')) return '/tmp/portless';\n return home;\n}\n\n/** Whether something accepts a TCP connection on 127.0.0.1:<port>. */\nasync function tcpAccepts(port: number, timeoutMs = 400): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = connect({ host: '127.0.0.1', port });\n const done = (result: boolean): void => {\n socket.destroy();\n resolve(result);\n };\n socket.setTimeout(timeoutMs);\n socket.once('connect', () => {\n done(true);\n });\n socket.once('timeout', () => {\n done(false);\n });\n socket.once('error', () => {\n done(false);\n });\n });\n}\n\n/**\n * Best-effort: is a Portless proxy currently *serving* on this host.\n *\n * Two signals, both about the running process rather than the persisted config\n * (which survives reboots and would otherwise report a proxy that is long gone):\n * 1. a live `proxy.pid` in a Portless state dir — cheap and authoritative for\n * a daemonized proxy;\n * 2. something accepting TCP on the port Portless is configured to serve —\n * covers a `--foreground` proxy, which writes no pid file.\n *\n * This deliberately does NOT scan the process table. `pgrep -f \"portless proxy\"`\n * matches any command line that merely *contains* that phrase — a shell that ran\n * the command, an editor, a script, an agent transcript — so it reported a live\n * proxy on hosts that had none. Every \"is it up?\" decision here (start one or\n * not, advertise the URL or not) inverts on that answer, so a false positive is\n * worse than a missed detection: it is what leaves a user with `.localhost` URLs\n * that resolve to nothing.\n */\nasync function isProxyRunning(): Promise<boolean> {\n if ((await findLivePortlessStateDir()) !== null) return true;\n const mode = await portlessConfiguredMode();\n if (mode === null) return false;\n return tcpAccepts(mode.port);\n}\n","import { execa } from 'execa';\nimport { mkdir, readdir, rm, stat } from 'node:fs/promises';\nimport { homedir, platform } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { sanitizeMnemonic } from '@agentbox/config';\n\n/**\n * Directories whose contents are either platform-specific (built native modules,\n * compiled outputs) or large enough to be wasteful to include in a frozen\n * workspace snapshot. Pruned from the snapshot tree *after* the APFS clone\n * — removing CoW-cloned entries is essentially free.\n */\nexport const EXCLUDE_DIRS: ReadonlySet<string> = new Set([\n // AgentBox's own durable host dir (`download --backup` writes a bot's\n // workspace and gateway identity under it). The tar seed excludes it too;\n // pruning it here as well keeps the clone from copying gigabytes of backups\n // that are then dropped on the way in.\n '.agentbox',\n 'node_modules',\n '.next',\n '.nuxt',\n '.turbo',\n '.svelte-kit',\n 'dist',\n 'build',\n 'out',\n 'target',\n '.venv',\n '__pycache__',\n '.cache',\n '.parcel-cache',\n]);\n\nexport const SNAPSHOTS_ROOT = join(homedir(), '.agentbox', 'snapshots');\n\n/**\n * `<id>-<n>-<mnemonic>` when `projectIndex` is set (post-feature boxes — all\n * new boxes), else `<id>-<mnemonic>` (legacy pre-feature fallback). Mirrors\n * `boxDirSegment` in `host-export.ts` — kept structurally compatible so the\n * snapshot dir can be looked up alongside its box dir.\n */\nexport function snapshotPathFor(box: { id: string; name: string; projectIndex?: number }): string {\n const mnemonic = sanitizeMnemonic(box.name);\n const n = box.projectIndex;\n const segment =\n typeof n === 'number' && Number.isFinite(n) && n > 0\n ? `${box.id}-${String(n)}-${mnemonic}`\n : `${box.id}-${mnemonic}`;\n return join(SNAPSHOTS_ROOT, segment);\n}\n\n/**\n * Walk a directory tree and return absolute paths of every directory whose\n * basename matches `EXCLUDE_DIRS`. Does not descend into a matched directory.\n * Pure (modulo `fs.readdir`) — easy to unit-test against a fixture tree.\n */\nexport async function findExcludedDirs(\n root: string,\n excluded: ReadonlySet<string> = EXCLUDE_DIRS,\n): Promise<string[]> {\n const matches: string[] = [];\n const walk = async (dir: string): Promise<void> => {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const abs = join(dir, entry.name);\n if (excluded.has(entry.name)) {\n matches.push(abs);\n continue; // do not descend\n }\n await walk(abs);\n }\n };\n await walk(root);\n return matches;\n}\n\nexport interface CreateSnapshotOptions {\n source: string;\n destination: string;\n excluded?: ReadonlySet<string>;\n}\n\nexport interface CreateSnapshotResult {\n destination: string;\n prunedPaths: string[];\n}\n\n/**\n * Create a frozen workspace snapshot. On macOS (APFS) this is an instant CoW\n * clone via `cp -cR`; on other platforms it falls back to plain `cp -R`\n * (slow, but functional — the production fallback will be `rsync --exclude`).\n *\n * After the copy, prune all `EXCLUDE_DIRS` directories so the snapshot is free\n * of platform-specific artifacts before it becomes the overlay's lower layer.\n */\nexport async function createSnapshot(opts: CreateSnapshotOptions): Promise<CreateSnapshotResult> {\n const source = resolve(opts.source);\n const destination = resolve(opts.destination);\n const excluded = opts.excluded ?? EXCLUDE_DIRS;\n\n await mkdir(SNAPSHOTS_ROOT, { recursive: true });\n\n // `cp -c` only exists on macOS and is the APFS clone flag.\n const cpArgs = platform() === 'darwin' ? ['-cR'] : ['-R'];\n await execa('cp', [...cpArgs, `${source}/`, destination]);\n\n const toPrune = await findExcludedDirs(destination, excluded);\n await Promise.all(toPrune.map((p) => rm(p, { recursive: true, force: true })));\n\n return { destination, prunedPaths: toPrune };\n}\n\n/** Guard used by tests + by `create.ts` when we don't want to clobber a path. */\nexport async function snapshotExists(path: string): Promise<boolean> {\n try {\n const s = await stat(path);\n return s.isDirectory();\n } catch {\n return false;\n }\n}\n","import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { basename, join } from 'node:path';\nimport { execa } from 'execa';\nimport {\n hashProjectPath,\n projectDirSegment,\n sanitizeMnemonic,\n setConfigValue,\n} from '@agentbox/config';\nimport { readCliStamp } from '@agentbox/sandbox-core';\nimport { execInBox, removeImage } from './docker.js';\nimport { DEFAULT_BOX_IMAGE } from './image.js';\nimport { computeDockerContextFingerprint, readPreparedDockerState } from './prepared-state.js';\nimport type { BoxRecord, GitWorktreeRecord } from './state.js';\n\nexport const CHECKPOINTS_ROOT = join(homedir(), '.agentbox', 'checkpoints');\n\n/**\n * All per-project checkpoint *image* tags share this prefix. `prune --all`\n * allowlists by it (parallel to the old volume prefix) and `agentbox status`\n * /`inspect` recognizes a box's image as a checkpoint from this prefix.\n */\nexport const CHECKPOINT_IMAGE_PREFIX = 'agentbox-ckpt-';\n\nexport type CheckpointType = 'layered' | 'flattened';\n\n/**\n * Deterministic image tag for a project checkpoint. The repository segment is\n * keyed on the project root (same hash the per-project config dir uses) and\n * carries a mnemonic suffix so `docker images` reads self-describing. The\n * mnemonic is joined with `_` (not `-`) so the leading 16 hex chars remain\n * unambiguous and the existing `agentbox-ckpt-*` prune glob still matches.\n * Pure — unit-tested directly.\n */\nexport function checkpointImageTag(projectRoot: string, name: string): string {\n const mnemonic = sanitizeMnemonic(basename(projectRoot));\n return `${CHECKPOINT_IMAGE_PREFIX}${hashProjectPath(projectRoot)}_${mnemonic}:${name}`;\n}\n\nexport interface CheckpointManifest {\n /**\n * Schema history:\n * 2 — original fields (image, parents, base, worktrees, source*, createdAt)\n * 3 — adds `baseProvider`, `baseFingerprint`, `cliVersion`. A checkpoint\n * captured before the rebuild that produced the *current* base\n * image will have a stale `baseFingerprint`; the restore path warns\n * loudly so the user knows the box won't see the new base layers\n * until the checkpoint is removed and recaptured.\n */\n schema: 2 | 3;\n name: string;\n type: CheckpointType;\n /** Local Docker image tag this checkpoint resolves to (`agentbox-ckpt-<hash>:<name>`). */\n image: string;\n /**\n * For a `layered` checkpoint, the older checkpoint refs this commit stacks\n * on — i.e. the chain the *source* box was built from (upper-most first,\n * base-most last). `[]` for a `flattened` checkpoint (self-contained,\n * exported+rebuilt as a single layer) or a layered checkpoint taken from a\n * box that itself started from bare host code.\n */\n parents: string[];\n base: 'worktree' | 'workspace';\n sourceBoxId: string;\n sourceBoxName: string;\n /**\n * Source box's per-worktree paths so a restored box can re-bind\n * `/workspace` (and `/workspace/<sub>`) without rerunning `seedWorkspace`.\n * `docker commit` does NOT capture bind-mounted content, so the captured\n * image's `/workspace` is empty — the actual worktree files live under\n * `gitWorktreePath` (preserved in the image's writable layer). On restore,\n * `bindWorktrees` reads these to wire the binds back. Absent only for\n * no-git boxes (their `seedWorkspaceFromDir` puts files directly in\n * `/workspace`, which the bind logic doesn't touch).\n */\n worktrees?: GitWorktreeRecord[];\n /**\n * Provider whose base-image fingerprint this checkpoint was captured\n * against. Schema-3+ only. Always `'docker'` today (docker is the only\n * provider with local checkpoints); cloud-provider checkpoints will set\n * it accordingly when they land.\n */\n baseProvider?: 'docker' | 'daytona' | 'hetzner';\n /**\n * Build-context fingerprint of the base image at the time the checkpoint\n * was captured. Schema-3+ only. Missing → schema 2 → \"unknown\n * fingerprint\" (caller surfaces a softer \"this checkpoint predates\n * versioning\" warning).\n */\n baseFingerprint?: string;\n /** CLI version that captured the checkpoint. Schema-3+ only. */\n cliVersion?: string;\n /**\n * The agent set the source box was created for (`BoxRecord.agents`), so a\n * restore into a box built for a DIFFERENT agent can say so.\n *\n * Deliberately NOT behind a schema bump: `readManifest` hard-gates on the\n * schema number, so bumping would make every new checkpoint vanish from an\n * older CLI's `agentbox checkpoints`, while an older CLI that ignores this\n * field behaves exactly as it does today. Advisory data — losing a warning is\n * far cheaper than losing sight of a checkpoint.\n *\n * Absent means UNKNOWN, never \"no agents\": every checkpoint captured before\n * this field existed lacks it, as does any box predating per-agent selection.\n * Callers must stay silent on absent, or every old checkpoint warns.\n */\n agents?: string[];\n createdAt: string;\n}\n\nexport interface CheckpointInfo {\n name: string;\n /** Host dir holding `manifest.json` (`~/.agentbox/checkpoints/<hash>/<name>`). */\n dir: string;\n manifest: CheckpointManifest;\n}\n\nexport function projectCheckpointsDir(projectRoot: string): string {\n return join(CHECKPOINTS_ROOT, projectDirSegment(projectRoot));\n}\n\nfunction checkpointDir(projectRoot: string, name: string): string {\n return join(projectCheckpointsDir(projectRoot), name);\n}\n\nasync function readManifest(dir: string): Promise<CheckpointManifest | null> {\n try {\n const raw = await readFile(join(dir, 'manifest.json'), 'utf8');\n const m = JSON.parse(raw) as CheckpointManifest;\n // Accept schema 2 (legacy — no baseFingerprint, restore warns softly)\n // and schema 3 (current — full versioning). Anything else is treated\n // as unreadable so an opaque file can't break list/resolve.\n if (m.schema !== 2 && m.schema !== 3) return null;\n return m;\n } catch {\n return null;\n }\n}\n\n/**\n * Read every valid checkpoint manifest directly under `root` (a project's\n * `<hash>-<mnemonic>` dir), sorted by `createdAt`. Shared by the scoped and\n * global listers. Missing root / unreadable manifests are skipped.\n */\nasync function listCheckpointsInDir(root: string): Promise<CheckpointInfo[]> {\n let entries: string[];\n try {\n entries = (await readdir(root, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n return [];\n }\n const out: CheckpointInfo[] = [];\n for (const name of entries) {\n const dir = join(root, name);\n const manifest = await readManifest(dir);\n if (manifest) out.push({ name, dir, manifest });\n }\n out.sort((a, b) => a.manifest.createdAt.localeCompare(b.manifest.createdAt));\n return out;\n}\n\nexport async function listCheckpoints(projectRoot: string): Promise<CheckpointInfo[]> {\n return listCheckpointsInDir(projectCheckpointsDir(projectRoot));\n}\n\nexport interface CheckpointProjectGroup {\n /** `<hash>-<mnemonic>` dir name under CHECKPOINTS_ROOT. */\n segment: string;\n items: CheckpointInfo[];\n}\n\n/**\n * Every project's docker checkpoints, one group per project dir. Mirrors\n * `listAllCheckpointImages`' two-level scan but returns the full manifests so\n * `checkpoints -g` can render them. Best-effort: missing root / unreadable\n * project dirs are skipped, and segments with zero valid manifests are dropped.\n */\nexport async function listAllCheckpoints(): Promise<CheckpointProjectGroup[]> {\n let segments: string[];\n try {\n segments = (await readdir(CHECKPOINTS_ROOT, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n return [];\n }\n const out: CheckpointProjectGroup[] = [];\n for (const segment of segments) {\n const items = await listCheckpointsInDir(join(CHECKPOINTS_ROOT, segment));\n if (items.length > 0) out.push({ segment, items });\n }\n return out;\n}\n\nexport async function resolveCheckpoint(\n projectRoot: string,\n ref: string,\n): Promise<CheckpointInfo | null> {\n const dir = checkpointDir(projectRoot, ref);\n const manifest = await readManifest(dir);\n if (!manifest) return null;\n return { name: ref, dir, manifest };\n}\n\n/**\n * Walk every per-project checkpoint manifest under CHECKPOINTS_ROOT and\n * return the union of their `image` tags. Used by `pruneBoxes({ all: true })`\n * to keep an image alive as long as any manifest on disk points at it —\n * destroy leaves the checkpoint behind by design, and the user expects to\n * still be able to start a new box from it long after the source box is gone.\n *\n * Best-effort, matching listSnapshotDirs / listBoxDirs in lifecycle.ts:\n * missing root, unreadable / non-schema-2 manifests, and non-directory\n * entries at any level are all skipped silently.\n */\nexport async function listAllCheckpointImages(): Promise<string[]> {\n let projectDirs: string[];\n try {\n projectDirs = (await readdir(CHECKPOINTS_ROOT, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n return [];\n }\n const out = new Set<string>();\n for (const proj of projectDirs) {\n const projPath = join(CHECKPOINTS_ROOT, proj);\n let names: string[];\n try {\n names = (await readdir(projPath, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n continue;\n }\n for (const name of names) {\n const manifest = await readManifest(join(projPath, name));\n if (manifest) out.add(manifest.image);\n }\n }\n return Array.from(out);\n}\n\nexport async function removeCheckpoint(projectRoot: string, ref: string): Promise<boolean> {\n const dir = checkpointDir(projectRoot, ref);\n const manifest = await readManifest(dir);\n if (!manifest) return false;\n await rm(dir, { recursive: true, force: true });\n // Image is the durable artifact; best-effort because nothing else references\n // it once the manifest is gone. `-f` so a stale tag without containers is\n // dropped even if Docker considers it \"in use\" via dangling layers.\n await removeImage(manifest.image, { force: true });\n return true;\n}\n\n/**\n * Next `<boxName>-<n>` given the names already present. Monotonic per\n * box-name; gaps from deleted checkpoints are skipped (max+1, never\n * recycled). Pure — unit-tested directly.\n */\nexport function computeNextCheckpointName(existingNames: string[], boxName: string): string {\n const re = new RegExp(`^${boxName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}-(\\\\d+)$`);\n let max = 0;\n for (const n of existingNames) {\n const m = re.exec(n);\n if (m) max = Math.max(max, Number(m[1]));\n }\n return `${boxName}-${String(max + 1)}`;\n}\n\nasync function nextCheckpointName(projectRoot: string, boxName: string): Promise<string> {\n const existing = await listCheckpoints(projectRoot);\n return computeNextCheckpointName(\n existing.map((c) => c.name),\n boxName,\n );\n}\n\nfunction chainDepth(box: BoxRecord): number {\n return box.checkpointSource?.chain.length ?? 0;\n}\n\nexport interface CreateCheckpointOptions {\n box: BoxRecord;\n projectRoot: string;\n name?: string;\n /** Force a flattened (export+`FROM scratch` rebuild) capture. */\n merged?: boolean;\n setDefault?: boolean;\n /**\n * If an existing checkpoint has the same name, delete it (manifest + image)\n * before capturing. Without this, name collisions throw `CheckpointError`.\n * Useful for idempotent re-runs from the in-box agent (`agentbox-ctl\n * checkpoint --replace`), e.g. when the previous invocation's stdout was\n * lost mid-flight and the agent can't tell whether it succeeded.\n */\n replace?: boolean;\n /** checkpoint.maxLayers — auto-flatten when the source chain is at/over this. */\n maxLayers: number;\n onLog?: (line: string) => void;\n}\n\n/**\n * Run the pre-commit cleanup in the box. Script is image-baked at\n * /usr/local/bin/agentbox-checkpoint-cleanup. Best-effort: a non-zero exit\n * from the cleanup logs but does not abort the capture (the script itself\n * is also `set +e` for the same reason).\n */\nasync function runCleanup(container: string, log: (line: string) => void): Promise<void> {\n const r = await execInBox(container, ['/usr/local/bin/agentbox-checkpoint-cleanup'], {\n user: 'root',\n });\n if (r.exitCode !== 0) {\n log(`warning: checkpoint cleanup exited ${String(r.exitCode)}: ${r.stderr.slice(0, 200)}`);\n }\n}\n\n/**\n * Read the base image's Config block so the flatten step can replay\n * Env/Cmd/Entrypoint/WorkingDir/User/ExposedPorts on the `FROM scratch`\n * rebuild. (`docker export` discards every Config field.)\n */\nasync function inspectImageConfig(imageRef: string): Promise<DockerImageConfig> {\n const r = await execa('docker', ['image', 'inspect', imageRef], { reject: false });\n if (r.exitCode !== 0) {\n throw new CheckpointError(`docker image inspect ${imageRef} failed`, r.stdout, r.stderr);\n }\n const parsed = JSON.parse(r.stdout) as Array<{ Config: DockerImageConfig }>;\n if (!Array.isArray(parsed) || parsed.length === 0 || !parsed[0]?.Config) {\n throw new CheckpointError(\n `unexpected docker image inspect shape for ${imageRef}`,\n r.stdout,\n '',\n );\n }\n return parsed[0].Config;\n}\n\ninterface DockerImageConfig {\n Env?: string[];\n Cmd?: string[];\n Entrypoint?: string[] | null;\n WorkingDir?: string;\n User?: string;\n ExposedPorts?: Record<string, unknown>;\n}\n\n/**\n * Per-instance env keys that `docker commit` picks up from the running\n * container's Config and that must NOT be baked into a project-shared\n * checkpoint image. `runBox -e` sets these per launch; persisting them\n * would leak another box's relay token / VNC password / box-id into every\n * future box restored from this checkpoint.\n */\nconst RUNTIME_ENV_BLOCKLIST = new Set([\n 'AGENTBOX',\n 'AGENTBOX_BOX_ID',\n 'AGENTBOX_BOX_NAME',\n 'AGENTBOX_HOST_WORKSPACE',\n 'AGENTBOX_PROJECT_ROOT',\n 'AGENTBOX_PROJECT_INDEX',\n 'AGENTBOX_RELAY_URL',\n 'AGENTBOX_RELAY_TOKEN',\n // Carries this machine's `relay.port`. Baking it would point every box\n // restored from the checkpoint at the creating host's port.\n 'AGENTBOX_HOST_RELAY_URL',\n 'AGENTBOX_VNC_PASSWORD',\n 'CLAUDE_EFFORT',\n 'CLAUDE_CODE_OAUTH_TOKEN',\n 'ANTHROPIC_API_KEY',\n 'ANTHROPIC_MODEL',\n]);\n\n/**\n * Render the Dockerfile lines that replay an image's Config on top of a\n * `FROM scratch\\nADD rootfs.tar /` base. Each Env entry becomes its own ENV\n * line (the Dockerfile `ENV KEY=value` form is the only one that safely\n * handles `=` in values). Per-instance env keys (RUNTIME_ENV_BLOCKLIST) are\n * stripped — those come from `docker run -e` at the source box's launch and\n * must not leak into a project-shared checkpoint image.\n * Cmd/Entrypoint are emitted in their JSON exec form.\n */\nfunction renderConfigDirectives(cfg: DockerImageConfig): string[] {\n const lines: string[] = [];\n for (const kv of cfg.Env ?? []) {\n const eq = kv.indexOf('=');\n if (eq <= 0) continue;\n const k = kv.slice(0, eq);\n if (RUNTIME_ENV_BLOCKLIST.has(k)) continue;\n const v = kv.slice(eq + 1);\n lines.push(`ENV ${k}=${dockerfileQuote(v)}`);\n }\n if (cfg.WorkingDir) lines.push(`WORKDIR ${cfg.WorkingDir}`);\n if (cfg.User) lines.push(`USER ${cfg.User}`);\n for (const p of Object.keys(cfg.ExposedPorts ?? {}))\n lines.push(`EXPOSE ${p.replace('/tcp', '')}`);\n if (cfg.Entrypoint && cfg.Entrypoint.length > 0) {\n lines.push(`ENTRYPOINT ${JSON.stringify(cfg.Entrypoint)}`);\n }\n if (cfg.Cmd && cfg.Cmd.length > 0) {\n lines.push(`CMD ${JSON.stringify(cfg.Cmd)}`);\n }\n return lines;\n}\n\n/** Dockerfile-safe quoting for ENV values (handles spaces and quotes). */\nfunction dockerfileQuote(v: string): string {\n if (/^[A-Za-z0-9._/:+@,=-]+$/.test(v)) return v;\n return `\"${v.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/**\n * Capture a box's accumulated state as a project checkpoint.\n *\n * - `layered`: `docker exec /usr/local/bin/agentbox-checkpoint-cleanup` then\n * `docker commit <container> <tag>`. Captures everything the container has\n * written *and* the inherited image layers; the new image's parent is the\n * container's current image (i.e. the previous checkpoint or the base).\n * - `flattened`: same prelude, then `docker export | docker build` against\n * a tiny `FROM scratch` Dockerfile that ADDs the rootfs tar and replays\n * the base image's Env/Cmd/Entrypoint/WorkingDir/User/ExposedPorts. The\n * resulting image is a single layer.\n *\n * Flattened is chosen when `--merged` is passed or the source box's chain is\n * already `>= maxLayers` deep (caps image-layer growth and reset lineage).\n */\nexport async function createCheckpoint(opts: CreateCheckpointOptions): Promise<CheckpointInfo> {\n const log = opts.onLog ?? (() => {});\n const { box } = opts;\n\n const type: CheckpointType =\n opts.merged === true || chainDepth(box) >= opts.maxLayers ? 'flattened' : 'layered';\n const name = opts.name ?? (await nextCheckpointName(opts.projectRoot, box.name));\n const dir = checkpointDir(opts.projectRoot, name);\n const existing = await readManifest(dir);\n if (existing) {\n if (opts.replace) {\n log(`replacing existing checkpoint ${name} (created ${existing.createdAt})`);\n await removeCheckpoint(opts.projectRoot, name);\n } else {\n // Surface the existing checkpoint's createdAt so a caller whose previous\n // stdout was lost (e.g. the in-box agent's harness wiping output) can\n // immediately tell whether their prior attempt succeeded. Same `rm`\n // hint, plus a `--replace` shortcut for idempotent re-runs.\n throw new CheckpointError(\n `checkpoint ${name} already exists (created ${existing.createdAt}; rm it or pass --replace to recapture)`,\n '',\n '',\n );\n }\n }\n const tag = checkpointImageTag(opts.projectRoot, name);\n await mkdir(dir, { recursive: true });\n\n log(`running pre-commit cleanup in ${box.container}`);\n await runCleanup(box.container, log);\n\n if (type === 'layered') {\n log(`docker commit ${box.container} -> ${tag} (layered)`);\n const r = await execa('docker', ['commit', box.container, tag], { reject: false });\n if (r.exitCode !== 0) {\n throw new CheckpointError(`docker commit failed for ${box.container}`, r.stdout, r.stderr);\n }\n } else {\n log(`docker commit ${box.container} -> <intermediate> (flattened path)`);\n // Two-step: commit first (so we can `docker export` from the resulting\n // image without disturbing the live container), then export+build.\n const intermediate = `${tag}-intermediate`;\n const commit = await execa('docker', ['commit', box.container, intermediate], {\n reject: false,\n });\n if (commit.exitCode !== 0) {\n throw new CheckpointError(\n `docker commit (intermediate) failed`,\n commit.stdout,\n commit.stderr,\n );\n }\n try {\n await flattenImage(intermediate, tag, log);\n } finally {\n // The intermediate is layered (commits don't squash); replaced by the\n // flattened tag. -f because dangling tags would otherwise pin the\n // layered intermediate forever.\n await removeImage(intermediate, { force: true });\n }\n }\n\n const base: 'worktree' | 'workspace' = (box.gitWorktrees ?? []).some((w) => w.kind === 'root')\n ? 'worktree'\n : 'workspace';\n // Capture the base-image fingerprint so a future `create --checkpoint`\n // can detect a stale checkpoint pinned to a now-rebuilt base. Prefer the\n // recorded prepared state (cheap, no I/O on the build context), but fall\n // back to recomputing if the prepared file is missing. Both paths may\n // yield `null` (partial dev rebuild) — the manifest then omits the\n // field and restore degrades to a softer warning.\n const prepared = readPreparedDockerState();\n let baseFingerprint: string | undefined = prepared?.base?.contextSha256;\n if (!baseFingerprint) {\n const fp = await computeDockerContextFingerprint();\n baseFingerprint = fp?.contextSha256;\n }\n const stamp = readCliStamp();\n const manifest: CheckpointManifest = {\n schema: 3,\n name,\n type,\n image: tag,\n // Layered carries lineage forward; flattened is self-contained.\n parents: type === 'layered' ? (box.checkpointSource?.chain ?? []) : [],\n base,\n sourceBoxId: box.id,\n sourceBoxName: box.name,\n worktrees: box.gitWorktrees,\n baseProvider: 'docker',\n // Advisory: lets a restore into a box built for a different agent say so.\n // Absent on boxes created before per-agent selection.\n ...(box.agents && box.agents.length > 0 ? { agents: box.agents } : {}),\n baseFingerprint,\n cliVersion: stamp.cliVersion,\n createdAt: new Date().toISOString(),\n };\n await writeFile(join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\\n', 'utf8');\n\n if (opts.setDefault) {\n // Pin the docker-specific default so a `agentbox create --provider daytona`\n // in the same project doesn't trip over a docker image ref it can't load.\n await setConfigValue('project', 'box.defaultCheckpointDocker', name, opts.projectRoot);\n log(`set project default checkpoint (box.defaultCheckpointDocker) -> ${name}`);\n }\n\n return { name, dir, manifest };\n}\n\n/**\n * Flatten a layered image: export its rootfs as a tar, wrap it in a tiny\n * `FROM scratch` Dockerfile that replays the source image's Config block,\n * and build the result. Leaves the source image alone (caller removes it).\n */\nasync function flattenImage(\n sourceTag: string,\n destTag: string,\n log: (line: string) => void,\n): Promise<void> {\n // `docker export` needs a *container*, so create one without running it.\n const tmpName = `agentbox-flatten-${Date.now().toString(36)}`;\n const create = await execa('docker', ['create', '--name', tmpName, sourceTag, 'sleep', '0'], {\n reject: false,\n });\n if (create.exitCode !== 0) {\n throw new CheckpointError(`docker create for flatten failed`, create.stdout, create.stderr);\n }\n const scratch = await mkdtemp(join(tmpdir(), 'agentbox-flatten-'));\n try {\n const rootfsPath = join(scratch, 'rootfs.tar');\n log(`exporting rootfs of ${sourceTag} to ${rootfsPath}`);\n const exp = await execa('docker', ['export', '-o', rootfsPath, tmpName], { reject: false });\n if (exp.exitCode !== 0) {\n throw new CheckpointError(`docker export failed`, exp.stdout, exp.stderr);\n }\n\n // The Config block to replay is the *source* image's — that's what the\n // running container saw, and `docker commit` carries it through\n // unmodified. `docker export` drops it, which is the only reason we need\n // to inspect+replay here.\n const cfg = await inspectImageConfig(sourceTag);\n const lines = [\n 'FROM scratch',\n // ADD untars during build (Docker's documented behavior for local tars).\n 'ADD rootfs.tar /',\n ...renderConfigDirectives(cfg),\n ];\n await writeFile(join(scratch, 'Dockerfile'), lines.join('\\n') + '\\n', 'utf8');\n\n log(`building flattened ${destTag} from rootfs.tar (FROM scratch)`);\n const build = await execa(\n 'docker',\n ['build', '-t', destTag, '-f', join(scratch, 'Dockerfile'), scratch],\n { reject: false },\n );\n if (build.exitCode !== 0) {\n throw new CheckpointError(`flatten docker build failed`, build.stdout, build.stderr);\n }\n } finally {\n await execa('docker', ['rm', '-f', tmpName], { reject: false });\n await rm(scratch, { recursive: true, force: true });\n }\n}\n\nexport class CheckpointError extends Error {\n constructor(\n message: string,\n public readonly stdout: string,\n public readonly stderr: string,\n ) {\n super(`${message}${stderr ? `: ${stderr.trim()}` : ''}`);\n this.name = 'CheckpointError';\n }\n}\n\n/** Kept for the type-only import in `image.ts`'s self-update path. */\nexport const _DEFAULT_BASE_IMAGE_REF = DEFAULT_BOX_IMAGE;\n","import { stat } from 'node:fs/promises';\nimport { execInBox } from './docker.js';\n\nexport interface CtlLaunchResult {\n up: boolean;\n reason?: string;\n}\n\n/**\n * In-box path the daemon's stdout/stderr are redirected to. `docker exec -d`\n * discards stdio, so without this redirect a crash on startup leaves no trace\n * — the unix socket file lingers (Node doesn't auto-unlink on exit) and any\n * later `agentbox-ctl <op>` connect gets ECONNREFUSED with no log to explain\n * why. The file lives in the container's writable layer; it survives\n * stop/start and is wiped on destroy.\n */\nconst CTL_DAEMON_LOG = '/var/log/agentbox/ctl-daemon.log';\n\n/**\n * Spawn `agentbox-ctl daemon` detached inside the container and wait briefly\n * for the unix socket to appear on the host-mounted path. Best-effort —\n * failure is logged but doesn't fail box creation, since a missing or empty\n * agentbox.yaml is a perfectly valid state.\n */\nexport async function launchCtlDaemon(\n container: string,\n hostSocketPath: string,\n timeoutMs = 3000,\n): Promise<CtlLaunchResult> {\n // Wrap in `sh -c` so the daemon's stdio lands in a log file we can read\n // after a crash. The log dir is pre-created in the image (Dockerfile.box\n // mkdir+chown vscode); `mkdir -p` is a cheap belt-and-braces. `exec` lets\n // the shell replace itself with the daemon for a clean process tree.\n //\n // Idempotent: skip the spawn when a daemon is already running — a normal\n // `start` runs on a freshly-started container (daemon dead, so this no-ops),\n // but `reconnect` (and `start` on an already-running container) would\n // otherwise launch a duplicate. Anchor the pattern at end-of-cmdline so it\n // matches the daemon (`node …/agentbox-ctl daemon`) but not this `sh -c`\n // wrapper, whose argv ends in the log redirect, not \"daemon\".\n const logDir = CTL_DAEMON_LOG.replace(/\\/[^/]*$/, '');\n const wrapped =\n `mkdir -p ${logDir} && ` +\n `{ pgrep -f 'agentbox-ctl daemon$' >/dev/null 2>&1 && exit 0; }; ` +\n `exec agentbox-ctl daemon >>${CTL_DAEMON_LOG} 2>&1`;\n const result = await execInBox(container, ['sh', '-c', wrapped], {\n user: 'vscode',\n detach: true,\n });\n if (result.exitCode !== 0) {\n return { up: false, reason: `docker exec failed: ${result.stderr || result.stdout}` };\n }\n\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (await pathExists(hostSocketPath)) return { up: true };\n await new Promise((r) => setTimeout(r, 100));\n }\n return {\n up: false,\n reason: `socket ${hostSocketPath} did not appear within ${String(timeoutMs)}ms`,\n };\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n","import { execa } from 'execa';\n\n/**\n * Writes /etc/agentbox/box.env inside the container as a POSIX-sourceable\n * key='value' file. Paired with /etc/profile.d/agentbox.sh (baked in the\n * image), which `set -a; . /etc/agentbox/box.env; set +a`s it on login.\n *\n * Best-effort: failure is logged by the caller; an unwritable file just\n * means interactive shells lose the AGENTBOX_* vars (the env vars baked\n * into docker run still survive).\n */\nexport async function writeBoxEnvFile(\n container: string,\n env: Record<string, string>,\n): Promise<{ ok: true } | { ok: false; reason: string }> {\n const body = formatBoxEnvBody(env);\n const result = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'root',\n '-i',\n container,\n 'sh',\n '-c',\n 'umask 022 && cat > /etc/agentbox/box.env',\n ],\n { input: body, reject: false },\n );\n if (result.exitCode !== 0) {\n return {\n ok: false,\n reason: `docker exec failed (exit ${String(result.exitCode)}): ${(result.stderr ?? '').toString().slice(0, 400)}`,\n };\n }\n return { ok: true };\n}\n\n// Single-quote each value and escape embedded single quotes as '\\''. Avoids\n// double-quoted form because `. ` would expand $foo / `cmd` at source time.\nexport function formatBoxEnvBody(env: Record<string, string>): string {\n const lines: string[] = [];\n for (const [k, v] of Object.entries(env)) {\n lines.push(`${k}=${shellSingleQuote(v)}`);\n }\n return lines.join('\\n') + '\\n';\n}\n\nfunction shellSingleQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n","/**\n * Which config volume an agent gets in a new box: the shared one, or a per-box\n * one.\n *\n * The default is the AGENT's, not a flat `false`. A `caps.surface: 'service'`\n * agent always isolates: its config dir holds a gateway's identity and its\n * pairings, so two daemons sharing one would answer as the same gateway — the\n * one thing the product cannot allow. Deriving it here, where `createBox`\n * applies it, is what makes every caller inherit it: the CLI's `agentbox\n * <agent>` used to force `isolate: true` at its own call site, so the hub's\n * queue worker (and the tray, and anything built next) would each have had to\n * remember the same line.\n *\n * `config` does not even generate a `box.isolate<Agent>Config` key for a\n * service agent, exactly so there is no switch that could turn this off from a\n * config file. An explicitly-passed option is still honored — the caller keeps\n * the last word — but it is warned about, because the consequence is not\n * something a setting name conveys.\n */\nimport { isServiceAgent, type AgentSyncSpec } from '@agentbox/core';\n\nexport interface AgentIsolationOptions {\n claudeConfig?: { isolate: boolean };\n codexConfig?: { isolate: boolean };\n opencodeConfig?: { isolate: boolean };\n agentConfig?: Record<string, { isolate?: boolean }>;\n}\n\nexport function resolveAgentIsolation(\n spec: AgentSyncSpec,\n opts: AgentIsolationOptions,\n log: (line: string) => void = () => {},\n): boolean {\n // The three named options win; `agentConfig` carries every other agent's.\n // This used to `return false` for anything but the three, so a fourth or\n // plugin agent could never isolate no matter what its config key said.\n if (spec.id === 'claude' && opts.claudeConfig) return opts.claudeConfig.isolate;\n if (spec.id === 'codex' && opts.codexConfig) return opts.codexConfig.isolate;\n if (spec.id === 'opencode' && opts.opencodeConfig) return opts.opencodeConfig.isolate;\n const explicit = opts.agentConfig?.[spec.id]?.isolate;\n if (explicit === false && isServiceAgent(spec)) {\n log(\n `warning: ${spec.id} is a service agent but this box will share the ${spec.dockerVolume} config volume — its gateway identity and pairings will be the same as every other ${spec.id} box's`,\n );\n }\n return explicit ?? isServiceAgent(spec);\n}\n","import { execa } from 'execa';\n\n/**\n * Re-own any root-owned file under /home/vscode to the uid-1000 `vscode`\n * user. Root-run `docker exec` steps (checkpoint cleanup, dockerd setup) and\n * any `sudo` the in-box agent runs can leave home-dir files owned by root;\n * since the box's shell and agent both run as `vscode`, those files become\n * silently unwritable (the original symptom: a root-owned `.bash_history`\n * dropping all shell history). Boxes are throwaway dev sandboxes, so healing\n * the whole home dir in one sweep beats per-file whack-a-mole.\n *\n * `--from=root` is load-bearing: it limits the chown to files actually owned\n * by root and skips the (vast) vscode-owned majority. A plain `chown -R`\n * issues a chown syscall per file, which on the box's overlay rootfs forces\n * a copy-up of every image-layer file into the writable layer — ~10s and\n * needless disk bloat. `--from` keeps it a fast (~1s) targeted heal.\n *\n * Best-effort, idempotent: runs at every create + start. A few files are\n * legitimately unfixable (a read-only `.gitconfig` bind-mount, git pack\n * files) — chown's per-file errors are harmless and ignored.\n */\nexport async function ensureHomeOwnedByVscode(container: string): Promise<void> {\n await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'root',\n container,\n 'chown',\n '-R',\n '--from=root',\n 'vscode:vscode',\n '/home/vscode',\n ],\n { reject: false },\n );\n}\n","import { spawn } from 'node:child_process';\nimport { randomBytes } from 'node:crypto';\nimport { existsSync, openSync } from 'node:fs';\nimport { cp, mkdir, readFile, readdir, rename, rm, unlink, writeFile } from 'node:fs/promises';\nimport { request as httpRequest } from 'node:http';\nimport { createRequire } from 'node:module';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve, sep } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { fileURLToPath } from 'node:url';\nimport {\n DEFAULT_RELAY_PORT,\n RELAY_CONTAINER_NAME,\n RELAY_IMAGE_REF,\n RELAY_NETWORK_NAME,\n type BoxWorktree,\n} from '@agentbox/relay';\nimport {\n ensureHub,\n fetchHealthz,\n killPid,\n pingHealthz,\n portIsOccupied,\n processAlive,\n relayPort,\n resolveCliEntry,\n shouldReclaimForVersion,\n type HealthzBody,\n type RelayReuseHealth,\n} from '@agentbox/sandbox-core';\nimport { containerExists, removeContainer } from './docker.js';\nimport type { GitWorktreeRecord } from './state.js';\n\n// The generic process / `/healthz` probes moved to `@agentbox/sandbox-core`\n// (`hub-process.ts`) so a docker-free host can start / probe the hub without\n// importing docker machinery. Re-exported here so existing\n// `@agentbox/sandbox-docker` importers (and the version-gate test) keep working.\nexport {\n fetchHealthz,\n killPid,\n pingHealthz,\n portIsOccupied,\n processAlive,\n relayPort,\n resolveCliEntry,\n shouldReclaimForVersion,\n type HealthzBody,\n type RelayReuseHealth,\n};\n\nconst STATE_DIR = join(homedir(), '.agentbox');\nconst PID_FILE = join(STATE_DIR, 'relay.pid');\n/** The hub's pidfile — cleared when a relay takes the port from a hub. */\nconst HUB_PID_FILE = join(STATE_DIR, 'hub.pid');\nconst LOG_FILE = join(STATE_DIR, 'relay.log');\nconst RELAY_HOME_DIR = join(STATE_DIR, 'relay');\n\nexport interface RelayEndpoint {\n /** URL boxes use to reach the relay from inside the container. */\n url: string;\n /** URL host-side processes (the CLI itself) use. */\n hostUrl: string;\n port: number;\n}\n\n/**\n * The relay's URLs at the CURRENTLY resolved port (`relay.port`, seeded into\n * `relayPort()` at CLI startup). Built per call rather than frozen at import so\n * a configured port is honoured — the module constant this replaced is exactly\n * why `relay.port` did nothing.\n */\nexport function relayEndpoint(): RelayEndpoint {\n const port = relayPort();\n return {\n // host.docker.internal is the Docker Desktop / OrbStack-supplied alias for\n // the host's loopback as seen from inside a container. The corresponding\n // `--add-host=host.docker.internal:host-gateway` flag in runBox makes the\n // resolution work on Linux native Docker too.\n url: `http://host.docker.internal:${String(port)}`,\n hostUrl: `http://127.0.0.1:${String(port)}`,\n port,\n };\n}\n\nexport interface EnsureRelayOptions {\n onLog?: (line: string) => void;\n}\n\n/**\n * Idempotently bring up the host relay. Spawns the bundled `agentbox-relay`\n * bin as a detached node process bound to `0.0.0.0:<relayPort()>` (so boxes can\n * reach it via host.docker.internal, and the CLI via 127.0.0.1). Best-effort:\n * failures throw and the caller treats it as \"relay not reachable\".\n *\n * NOTE for callers that report to a user: several paths here return an endpoint\n * WITHOUT a relay process of ours running — an incumbent reused, a hub serving\n * the port, or a live pid whose /healthz stays silent. Returning is therefore\n * not proof of liveness; `agentbox relay start` re-checks with\n * {@link getRelayStatus} before it claims success.\n *\n * If a legacy relay container from a previous version of agentbox is still\n * around, it's removed first so its bound DNS name doesn't shadow the new\n * host process for any old boxes that happen to still be running.\n */\nexport async function ensureRelay(opts: EnsureRelayOptions = {}): Promise<RelayEndpoint> {\n const log = opts.onLog ?? (() => {});\n await mkdir(STATE_DIR, { recursive: true });\n\n // Migration: kill the old in-docker relay if it's around. The host process\n // wants the same port; the container did NOT publish to the host, so there\n // is no actual port collision. We still remove it to avoid confusion (it'd\n // show up in `docker ps -a` forever otherwise).\n if (await containerExists(RELAY_CONTAINER_NAME)) {\n await removeContainer(RELAY_CONTAINER_NAME);\n log(`removed legacy relay container ${RELAY_CONTAINER_NAME}`);\n }\n\n const currentVersion = process.env.AGENTBOX_CLI_VERSION;\n const health = await fetchHealthz(500);\n if (health !== null) {\n // A relay is answering on the port. Reuse it unless it's either incapable\n // (no AGENTBOX_CLI_ENTRY → 64s every cp/download/checkpoint for its whole\n // lifetime, undetectable by bare liveness) or version-mismatched (spawned\n // by a different agentbox install — e.g. a stale npx cache entry — so its\n // code may not match this CLI). See shouldReclaimForVersion for the gates.\n if (!shouldReclaimForVersion(health, currentVersion)) {\n return relayEndpoint();\n }\n // The incumbent is a HUB, not a lean relay (the hub embeds this same relay\n // daemon and adds the UI). Replacing it with a bare relay would drop the UI\n // and start a takeover war: `ensureHub` evicts a lean relay on sight, so the\n // next hub-touching command puts the hub back and kills this relay, forever.\n // Every eviction SIGTERMs the queue loop mid-job, which is how a queued `-i`\n // job never reaches `running`. Hand off instead — `ensureHub` restarts the\n // hub at the right version. (No recursion: ensureHub never calls back here.)\n if (health.ui === true) {\n log(\n `a hub from agentbox ${health.version ?? '?'} holds :${String(relayPort())} but this CLI is ` +\n `${currentVersion ?? '?'} — restarting the hub rather than replacing it with a relay`,\n );\n await ensureHub({ onLog: log });\n return relayEndpoint();\n }\n if (health.cliEntry === false) {\n log(\n 'relay is alive but lacks AGENTBOX_CLI_ENTRY (cp/download/checkpoint would fail) — reclaiming',\n );\n } else {\n log(\n `relay was spawned by agentbox ${health.version ?? '?'} but this CLI is ` +\n `${currentVersion ?? '?'} — reclaiming to keep the relay version-consistent`,\n );\n }\n await reclaimRelay(health.pid, log);\n // fall through to a fresh spawn below\n } else {\n const existingPid = await readPidFile();\n if (existingPid !== null && (await processAlive(existingPid))) {\n // Pid exists but healthz isn't responding yet — give it a beat to finish\n // startup. If it stays unresponsive, leave it alone (someone might be\n // debugging it) and let downstream POSTs fail as best-effort.\n for (let i = 0; i < 10; i++) {\n if (await pingHealthz(300)) return relayEndpoint();\n await delay(200);\n }\n log(`relay pid ${String(existingPid)} alive but /healthz unresponsive — proceeding anyway`);\n return relayEndpoint();\n }\n if (existingPid !== null) {\n await unlink(PID_FILE).catch(() => {});\n }\n }\n\n // Prefer a stable ~/.agentbox/relay/<version>/ home so the long-lived relay's\n // code (and the CLI entry it shells back into) survive npx cache GC. Falls\n // back to the bundle-relative resolvers in dev / on any staging failure.\n const staged = await stageRelayHome(currentVersion ?? '', log).catch(() => null);\n const relayBin = staged?.relayBin ?? resolveRelayBin();\n // The relay shells back into this CLI entry for the cp / download /\n // checkpoint host actions (it only knows the box id; the CLI resolves the\n // rest). Resolve it BEFORE spawning and fail loud if missing: a relay\n // without it answers /healthz fine but 64s every such action, and the\n // capability gate above would just keep reclaiming + respawning it. A null\n // here almost always means the CLI dist is mid-rebuild — surface that\n // instead of producing a half-working relay.\n const cliEntry = staged?.cliEntry ?? resolveCliEntry();\n if (cliEntry === null) {\n throw new Error(\n 'cannot start the host relay: agentbox CLI entry not found ' +\n '(is the build complete / dist present?). Set AGENTBOX_CLI_ENTRY to override.',\n );\n }\n return spawnRelay(relayBin, cliEntry, log);\n}\n\n/**\n * Stop a relay we don't want to reuse (missing AGENTBOX_CLI_ENTRY, or spawned by\n * a different agentbox version) so a fresh one can take the port. Tries the pid\n * the relay reported via /healthz first, then the pidfile pid. Fails loud if the\n * port is still held afterward — a silent \"couldn't reclaim\" would just resurrect\n * the original broken-relay bug.\n */\nasync function reclaimRelay(\n reportedPid: number | undefined,\n log: (line: string) => void,\n): Promise<void> {\n const pidFromFile = await readPidFile();\n const seen = new Set<number>();\n for (const pid of [reportedPid, pidFromFile]) {\n if (typeof pid !== 'number' || pid <= 0 || seen.has(pid)) continue;\n seen.add(pid);\n if (!(await processAlive(pid))) continue;\n log(`stopping crippled relay pid ${String(pid)}`);\n await killPid(pid);\n }\n await unlink(PID_FILE).catch(() => {});\n // Whoever takes the port owns it. Leaving the loser's pidfile behind makes the\n // other side's `status` report a dead pid as running — which is exactly how\n // this bug got diagnosed against the wrong log.\n await unlink(HUB_PID_FILE).catch(() => {});\n // Confirm the port actually freed; if a relay still answers we'd reuse the\n // broken one again on the next call. Surface it rather than loop silently.\n if (await pingHealthz(300)) {\n throw new Error(\n `a relay is still listening on :${String(relayPort())} and could not be ` +\n `stopped (reported pid ${String(reportedPid ?? 'unknown')}); kill it manually and retry`,\n );\n }\n}\n\n/**\n * Spawn the detached relay process wired with AGENTBOX_CLI_ENTRY (cp / download\n * / checkpoint shell back into it) and AGENTBOX_CLOUD_BACKENDS (the CLI bundle's\n * built-in cloud backends, which the relay's own bundle can't carry), then wait\n * for it to come up.\n *\n * The `existsSync` gate keeps a layout without that second entry — a stale\n * relay home, or an `AGENTBOX_CLI_ENTRY` override pointing somewhere else —\n * degrading to the relay's legacy resolution instead of a hard failure.\n */\nasync function spawnRelay(\n relayBin: string,\n cliEntry: string,\n log: (line: string) => void,\n): Promise<RelayEndpoint> {\n const logFd = openSync(LOG_FILE, 'a');\n const cloudBackends =\n process.env.AGENTBOX_CLOUD_BACKENDS ?? join(dirname(cliEntry), 'cloud-backends.js');\n const child = spawn(\n process.execPath,\n [relayBin, 'serve', '--port', String(relayPort()), '--host', '0.0.0.0'],\n {\n detached: true,\n stdio: ['ignore', logFd, logFd],\n env: {\n ...process.env,\n AGENTBOX_CLI_ENTRY: cliEntry,\n ...(existsSync(cloudBackends) ? { AGENTBOX_CLOUD_BACKENDS: cloudBackends } : {}),\n },\n },\n );\n child.unref();\n // Note when the child dies before it ever answers /healthz — almost always a\n // bind failure (EADDRINUSE) whose message the child has already written to\n // LOG_FILE. Surfacing that beats making the user wait out the full timeout and\n // then go read the log by hand. Mirrors spawnHub.\n let exit: { code: number | null; signal: NodeJS.Signals | null } | null = null;\n child.on('exit', (code, signal) => {\n exit = { code, signal };\n });\n if (typeof child.pid === 'number') {\n await writeFile(PID_FILE, String(child.pid), 'utf8');\n log(`spawned relay host process (pid ${String(child.pid)}, port ${String(relayPort())})`);\n }\n\n const ep = relayEndpoint();\n for (let i = 0; i < 25; i++) {\n // fetchHealthz, NOT pingHealthz: it validates the response BODY, so an\n // unrelated service that happens to 2xx on /healthz can't be mistaken for\n // our relay. A bare 2xx check is exactly how a foreign process holding the\n // port read as a healthy relay while our own child was dead.\n if ((await fetchHealthz(300)) !== null) {\n log(`relay reachable on ${ep.hostUrl}`);\n return ep;\n }\n if (exit !== null) {\n await unlink(PID_FILE).catch(() => {});\n // Let the child flush its last stderr line into the log before we tail it.\n await delay(150);\n throw new Error(\n await relayStartupError(`relay process exited (${describeExit(exit)}) during startup`),\n );\n }\n await delay(200);\n }\n await unlink(PID_FILE).catch(() => {});\n throw new Error(\n await relayStartupError(`relay did not become reachable on ${ep.hostUrl} within 5s`),\n );\n}\n\nfunction describeExit(exit: { code: number | null; signal: NodeJS.Signals | null }): string {\n if (exit.signal !== null) return `killed by ${exit.signal}`;\n return `exit code ${String(exit.code ?? 'unknown')}`;\n}\n\n/**\n * Build a startup-failure message with the tail of the relay log inlined, and —\n * when the port is held by something that is NOT an agentbox relay — name that\n * collision and the way out of it. That case (an unrelated local service on the\n * port) is the one that reads as a flaky relay rather than a port conflict,\n * because the box's RPCs then reach the other service and get its errors back.\n */\nasync function relayStartupError(headline: string): Promise<string> {\n const parts = [headline];\n if (await portIsOccupied(300)) {\n parts.push(\n `\\nport ${String(relayPort())} is held by a process that is not an agentbox relay. ` +\n `Free it, or move the relay with \\`agentbox config set relay.port <port> --global\\` ` +\n `(then \\`agentbox relay restart\\`).`,\n );\n }\n const tail = await tailFile(LOG_FILE, 20);\n parts.push(tail ? `\\n--- last lines of ${LOG_FILE} ---\\n${tail}` : `\\nsee ${LOG_FILE}`);\n return parts.join('');\n}\n\n/** Last `maxLines` non-empty lines of a file, or '' when unreadable/empty. */\nasync function tailFile(file: string, maxLines: number): Promise<string> {\n try {\n const lines = (await readFile(file, 'utf8')).split('\\n').filter((l) => l.trim().length > 0);\n return lines.slice(-maxLines).join('\\n');\n } catch {\n return '';\n }\n}\n\n/**\n * Locate the `agentbox-relay` bin spawned as a child process. Layouts:\n * 0. env override: `AGENTBOX_RELAY_BIN`\n * 1. bundled CLI (dev + published `agent-box`): this module is bundled into\n * the CLI at `<root>/dist/index.js`, the stage step puts the bin at\n * `<root>/runtime/relay/bin.cjs` (sibling of dist/ in both layouts)\n * 2. legacy workspace: `<repo>/packages/sandbox-docker/dist` ↔ `<repo>/packages/relay/dist/bin.cjs`\n * 3. legacy externalized install: `<...>/node_modules/@agentbox/relay/dist/bin.cjs`\n */\nexport function resolveRelayBin(): string {\n const override = process.env.AGENTBOX_RELAY_BIN;\n if (override && existsSync(override)) return override;\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n resolve(here, '..', 'runtime', 'relay', 'bin.cjs'),\n resolve(here, '..', '..', 'relay', 'dist', 'bin.cjs'),\n resolve(here, '..', '..', '..', '@agentbox', 'relay', 'dist', 'bin.cjs'),\n resolve(here, '..', '..', 'node_modules', '@agentbox', 'relay', 'dist', 'bin.cjs'),\n ];\n for (const c of candidates) {\n if (existsSync(c)) return c;\n }\n throw new Error(`could not locate @agentbox/relay bin; tried:\\n ${candidates.join('\\n ')}`);\n}\n\ninterface StagedRelay {\n relayBin: string;\n cliEntry: string;\n}\n\n/**\n * Stage the relay's code into a stable `~/.agentbox/relay/<version>/` home so\n * the long-lived relay process AND the `AGENTBOX_CLI_ENTRY` it shells back into\n * for cp/download/checkpoint/git-push don't depend on the volatile npx cache\n * path (`~/.npm/_npx/<hash>/...`), which can be garbage-collected while the\n * relay is still alive — host actions fire even when no foreground CLI is\n * running, so a vanished entry path would break them.\n *\n * Copies the CLI package tree (`dist/` + `runtime/` + `share/`) PLUS the\n * externalized npm deps (`node_modules/`): the CLI bundle is not self-contained\n * (apps/cli/tsup.config.ts keeps commander/execa/@daytona/sdk/... external).\n * The staged tree mirrors the package layout exactly, so the bundled entry's\n * own sibling-relative resolvers and its external `require`s all resolve inside\n * the home.\n *\n * Returns null (caller falls back to the bundle-relative resolvers, unchanged)\n * when the version is dev/empty, an `AGENTBOX_RELAY_BIN`/`AGENTBOX_CLI_ENTRY`\n * override is set, the layout/dep root can't be resolved, or any copy fails.\n */\nasync function stageRelayHome(\n version: string,\n log: (line: string) => void,\n): Promise<StagedRelay | null> {\n // Dev is a moving target ('0.0.0-dev' regardless of code) — pinning it would\n // serve a stale bundle. Overrides must flow through untouched.\n if (!version || version === '0.0.0-dev') return null;\n if (process.env.AGENTBOX_RELAY_BIN || process.env.AGENTBOX_CLI_ENTRY) return null;\n\n const cliRoot = findCliRoot(dirname(fileURLToPath(import.meta.url)));\n if (cliRoot === null) return null;\n\n const homeDir = join(RELAY_HOME_DIR, version);\n const stagedEntry = join(homeDir, 'dist', 'index.js');\n const stagedBin = join(homeDir, 'runtime', 'relay', 'bin.cjs');\n // Warm path: already staged for this version → two existsSync checks, no I/O.\n if (existsSync(stagedEntry) && existsSync(stagedBin)) {\n return { relayBin: stagedBin, cliEntry: stagedEntry };\n }\n\n const nodeModules = resolveDepRoot(join(cliRoot, 'dist', 'index.js'));\n if (nodeModules === null) return null;\n\n // Stage into a per-pid tmp dir then atomic-rename, so a crash mid-copy never\n // leaves a homeDir that passes the existsSync gate above but is incomplete.\n const tmpDir = `${homeDir}.tmp-${String(process.pid)}`;\n try {\n await mkdir(RELAY_HOME_DIR, { recursive: true });\n await rm(tmpDir, { recursive: true, force: true });\n await mkdir(tmpDir, { recursive: true });\n for (const sub of ['dist', 'runtime', 'share']) {\n const src = join(cliRoot, sub);\n if (existsSync(src)) await cp(src, join(tmpDir, sub), { recursive: true });\n }\n // dereference so a symlinked dep tree (rare in published installs) lands as\n // real files in the portable home.\n await cp(nodeModules, join(tmpDir, 'node_modules'), { recursive: true, dereference: true });\n await rm(homeDir, { recursive: true, force: true });\n await rename(tmpDir, homeDir);\n } catch (err) {\n await rm(tmpDir, { recursive: true, force: true }).catch(() => {});\n // A concurrent invocation may have won the rename onto homeDir; if the home\n // is complete now, use it. Otherwise fall back to bundle-relative resolvers.\n if (existsSync(stagedEntry) && existsSync(stagedBin)) {\n return { relayBin: stagedBin, cliEntry: stagedEntry };\n }\n log(\n `relay home staging failed (${err instanceof Error ? err.message : String(err)}); using bundle paths`,\n );\n return null;\n }\n\n log(`staged relay home for ${version} at ${homeDir}`);\n await gcOldRelayHomes(version).catch(() => {});\n return { relayBin: stagedBin, cliEntry: stagedEntry };\n}\n\n/**\n * Walk up from the bundled module dir to the CLI package root (the dir holding\n * `dist/index.js` next to `runtime/`). The module is bundled into the CLI's\n * dist/, so it sits one level under the root (chunked builds keep it in dist/).\n */\nfunction findCliRoot(moduleDir: string): string | null {\n for (const root of [resolve(moduleDir, '..'), resolve(moduleDir, '..', '..')]) {\n if (\n existsSync(join(root, 'dist', 'index.js')) &&\n existsSync(join(root, 'runtime', 'relay', 'bin.cjs'))\n ) {\n return root;\n }\n }\n return null;\n}\n\n/**\n * Locate the flat `node_modules` dir the externalized CLI deps resolve from.\n * Uses commander (a guaranteed external dep) as the probe and ascends to its\n * enclosing node_modules — handles npm/npx hoisting where the deps live above\n * the package dir.\n *\n * Returns null for a non-flat (pnpm) store: there the probe resolves into a\n * `.pnpm/<pkg>/node_modules` path, and a wholesale recursive copy of that would\n * silently miss transitive deps and produce a broken staged CLI entry. Only a\n * flat npm/npx tree — the actual npx-cache scenario this staging targets — is\n * safe to copy. A pnpm workspace dev tree falls back to bundle-relative paths\n * (current behavior, no regression).\n */\nfunction resolveDepRoot(fromFile: string): string | null {\n try {\n const req = createRequire(fromFile);\n // Resolve the package MAIN, not '<pkg>/package.json' — modern packages with\n // an `exports` map (commander included) block deep package.json resolution\n // with ERR_PACKAGE_PATH_NOT_EXPORTED. The main always resolves.\n const main = req.resolve('commander');\n if (main.includes(`${sep}.pnpm${sep}`)) return null;\n const marker = `${sep}node_modules${sep}`;\n const idx = main.lastIndexOf(marker);\n if (idx === -1) return null;\n const nm = main.slice(0, idx + marker.length - 1); // \".../node_modules\"\n return existsSync(join(nm, 'commander')) ? nm : null;\n } catch {\n return null;\n }\n}\n\n/** Remove stale relay homes (other versions + leftover .tmp dirs), keeping the current version. */\nasync function gcOldRelayHomes(keepVersion: string): Promise<void> {\n let entries: string[];\n try {\n entries = await readdir(RELAY_HOME_DIR);\n } catch {\n return;\n }\n for (const name of entries) {\n if (name === keepVersion) continue;\n await rm(join(RELAY_HOME_DIR, name), { recursive: true, force: true }).catch(() => {});\n }\n}\n\nexport interface StopRelayResult {\n /** True when a live relay process was signalled (and the pidfile cleared). */\n stopped: boolean;\n /** The pid that was found in the pidfile, if any. */\n pid: number | null;\n}\n\n/**\n * Stop the host relay process and clear its pidfile. SIGTERM first, then\n * SIGKILL if it's still alive after a short grace period. Idempotent: a\n * missing/stale pidfile is not an error (returns `{ stopped: false }`).\n *\n * Used by `agentbox update` to reload the relay; the next box command brings\n * it back via {@link ensureRelay} (running the freshly-installed bin).\n */\nexport async function stopRelay(): Promise<StopRelayResult> {\n const pid = await readPidFile();\n if (pid === null) {\n return { stopped: false, pid: null };\n }\n if (!(await processAlive(pid))) {\n await unlink(PID_FILE).catch(() => {});\n return { stopped: false, pid };\n }\n try {\n process.kill(pid, 'SIGTERM');\n } catch {\n // already gone between the liveness check and the signal\n }\n for (let i = 0; i < 20; i++) {\n if (!(await processAlive(pid))) break;\n await delay(100);\n }\n if (await processAlive(pid)) {\n try {\n process.kill(pid, 'SIGKILL');\n } catch {\n // best-effort\n }\n }\n await unlink(PID_FILE).catch(() => {});\n return { stopped: true, pid };\n}\n\nexport interface RelayStatus {\n /** True when /healthz responded with a 2xx. */\n running: boolean;\n /** Pidfile contents (null when missing/unparseable). */\n pid: number | null;\n /** Signal-0 probe on `pid` (false when `pid` is null). */\n pidAlive: boolean;\n /** Configured port (same value as endpoint.port). */\n port: number;\n /** URLs boxes / host-side callers use to reach the relay. */\n endpoint: RelayEndpoint;\n /** Parsed /healthz body; null when the relay isn't responding. */\n health: {\n boxes: number;\n events: number;\n version?: string;\n commit?: string;\n /**\n * True when a HUB (relay + Next UI in one process) is what answers here.\n * Then there is no lean relay process at all, and no `relay.pid` — callers\n * that report to a user must say \"hub\", not \"relay\".\n */\n ui?: boolean;\n } | null;\n /** Absolute path to the pidfile. */\n pidFile: string;\n /** Absolute path to the process log. */\n logFile: string;\n}\n\n/**\n * Read-only snapshot of the host relay's liveness. Combines the two probes the\n * lifecycle code uses internally: pidfile + signal-0 + a short /healthz GET.\n * Three terminal states callers care about:\n * - running: true — healthz ok\n * - running: false, pidAlive: true — zombie (process up, healthz silent)\n * - running: false, pidAlive: false — truly down\n */\nexport async function getRelayStatus(): Promise<RelayStatus> {\n const fromFile = await readPidFile();\n const health = await fetchHealthz(300);\n // Fall back to the pid /healthz reports: when the HUB holds the port there is\n // no relay pidfile (whoever takes the port clears the loser's), and a bare `?`\n // reads as \"we lost it\" rather than \"the hub is serving this\".\n const pid = fromFile ?? health?.pid ?? null;\n const pidAlive = pid !== null && (await processAlive(pid));\n return {\n running: health !== null,\n pid,\n pidAlive,\n port: relayPort(),\n endpoint: relayEndpoint(),\n health:\n health === null\n ? null\n : {\n boxes: health.boxes,\n events: health.events,\n version: health.version,\n commit: health.commit,\n ui: health.ui,\n },\n pidFile: PID_FILE,\n logFile: LOG_FILE,\n };\n}\n\nasync function readPidFile(): Promise<number | null> {\n try {\n const text = await readFile(PID_FILE, 'utf8');\n const pid = Number.parseInt(text.trim(), 10);\n return Number.isFinite(pid) && pid > 0 ? pid : null;\n } catch {\n return null;\n }\n}\n\nexport function generateRelayToken(): string {\n return randomBytes(32).toString('hex');\n}\n\nexport interface RegisterBoxArgs {\n boxId: string;\n token: string;\n name: string;\n /**\n * Sandbox backend. Defaults to 'docker'. 'cloud' tells the host relay to\n * spawn a `CloudBoxPoller` for this box (which requires `previewUrl` +\n * `bridgeToken` to be set).\n */\n kind?: 'docker' | 'cloud';\n /**\n * For cloud boxes: which cloud backend to drive (e.g. 'daytona'). The\n * relay's executor lazy-imports `@agentbox/sandbox-{backend}` to do\n * host-only RPCs like git push.\n */\n backend?: string;\n /** Docker container name; lets the relay `docker pause` the box for auto-pause. */\n containerName?: string;\n /** ISO-8601 box-creation time (BoxRecord.createdAt); auto-pause tie-break. */\n createdAt?: string;\n /**\n * 1-based per-project box index. Forwarded so the relay's status-store\n * builds the same `<id>-<n>-<mnemonic>` dir segment the host's\n * `boxRunDirFor` uses. Absent for legacy boxes.\n */\n projectIndex?: number;\n /**\n * Subset of BoxRecord.gitWorktrees the relay needs to dispatch git RPCs.\n * Empty/omitted for boxes without git repos.\n */\n worktrees?: GitWorktreeRecord[];\n /** Required for `kind === 'cloud'`: preview URL of the in-sandbox relay's `/bridge/*`. */\n previewUrl?: string;\n /** Provider-proxy token for `previewUrl` (Daytona `x-daytona-preview-token`). */\n previewToken?: string;\n /** Required for `kind === 'cloud'`: bearer for the in-sandbox relay's `/bridge/*`. */\n bridgeToken?: string;\n /**\n * Mirrors `box.autoApproveHostActions`. When true the relay auto-resolves\n * this box's host-action confirms (git push, cp, gh writes, …) to `y`\n * without a prompt, recording each bypass as a relay event.\n */\n autoApproveHostActions?: boolean;\n /**\n * Mirrors `box.autoApproveSafeHostActions` (default true). When not `false`,\n * the SAFE subset of host actions auto-resolves without a prompt. Absent →\n * enabled; only an explicit `false` restores the always-prompt behavior.\n */\n autoApproveSafeHostActions?: boolean;\n /**\n * The box repo's origin remote URL. The hosted control plane resolves\n * owner/repo from this when leasing a GitHub-App push token. Absent for\n * boxes without a git origin.\n */\n originUrl?: string;\n /**\n * The agent the box was created for. The relay's `agents.list` hands a\n * `surface: 'service'` agent's units only to a box that runs it; a\n * registration without this gets every agent's (the pre-field answer).\n */\n agent?: string;\n}\n\nexport async function registerBoxWithRelay(args: RegisterBoxArgs): Promise<void> {\n const worktrees: BoxWorktree[] = (args.worktrees ?? []).map((w) => ({\n containerPath: w.containerPath,\n hostMainRepo: w.hostMainRepo,\n branch: w.branch,\n ...(w.sanctionedBranch ? { sanctionedBranch: w.sanctionedBranch } : {}),\n }));\n await adminPost('/admin/register-box', {\n boxId: args.boxId,\n token: args.token,\n name: args.name,\n kind: args.kind ?? 'docker',\n backend: args.backend,\n containerName: args.containerName,\n createdAt: args.createdAt,\n projectIndex: args.projectIndex,\n worktrees,\n previewUrl: args.previewUrl,\n previewToken: args.previewToken,\n bridgeToken: args.bridgeToken,\n autoApproveHostActions: args.autoApproveHostActions,\n autoApproveSafeHostActions: args.autoApproveSafeHostActions,\n originUrl: args.originUrl,\n agent: args.agent,\n });\n}\n\nexport async function forgetBoxFromRelay(boxId: string): Promise<void> {\n try {\n await adminPost('/admin/forget-box', { boxId });\n } catch {\n // best-effort\n }\n}\n\n/**\n * Silence a box's host poller without dropping its registration — what a\n * PAUSE wants, where `forgetBoxFromRelay` (which also drops the record and\n * status) would be far too much.\n *\n * Load-bearing on a backend whose paused sandboxes auto-resume on inbound\n * traffic (e2b): the poller long-polls the box's preview URL every ~25s, so a\n * pause that leaves it running is undone within seconds. Measured — an\n * `agentbox stop` on an e2b box read back `running` on every sample until the\n * poller was stopped, after which the pause held.\n *\n * The wake path re-registers the box, which starts a fresh poller, so this\n * needs no restart counterpart.\n */\nexport async function stopBoxPollerOnRelay(boxId: string): Promise<void> {\n try {\n await adminPost('/admin/stop-poller', { boxId });\n } catch {\n // best-effort — a relay that isn't running has no poller to stop.\n }\n}\n\n/**\n * Best-effort: register an informational notice for a box so attached\n * `agentbox claude` footers / the dashboard show it (e.g. a spinner while a\n * checkpoint freezes the box). Returns the notice id, or null when the relay\n * is unreachable / too old to know the route — the caller treats a null id\n * as \"nothing to clear later\". Never throws: a missing notice must not fail\n * the operation it was decorating.\n */\nexport async function setRelayNotice(\n boxId: string,\n kind: string,\n message: string,\n ttlMs?: number,\n): Promise<string | null> {\n try {\n const body = await adminPostForJson('/admin/notices/set', {\n boxId,\n kind,\n message,\n ...(typeof ttlMs === 'number' ? { ttlMs } : {}),\n });\n const id = (body as { id?: unknown } | null)?.id;\n return typeof id === 'string' && id.length > 0 ? id : null;\n } catch {\n return null;\n }\n}\n\n/** Best-effort: clear a notice previously set via {@link setRelayNotice}. */\nexport async function clearRelayNotice(boxId: string, id: string): Promise<void> {\n try {\n await adminPost('/admin/notices/clear', { boxId, id });\n } catch {\n // best-effort\n }\n}\n\n/**\n * Mint a one-time host-initiated token from the host relay, scoped to\n * `(boxId, method, paramsHash)`. The caller passes the returned token to\n * `agentbox-ctl` via `--host-initiated-token`, which forwards it in the RPC\n * params; the relay re-hashes the incoming params and only skips the confirm\n * prompt on a full scope+hash match. Binding to paramsHash prevents a box\n * that harvests the token from agentbox-ctl's argv from replaying it with\n * mutated args (e.g. `--force` on push, modified `--title`/`--body` on PR).\n *\n * The endpoint is loopback-only, so the box cannot mint these directly. If\n * the relay is unreachable / too old to know the route, returns null and the\n * caller falls back to the wrapper-side prompt path.\n *\n * Pass `paramsHash: null` to opt out of params binding (no current call\n * sites do this; the host CLI always binds).\n */\nexport async function mintHostInitiatedToken(\n boxId: string,\n method: string,\n paramsHash: string | null,\n ttlMs?: number,\n): Promise<string | null> {\n try {\n const body = await adminPostForJson('/admin/host-initiated/mint', {\n boxId,\n method,\n paramsHash,\n ...(typeof ttlMs === 'number' ? { ttlMs } : {}),\n });\n const token = (body as { token?: unknown } | null)?.token;\n return typeof token === 'string' && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\nasync function adminPost(path: string, body: unknown): Promise<void> {\n const json = JSON.stringify(body);\n await new Promise<void>((resolveP, rejectP) => {\n const req = httpRequest(\n {\n host: '127.0.0.1',\n port: relayPort(),\n method: 'POST',\n path,\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(json).toString(),\n },\n timeout: 3000,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (c: Buffer) => chunks.push(c));\n res.on('end', () => {\n const status = res.statusCode ?? 0;\n if (status >= 200 && status < 300) {\n resolveP();\n } else {\n const text = Buffer.concat(chunks).toString('utf8');\n rejectP(new Error(`relay ${path} → ${String(status)}: ${text}`));\n }\n });\n },\n );\n req.on('error', rejectP);\n req.on('timeout', () => {\n req.destroy();\n rejectP(new Error(`relay ${path} timeout`));\n });\n req.write(json);\n req.end();\n });\n}\n\n/** Like {@link adminPost} but resolves with the parsed JSON response body. */\nasync function adminPostForJson(path: string, body: unknown): Promise<unknown> {\n const json = JSON.stringify(body);\n return new Promise<unknown>((resolveP, rejectP) => {\n const req = httpRequest(\n {\n host: '127.0.0.1',\n port: relayPort(),\n method: 'POST',\n path,\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(json).toString(),\n },\n timeout: 3000,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (c: Buffer) => chunks.push(c));\n res.on('end', () => {\n const status = res.statusCode ?? 0;\n if (status < 200 || status >= 300) {\n rejectP(new Error(`relay ${path} → ${String(status)}`));\n return;\n }\n const text = Buffer.concat(chunks).toString('utf8');\n try {\n resolveP(text.length > 0 ? JSON.parse(text) : {});\n } catch (err) {\n rejectP(err instanceof Error ? err : new Error(String(err)));\n }\n });\n res.on('error', rejectP);\n },\n );\n req.on('error', rejectP);\n req.on('timeout', () => {\n req.destroy();\n rejectP(new Error(`relay ${path} timeout`));\n });\n req.write(json);\n req.end();\n });\n}\n\nexport interface BoxWithToken {\n id: string;\n name: string;\n /** Sandbox backend the box runs on. Defaults to 'docker' when absent. */\n provider?: 'docker' | 'cloud' | string;\n container?: string;\n createdAt?: string;\n relayToken?: string;\n projectIndex?: number;\n gitWorktrees?: GitWorktreeRecord[];\n /** Cloud-only: which backend (e.g. 'daytona') drives this box. */\n cloudBackend?: string;\n /** Cloud-only: in-sandbox /bridge URL + tokens (from BoxRecord.cloud). */\n relayPreviewUrl?: string;\n relayPreviewToken?: string;\n bridgeToken?: string;\n /** Mirrors `BoxRecord.autoApproveHostActions`; re-registered on rehydrate. */\n autoApproveHostActions?: boolean;\n /** Mirrors `BoxRecord.autoApproveSafeHostActions`; re-registered on rehydrate. */\n autoApproveSafeHostActions?: boolean;\n}\n\n/**\n * Re-push every known (id, token) to the relay's in-memory registry. Called\n * after `ensureRelay()` so a fresh / restarted relay learns about boxes that\n * were created in a previous CLI invocation — and, for cloud boxes,\n * restarts the host-side `CloudBoxPoller`.\n */\nexport async function rehydrateRelayRegistry(boxes: BoxWithToken[]): Promise<void> {\n for (const b of boxes) {\n if (!b.relayToken) continue;\n const kind = b.provider === 'docker' || b.provider === undefined ? 'docker' : 'cloud';\n try {\n await registerBoxWithRelay({\n boxId: b.id,\n token: b.relayToken,\n name: b.name,\n kind,\n backend: kind === 'cloud' ? b.cloudBackend : undefined,\n containerName: b.container,\n createdAt: b.createdAt,\n projectIndex: b.projectIndex,\n worktrees: b.gitWorktrees,\n previewUrl: b.relayPreviewUrl,\n previewToken: b.relayPreviewToken,\n bridgeToken: b.bridgeToken,\n autoApproveHostActions: b.autoApproveHostActions,\n autoApproveSafeHostActions: b.autoApproveSafeHostActions,\n });\n } catch {\n // best-effort\n }\n }\n}\n\nexport { RELAY_CONTAINER_NAME, RELAY_NETWORK_NAME, RELAY_IMAGE_REF, DEFAULT_RELAY_PORT };\n","import { ensureVolume, execInBox, type DockerExecResult } from './docker.js';\n\nexport type IdeFlavor = 'vscode' | 'cursor';\n\ninterface IdeProfile {\n /** Container path the IDE's server installs into. */\n serverDir: string;\n /** Container path of the extensions subdir under serverDir. */\n extensionsDir: string;\n /** Per-box volume name = perBoxVolumePrefix + boxId. */\n perBoxVolumePrefix: string;\n /** Shared extensions volume name (never auto-removed). */\n sharedExtensionsVolume: string;\n /** Host CLI binary that opens this IDE (`code` / `cursor`). */\n cli: string;\n /** Human-readable label used in CLI output. */\n displayName: string;\n /** macOS protocol scheme for the `open` fallback (no trailing colon). */\n protocolScheme: string;\n}\n\nconst PROFILES: Record<IdeFlavor, IdeProfile> = {\n vscode: {\n serverDir: '/home/vscode/.vscode-server',\n extensionsDir: '/home/vscode/.vscode-server/extensions',\n perBoxVolumePrefix: 'agentbox-vscode-server-',\n sharedExtensionsVolume: 'agentbox-vscode-extensions',\n cli: 'code',\n displayName: 'VS Code',\n protocolScheme: 'vscode',\n },\n cursor: {\n serverDir: '/home/vscode/.cursor-server',\n extensionsDir: '/home/vscode/.cursor-server/extensions',\n perBoxVolumePrefix: 'agentbox-cursor-server-',\n sharedExtensionsVolume: 'agentbox-cursor-extensions',\n cli: 'cursor',\n displayName: 'Cursor',\n protocolScheme: 'cursor',\n },\n};\n\nexport const IDE_FLAVORS: readonly IdeFlavor[] = ['vscode', 'cursor'];\n\nexport function ideProfile(flavor: IdeFlavor): IdeProfile {\n return PROFILES[flavor];\n}\n\n/**\n * Shared across all boxes. Holds downloaded VS Code extensions so the second\n * box onward doesn't re-download them. Never auto-removed by destroy/prune\n * (parallel to SHARED_CLAUDE_VOLUME).\n */\nexport const SHARED_VSCODE_EXTENSIONS_VOLUME = PROFILES.vscode.sharedExtensionsVolume;\n\n/** Same idea for Cursor's downloaded extensions. */\nexport const SHARED_CURSOR_EXTENSIONS_VOLUME = PROFILES.cursor.sharedExtensionsVolume;\n\n/** Per-box VS Code server volume name. Holds server binary + TS cache + workspace state. */\nexport function vscodeServerVolumeName(boxId: string): string {\n return ideServerVolumeName('vscode', boxId);\n}\n\n/** Per-box Cursor server volume name. */\nexport function cursorServerVolumeName(boxId: string): string {\n return ideServerVolumeName('cursor', boxId);\n}\n\nexport function ideServerVolumeName(flavor: IdeFlavor, boxId: string): string {\n return `${PROFILES[flavor].perBoxVolumePrefix}${boxId}`;\n}\n\nexport interface IdeMounts {\n /** Volume names to ensure() before runBox. */\n volumes: string[];\n /** `-v` arg values to pass to runBox. */\n extraVolumes: string[];\n}\n\n/**\n * Build the volume mounts for one IDE flavor: per-box `.vscode-server` (or\n * `.cursor-server`) mounts first, then the shared extensions volume layered\n * over its `extensions` subdir.\n */\nexport function buildFlavorMounts(flavor: IdeFlavor, boxId: string): IdeMounts {\n const profile = PROFILES[flavor];\n const perBox = ideServerVolumeName(flavor, boxId);\n return {\n volumes: [perBox, profile.sharedExtensionsVolume],\n extraVolumes: [\n `${perBox}:${profile.serverDir}`,\n `${profile.sharedExtensionsVolume}:${profile.extensionsDir}`,\n ],\n };\n}\n\n/** VS Code subset — kept for callers that only want the VS Code mounts. */\nexport function buildVscodeMounts(boxId: string): IdeMounts {\n return buildFlavorMounts('vscode', boxId);\n}\n\n/**\n * All IDE flavors' mounts unioned together. This is what createBox uses so\n * any existing box can be opened with either IDE without recreating.\n */\nexport function buildIdeMounts(boxId: string): IdeMounts {\n const merged: IdeMounts = { volumes: [], extraVolumes: [] };\n for (const f of IDE_FLAVORS) {\n const m = buildFlavorMounts(f, boxId);\n merged.volumes.push(...m.volumes);\n merged.extraVolumes.push(...m.extraVolumes);\n }\n return merged;\n}\n\n/** Ensure VS Code's volumes exist. */\nexport async function ensureVscodeVolumes(boxId: string): Promise<void> {\n for (const v of buildFlavorMounts('vscode', boxId).volumes) await ensureVolume(v);\n}\n\n/** Ensure every IDE flavor's volumes exist. */\nexport async function ensureIdeVolumes(boxId: string): Promise<void> {\n for (const v of buildIdeMounts(boxId).volumes) await ensureVolume(v);\n}\n\n/**\n * Belt-and-suspenders chown of the server trees after the named volumes are\n * mounted. The Dockerfile pre-creates these dirs so first-mount inherits\n * vscode:vscode ownership, but a shared extensions volume might already exist\n * from a box created against an older image where the dirs weren't seeded —\n * in that case the volume is root-owned and the Dev Containers extension\n * fails with \"mkdir: cannot create directory '<server>/bin': Permission\n * denied\". One docker exec fixes it idempotently for both flavors.\n */\nexport async function repairVscodeServerOwnership(container: string): Promise<void> {\n await execInBox(container, ['chown', '-R', 'vscode:vscode', PROFILES.vscode.serverDir], {\n user: 'root',\n });\n}\n\nexport async function repairIdeOwnership(container: string): Promise<void> {\n for (const flavor of IDE_FLAVORS) {\n await execInBox(container, ['chown', '-R', 'vscode:vscode', PROFILES[flavor].serverDir], {\n user: 'root',\n });\n }\n}\n\nexport interface AttachedContainerUriOptions {\n /** Active Docker context (e.g. \"desktop-linux\" / \"orbstack\"). Embedded in\n * the URI's `settings.context` so the Dev Containers extension queries the\n * same daemon agentbox created the container in. Omitted → the extension\n * falls back to its own default context. */\n dockerContext?: string;\n /** Folder opened inside the container (default `/workspace`). */\n workspacePath?: string;\n}\n\n/**\n * Resource URI for an attached container, consumed by `code --folder-uri` /\n * `cursor --folder-uri` (Cursor is a VS Code fork — same URI scheme).\n *\n * The modern Dev Containers extension expects the `attached-container+<hex>`\n * authority to decode to a JSON payload, not a bare name:\n *\n * attached-container+hex({\"containerName\":\"/<name>\",\"settings\":{\"context\":\"<ctx>\"}})\n *\n * `containerName` keeps the leading slash docker's own `.Name` field carries.\n * `settings.context` pins the Docker context — without it, after switching\n * engines (OrbStack ⇄ Docker Desktop) the extension probes the wrong daemon\n * and reports the container as non-existent (\"…because it no longer exists\").\n *\n * Note: the `vscode://vscode-remote/...` protocol-handler form looks similar\n * but goes through macOS `open`, which percent-encodes the `+` authority\n * separator into `%2B` and the extension then fails to resolve it. Use\n * `<cli> --folder-uri <this>` to bypass that.\n */\nexport function attachedContainerUri(\n containerName: string,\n opts: AttachedContainerUriOptions = {},\n): string {\n const workspacePath = opts.workspacePath ?? '/workspace';\n const payload: { containerName: string; settings?: { context: string } } = {\n containerName: containerName.startsWith('/') ? containerName : `/${containerName}`,\n };\n if (opts.dockerContext) payload.settings = { context: opts.dockerContext };\n const hex = Buffer.from(JSON.stringify(payload), 'utf8').toString('hex');\n return `vscode-remote://attached-container+${hex}${workspacePath}`;\n}\n\n/**\n * agentbox-managed `.vscode/tasks.json` lives in the overlay's upper layer so\n * it doesn't pollute the host's working tree. The sentinel comment lets us\n * detect our own file and regenerate it on every `agentbox code` invocation\n * without overwriting a user-authored one. The file lives at `.vscode/` —\n * Cursor reads the same path (VS Code fork), so no per-IDE variant needed.\n */\nconst SENTINEL =\n '// agentbox-managed: regenerated on `agentbox code`; remove this header to take ownership';\n\nexport type ServiceTailHint = { name: string };\n\nexport interface EnsureTasksFileResult {\n status: 'wrote' | 'skipped-user-owned' | 'skipped-no-services';\n}\n\n/**\n * Write (or skip) `/workspace/.vscode/tasks.json` inside the container. Each\n * service in `services` gets a background task that tails its log so the IDE\n * shows a dedicated terminal panel on attach.\n *\n * - File absent → write.\n * - File present with our sentinel → overwrite.\n * - File present without sentinel → skip (user owns it). Caller can force\n * by setting `regen: true`.\n */\nexport async function ensureAgentboxTasksFile(\n container: string,\n services: ServiceTailHint[],\n opts: { regen?: boolean } = {},\n): Promise<EnsureTasksFileResult> {\n if (services.length === 0) return { status: 'skipped-no-services' };\n\n const existing = await execInBox(container, ['cat', '/workspace/.vscode/tasks.json'], {\n user: 'vscode',\n });\n if (existing.exitCode === 0 && !opts.regen && !existing.stdout.includes(SENTINEL)) {\n return { status: 'skipped-user-owned' };\n }\n\n const tasks = services.map((s) => ({\n label: `agentbox: ${s.name}`,\n type: 'shell',\n command: `tail -F /var/log/agentbox/${s.name}.log`,\n isBackground: true,\n presentation: { panel: 'dedicated', reveal: 'always', echo: false },\n runOptions: { runOn: 'folderOpen' },\n problemMatcher: [] as unknown[],\n }));\n const body =\n `${SENTINEL}\\n` +\n JSON.stringify(\n {\n version: '2.0.0',\n tasks,\n },\n null,\n 2,\n ) +\n '\\n';\n\n await execInBox(container, ['mkdir', '-p', '/workspace/.vscode'], { user: 'vscode' });\n const write = await writeFileInBox(container, '/workspace/.vscode/tasks.json', body);\n if (write.exitCode !== 0) {\n throw new Error(`failed to write tasks.json in ${container}: ${write.stderr || write.stdout}`);\n }\n return { status: 'wrote' };\n}\n\nasync function writeFileInBox(\n container: string,\n path: string,\n content: string,\n): Promise<DockerExecResult> {\n const { execa } = await import('execa');\n const result = await execa(\n 'docker',\n ['exec', '-i', '--user', 'vscode', container, 'sh', '-c', `cat > ${shellQuote(path)}`],\n { input: content, reject: false },\n );\n return {\n exitCode: result.exitCode ?? -1,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n };\n}\n\nfunction shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// Backward-compat alias for the previous mount type name.\nexport type VscodeMounts = IdeMounts;\n","import { execa } from 'execa';\nimport { readdir, rm, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { BoxState, ResyncResult } from '@agentbox/core';\nimport {\n agentConfigVolume,\n AmbiguousBoxError,\n BoxNotFoundError,\n buildNoVncUrl,\n normalizeAgentStatus,\n} from '@agentbox/core';\nimport type { AgentActivityState, AgentQuestionPayload, AgentStatusMap } from '@agentbox/core';\nimport type { BoxStatus } from '@agentbox/ctl';\nimport { SHARED_AGENTS_VOLUME } from './sync/agents/skills.js';\nimport { listShellSessions, type ShellSessionSummary } from './shell-session.js';\nimport { bindWorktrees, removeInBoxWorktree, resyncWorkspaceFromHost } from './sync/in-box-git.js';\nimport {\n cursorServerVolumeName,\n SHARED_CURSOR_EXTENSIONS_VOLUME,\n SHARED_VSCODE_EXTENSIONS_VOLUME,\n vscodeServerVolumeName,\n} from './vscode.js';\nimport {\n BOXES_ROOT,\n boxRunDirFor,\n detectEngine,\n getHostPaths,\n openInFinder,\n readBoxStatus,\n type HostPaths,\n type OpenOptions,\n type OpenResult,\n} from './sync/host-export.js';\nimport {\n inspectContainer,\n inspectContainerStatus,\n listAgentboxContainers,\n listAgentboxVolumes,\n pauseContainer,\n publishedHostPort,\n removeContainer,\n removeImage,\n removeNetwork,\n removeVolume,\n startContainer,\n stopContainer,\n unpauseContainer,\n} from './docker.js';\nimport { CHECKPOINT_IMAGE_PREFIX, listAllCheckpointImages } from './checkpoint.js';\nimport { launchCtlDaemon } from './ctl.js';\nimport { ensureHomeOwnedByVscode } from './home-ownership.js';\nimport { launchDockerdDaemon, SHARED_DOCKER_CACHE_VOLUME } from './dockerd.js';\nimport { launchVncDaemon, VNC_CONTAINER_PORT } from './vnc.js';\nimport { setUpBoxSshd } from './ssh.js';\nimport { WEB_CONTAINER_PORT } from './web.js';\nimport { AGENT_SYNC_SPECS, syncAgentboxSshConfig } from '@agentbox/sandbox-core';\nimport { agentSyncModule, type AgentSessionInfo } from './sync/agents/module.js';\nimport { detectPortless, portlessAlias, portlessGetUrl, portlessUnalias } from './portless.js';\nimport { getBoxEndpoints, type BoxEndpoint, type BoxEndpoints } from './endpoints.js';\nimport {\n ensureRelay,\n forgetBoxFromRelay,\n registerBoxWithRelay,\n RELAY_CONTAINER_NAME,\n RELAY_IMAGE_REF,\n RELAY_NETWORK_NAME,\n} from './relay.js';\nimport { SNAPSHOTS_ROOT } from './snapshot.js';\nimport {\n findBox,\n readState,\n recordBox,\n removeBoxRecord,\n type BoxRecord,\n type FindBoxResult,\n} from './state.js';\n\nexport interface ListedBox extends BoxRecord {\n state: BoxState;\n endpoints: BoxEndpoints;\n /**\n * Every reporting agent's live status, keyed by id; `{}` for pre-feature /\n * never-pushed boxes. THE source — the named fields below are derived from it\n * and exist only for clients that predate the map.\n *\n * Named `agentStatus`, not `agents`: `BoxRecord.agents` is already the list of\n * agents INSTALLED in the box, which is a different question.\n */\n agentStatus: AgentStatusMap;\n /** From the persisted status file; undefined for pre-feature/never-pushed boxes. */\n claudeActivity?: AgentActivityState;\n /** Sanitized in-box terminal title Claude set; undefined when none. */\n claudeSessionTitle?: string;\n /** Last captured `AskUserQuestion` payload — present only when\n * `claudeActivity === 'question'`. Surfaced to the dashboard so it can paint\n * the agent's question into the alert band above the footer. */\n claudeQuestion?: AgentQuestionPayload;\n /** Codex activity from the persisted status file; undefined when none. */\n codexActivity?: AgentActivityState;\n /**\n * OpenCode activity. Its plugin has always reported one and it was dropped\n * at this hop, so every OpenCode box read as \"no activity\" no matter what it\n * was doing — `list` could only ever print a bare `opencode`.\n */\n opencodeActivity?: AgentActivityState;\n /** Sanitized in-box terminal title the Codex/OpenCode TUI set; undefined when none. */\n codexSessionTitle?: string;\n opencodeSessionTitle?: string;\n /** Live shell tmux sessions; `[]` for non-running boxes (can't `docker exec`). */\n shellSessions: ShellSessionSummary[];\n /** Live probe of the Codex tmux session; null when the box isn't running. */\n codexSession: AgentSessionInfo | null;\n /** Live probe of the OpenCode tmux session; null when the box isn't running. */\n opencodeSession: AgentSessionInfo | null;\n}\n\n/**\n * Flatten a persisted status snapshot into the per-agent fields a `ListedBox`\n * carries.\n *\n * `agents` is the real payload; the named fields beside it are a derived\n * projection kept for clients that predate the map (the hub's `/api/v1` Box and\n * the macOS tray, which decodes the three `*SessionTitle` keys by name). They\n * cover only the built-in three — a fourth agent is reachable through `agents`,\n * which is the point.\n *\n * Reads through `normalizeAgentStatus`, so a snapshot written by an older box —\n * baked ctl posts the old shape for as long as that box lives — folds into the\n * same map as a current one.\n */\nfunction agentStatusFields(\n persisted: BoxStatus | null,\n): Pick<\n ListedBox,\n | 'agentStatus'\n | 'claudeActivity'\n | 'claudeSessionTitle'\n | 'claudeQuestion'\n | 'codexActivity'\n | 'codexSessionTitle'\n | 'opencodeActivity'\n | 'opencodeSessionTitle'\n> {\n const agents = normalizeAgentStatus(persisted);\n const claude = agents.claude;\n return {\n agentStatus: agents,\n claudeActivity: claude?.state,\n claudeSessionTitle: claude?.sessionTitle,\n claudeQuestion: claude?.state === 'question' ? claude.question : undefined,\n codexActivity: agents.codex?.state,\n codexSessionTitle: agents.codex?.sessionTitle,\n opencodeActivity: agents.opencode?.state,\n opencodeSessionTitle: agents.opencode?.sessionTitle,\n };\n}\n\n/**\n * A box's PER-BOX agent config volumes — the ones `box.isolate<Agent>Config`\n * created, which belong to this box alone.\n *\n * A volume equal to the agent's shared `dockerVolume` is deliberately excluded:\n * that one carries the user's identity (auth, skills, plugins) across every box\n * and is never auto-removed.\n *\n * `BoxRecord` still names its three fields one at a time, so the mapping is\n * spelled out here rather than derived; that field set is generalized in a later\n * phase. What matters now is that the SHARED name comes from the registry\n * instead of a second copy in this package.\n */\n/**\n * Probe one agent's tmux session through the registry.\n *\n * `null` for an agent with no registered module rather than a throw: a box may\n * reference an agent this build has no docker behavior for, and a listing must\n * degrade to \"no session\" instead of failing.\n */\nasync function agentSession(id: string, container: string): Promise<AgentSessionInfo | null> {\n const mod = agentSyncModule(id);\n if (!mod) return null;\n return mod.sessionInfo(container);\n}\n\n/**\n * The box's ISOLATED per-agent volumes — the ones `destroy` must remove.\n *\n * Filters out each agent's shared `dockerVolume`, which outlives the box. The\n * lookup is `agentConfigVolume` rather than a three-row table, so an agent\n * outside the built-in three has its per-box volume cleaned up instead of\n * leaking (and, before the volume map, being invisible here entirely).\n */\nfunction boxAgentConfigVolumes(box: BoxRecord): { agent: string; volume?: string }[] {\n return AGENT_SYNC_SPECS.map((spec) => ({\n agent: spec.id,\n volume: agentConfigVolume(box, spec.id),\n })).filter((e) => e.volume !== undefined && e.volume !== agentSpecById(e.agent)?.dockerVolume);\n}\n\nfunction agentSpecById(id: string): { dockerVolume: string } | undefined {\n return AGENT_SYNC_SPECS.find((s) => s.id === id);\n}\n\nexport async function listBoxes(): Promise<ListedBox[]> {\n const { boxes } = await readState();\n const engine = await detectEngine();\n return Promise.all(\n boxes.map(async (b): Promise<ListedBox> => {\n // Cloud boxes don't have a host Docker container — skip every Docker\n // probe (inspect / exec / shell-session). State is the last host-driven\n // lifecycle state persisted on `cloud.lastState` (create/start/resume ->\n // running, pause/stop/checkpoint -> paused), so `list` stays instant with\n // no SDK round-trip; `agentbox list --live` probes for the authoritative\n // state. Pre-feature records (no lastState) fall back to 'running'.\n // Endpoints come from the cloud.previewUrls map populated at create/start;\n // agent activity rides the persisted status snapshot the host poller\n // mirrors from the in-sandbox relay.\n if (b.provider && b.provider !== 'docker') {\n const persisted = await readBoxStatus(b);\n const webPort = b.cloud?.webPort ?? 0;\n // Prefer the stable Portless URL when one was registered (Hetzner\n // gets it by default; Daytona naturally skips because its URL isn't\n // loopback). Falls back to the ephemeral `127.0.0.1:<random>`\n // preview URL when Portless isn't in play.\n const portlessWebUrl =\n b.portlessAlias !== undefined\n ? (b.portlessUrl ?? `https://${b.portlessAlias}.localhost`)\n : undefined;\n const cachedWebUrl = webPort > 0 ? b.cloud?.previewUrls?.[webPort] : undefined;\n const webUrl = portlessWebUrl ?? cachedWebUrl;\n const portlessVncBase =\n b.portlessVncAlias !== undefined\n ? (b.portlessVncUrl ?? `https://${b.portlessVncAlias}.localhost`)\n : undefined;\n // Only Portless yields a URL stable enough to persist in a listing. A\n // cloud provider's own preview URL is either header-authed or a signed\n // URL that expires within the hour, so daytona/vercel/e2b report the\n // endpoint as enabled-but-unreachable here and clients mint one on\n // demand via the hub's `/boxes/:id/vnc`.\n const vncUrl =\n portlessVncBase && b.vncPassword\n ? buildNoVncUrl(portlessVncBase, b.vncPassword)\n : undefined;\n const cloudEndpoints: BoxEndpoint[] = [];\n if (webUrl) {\n cloudEndpoints.push({\n kind: 'web',\n name: 'web',\n containerPort: webPort,\n url: webUrl,\n reachable: true,\n });\n }\n if (b.vncEnabled && b.vncPassword) {\n cloudEndpoints.push({\n kind: 'vnc',\n name: 'vnc',\n containerPort: b.vncContainerPort ?? 6080,\n ...(vncUrl ? { url: vncUrl, reachable: true } : { reachable: false }),\n });\n }\n const endpoints: BoxEndpoints = {\n domain: webUrl ? safeHost(webUrl) : '',\n domainIsOrb: false,\n endpoints: cloudEndpoints,\n };\n return {\n ...b,\n state: b.cloud?.lastState ?? 'running',\n endpoints,\n ...agentStatusFields(persisted),\n shellSessions: [],\n codexSession: null,\n opencodeSession: null,\n };\n }\n const state = await inspectContainerStatus(b.container);\n const persisted = await readBoxStatus(b);\n const endpoints = await getBoxEndpoints(b, engine, persisted);\n // Shell sessions + the codex session probe are live tmux state — only a\n // running container is reachable via `docker exec`; paused/stopped report\n // none. (Claude activity rides the persisted status snapshot instead, so\n // it needs no live probe.)\n const shellSessions = state === 'running' ? await listShellSessions(b.container) : [];\n const codexSession = state === 'running' ? await agentSession('codex', b.container) : null;\n const opencodeSession =\n state === 'running' ? await agentSession('opencode', b.container) : null;\n return {\n ...b,\n state,\n endpoints,\n ...agentStatusFields(persisted),\n shellSessions,\n codexSession,\n opencodeSession,\n };\n }),\n );\n}\n\n/** Extract host from a URL string; empty when unparseable. */\nfunction safeHost(url: string): string {\n try {\n return new URL(url).host;\n } catch {\n return '';\n }\n}\n\n// The box-resolution error classes are provider-neutral; they live in\n// @agentbox/core. Imported for local `throw`s below and re-exported so existing\n// `@agentbox/sandbox-docker` consumers keep importing them from here.\nexport { AmbiguousBoxError, BoxNotFoundError };\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function resolveBox(idOrName: string): Promise<BoxRecord> {\n const state = await readState();\n const result: FindBoxResult = findBox(idOrName, state);\n switch (result.kind) {\n case 'ok':\n return result.box;\n case 'none':\n throw new BoxNotFoundError(idOrName);\n case 'ambiguous':\n throw new AmbiguousBoxError(idOrName, result.matches);\n }\n}\n\nexport async function pauseBox(idOrName: string): Promise<BoxRecord> {\n const box = await resolveBox(idOrName);\n await pauseContainer(box.container);\n return box;\n}\n\nexport async function unpauseBox(idOrName: string): Promise<BoxRecord> {\n const box = await resolveBox(idOrName);\n await unpauseContainer(box.container);\n return box;\n}\n\nexport async function stopBox(idOrName: string): Promise<BoxRecord> {\n const box = await resolveBox(idOrName);\n await stopContainer(box.container);\n return box;\n}\n\nexport interface StartedBox {\n record: BoxRecord;\n}\n\n/**\n * Resync a box's worktrees with the host: merge the host's current branch into\n * each per-box branch and overlay the host's uncommitted/untracked changes,\n * keeping the box's version on conflict. Returns the conflicts so the CLI can\n * warn the agent. No-op (empty result) for boxes with no git worktrees. The\n * caller is responsible for gating (config + \"no live agent session\"); this\n * mutates the worktree and must not run under a running agent.\n */\nexport async function resyncBox(\n idOrName: string,\n onLog?: (line: string) => void,\n): Promise<ResyncResult> {\n const box = await resolveBox(idOrName);\n const worktrees = box.gitWorktrees ?? [];\n if (worktrees.length === 0) return { repos: [], hadConflicts: false };\n const repos = await resyncWorkspaceFromHost({ container: box.container, worktrees, onLog });\n const hadConflicts = repos.some(\n (r) => r.mergeConflicts.length > 0 || r.overlaySkipped.length > 0,\n );\n return { repos, hadConflicts };\n}\n\n/**\n * Re-start a stopped box.\n *\n * /workspace is just the container's writable filesystem now, so there's no\n * overlay to remount — `docker start` brings everything back. The in-box\n * supervisor, dockerd, and Xvnc all die with the container, so we relaunch\n * them via the same exec-d helpers `create` used. Ephemeral host ports for\n * VNC + web get re-allocated by Docker on `start`, so we re-resolve and\n * persist those too.\n */\n/**\n * Ensure the box's localhost sshd is up and its recorded loopback port is\n * current, then re-sync `~/.agentbox/ssh/config`. Called on `start` (the daemon\n * died with the container) AND before any `agentbox open`/`--in codex` on a box\n * that is *already running* — Docker reallocates the ephemeral `-p 0:22` host\n * port whenever the container restarts, and a `docker restart` (or daemon\n * restart) outside `agentbox start` leaves the recorded `Port` stale. Idempotent:\n * `mintSshKey` reuses the on-disk key, install + launch are no-ops when up, and\n * we only re-persist + re-sync when the resolved port actually changed.\n * Best-effort — mutates and returns `box`.\n */\nexport async function refreshBoxSshd(box: BoxRecord): Promise<BoxRecord> {\n if (!box.sshEnabled) return box;\n const ssh = await setUpBoxSshd(\n box.container,\n join(boxRunDirFor(box), 'ssh'),\n `agentbox-${box.name}-${box.id}`,\n );\n // Only (re)write the alias when sshd actually bound. If it didn't come up we\n // leave the last-known target untouched rather than pointing `~/.ssh/config` at\n // a dead loopback port (matches the create-time gate) — a later retry records\n // it once sshd is healthy.\n if (!ssh.up || !ssh.sshHostPort) return box;\n const port = ssh.sshHostPort;\n const changed = port !== box.sshHostPort || box.ssh?.port !== port;\n box.sshHostPort = port;\n box.ssh = { host: '127.0.0.1', user: 'vscode', identityFile: ssh.identityFile, port };\n if (changed) {\n await recordBox(box);\n try {\n await syncAgentboxSshConfig();\n } catch {\n /* best-effort */\n }\n }\n return box;\n}\n\nexport async function startBox(idOrName: string): Promise<StartedBox> {\n const box = await resolveBox(idOrName);\n // .git bind-mounts are baked into the container at create time; if a host\n // main repo's .git/ has been deleted out from under us, restart fails with\n // an opaque mount error. Surface it loudly.\n for (const w of box.gitWorktrees ?? []) {\n if (!(await pathExists(join(w.hostMainRepo, '.git')))) {\n throw new Error(\n `main repo for box worktree missing: ${join(w.hostMainRepo, '.git')} (recreate the box)`,\n );\n }\n }\n await startContainer(box.container);\n\n // /workspace bind mounts don't survive `docker stop` (the mount namespace\n // is recreated on start). Re-bind each registered worktree before any\n // daemon comes up — the supervisor and dockerd may resolve paths under\n // /workspace and would see the image's empty dir without this.\n if ((box.gitWorktrees ?? []).length > 0) {\n await bindWorktrees(\n box.container,\n (box.gitWorktrees ?? []).map((w) => ({\n kind: w.kind,\n containerPath: w.containerPath,\n gitWorktreePath: w.gitWorktreePath,\n })),\n );\n }\n\n // Re-own /home/vscode to vscode in case root-run steps left files behind\n // (see ensureHomeOwnedByVscode). Best-effort; safe to repeat.\n await ensureHomeOwnedByVscode(box.container);\n\n if (box.dockerVolume) {\n // The daemon died with the container; relaunch it BEFORE the ctl supervisor\n // (mirrors create.ts) so a docker-based agentbox.yaml service doesn't race a\n // not-yet-ready socket on restart. launchDockerdDaemon blocks until ready.\n await launchDockerdDaemon(box.container);\n }\n if (box.socketPath) {\n // The daemon died with the container; relaunch it. Best-effort, same as\n // create.ts — a missing config or other startup issue shouldn't block\n // resumption of the box itself.\n await launchCtlDaemon(box.container, box.socketPath);\n }\n if (box.vncEnabled) {\n // Xvnc + websockify both die with the container. The password is already\n // in the container env (set at `docker run` time and preserved across\n // start/stop), so we don't need to forward it here.\n await launchVncDaemon(box.container);\n // Docker re-allocates an ephemeral host port for `-p 0:6080` on every\n // `start`. Re-resolve and persist; the orb.local URL is name-based and\n // unaffected. Best-effort — a failed resolve just leaves the record as-is.\n const freshHostPort = await publishedHostPort(box.container, VNC_CONTAINER_PORT);\n if (freshHostPort && freshHostPort !== box.vncHostPort) {\n box.vncHostPort = freshHostPort;\n await recordBox(box);\n }\n }\n // Same ephemeral-reallocation story for the reserved web port. Gated on\n // webContainerPort so pre-feature boxes (no `-p 0:80` mapping) are skipped.\n if (box.webContainerPort !== undefined) {\n const freshWebPort = await publishedHostPort(\n box.container,\n box.webContainerPort ?? WEB_CONTAINER_PORT,\n );\n if (freshWebPort && freshWebPort !== box.webHostPort) {\n box.webHostPort = freshWebPort;\n await recordBox(box);\n }\n }\n // sshd died with the container; relaunch it, re-resolve the (reallocated)\n // loopback host port, and regenerate `~/.agentbox/ssh/config`.\n await refreshBoxSshd(box);\n // Docker reallocated the ephemeral host ports above, so both Portless\n // routes now point at stale ports — re-register them. Best-effort and\n // silent (startBox has no onLog); if the proxy/Portless is gone the box\n // still works on loopback.\n if ((box.portlessAlias && box.webHostPort) || (box.portlessVncAlias && box.vncHostPort)) {\n try {\n const portless = await detectPortless();\n if (portless.installed) {\n let dirty = false;\n if (box.portlessAlias && box.webHostPort) {\n await portlessAlias(box.portlessAlias, box.webHostPort);\n // The proxy's scheme/port can change between sessions — re-resolve.\n const url = await portlessGetUrl(box.portlessAlias);\n if (url !== box.portlessUrl) {\n box.portlessUrl = url;\n dirty = true;\n }\n }\n if (box.portlessVncAlias && box.vncHostPort) {\n await portlessAlias(box.portlessVncAlias, box.vncHostPort);\n const url = await portlessGetUrl(box.portlessVncAlias);\n if (url !== box.portlessVncUrl) {\n box.portlessVncUrl = url;\n dirty = true;\n }\n }\n if (dirty) await recordBox(box);\n }\n } catch {\n /* best-effort */\n }\n }\n // Relay's in-memory registry may have been lost if the relay restarted\n // between create and now (or this is the first start after a host reboot).\n // Re-ensure + re-register so outbound push from the box keeps working.\n if (box.relayToken) {\n try {\n await ensureRelay();\n await registerBoxWithRelay({\n boxId: box.id,\n token: box.relayToken,\n name: box.name,\n containerName: box.container,\n createdAt: box.createdAt,\n projectIndex: box.projectIndex,\n worktrees: box.gitWorktrees,\n autoApproveHostActions: box.autoApproveHostActions,\n autoApproveSafeHostActions: box.autoApproveSafeHostActions,\n agent: box.agents?.[0] ?? box.lastAgent,\n });\n } catch {\n // best-effort\n }\n }\n return { record: box };\n}\n\nexport interface OpenedBox extends OpenResult {\n record: BoxRecord;\n}\n\nexport async function openBoxInFinder(idOrName: string, opts: OpenOptions): Promise<OpenedBox> {\n const box = await resolveBox(idOrName);\n const result = await openInFinder(box, opts);\n return { ...result, record: box };\n}\n\nexport async function getBoxHostPaths(\n idOrName: string,\n): Promise<{ record: BoxRecord; paths: HostPaths }> {\n const box = await resolveBox(idOrName);\n const paths = await getHostPaths(box);\n return { record: box, paths };\n}\n\nexport interface InspectedBox {\n record: BoxRecord;\n state: BoxState;\n snapshotSizeBytes: number | null;\n dockerInspect: unknown;\n /** Null when the container isn't running; otherwise best-effort probe of the tmux 'claude' session. */\n claudeSession: AgentSessionInfo | null;\n /** Null when the container isn't running; otherwise best-effort probe of the tmux 'codex' session. */\n codexSession: AgentSessionInfo | null;\n /** Null when the container isn't running; otherwise best-effort probe of the tmux 'opencode' session. */\n opencodeSession: AgentSessionInfo | null;\n /** Live shell tmux sessions; `[]` when the container isn't running. */\n shellSessions: ShellSessionSummary[];\n /** Persisted status snapshot (services/tasks/ports/claude); null when none. */\n persistedStatus: BoxStatus | null;\n /** Host paths for `agentbox open`. */\n hostPaths: HostPaths;\n /** Box network surface: domain + VNC + service ports. */\n endpoints: BoxEndpoints;\n}\n\nasync function dirSizeBytes(path: string): Promise<number | null> {\n try {\n const result = await execa('du', ['-sk', path], { reject: false });\n if (result.exitCode !== 0) return null;\n const sizeKb = Number.parseInt((result.stdout ?? '').split(/\\s+/)[0] ?? '', 10);\n if (Number.isNaN(sizeKb)) return null;\n return sizeKb * 1024;\n } catch {\n return null;\n }\n}\n\nexport async function inspectBox(idOrName: string): Promise<InspectedBox> {\n const record = await resolveBox(idOrName);\n const state = await inspectContainerStatus(record.container);\n const snapshotSizeBytes = record.snapshotDir ? await dirSizeBytes(record.snapshotDir) : null;\n const dockerJson = await inspectContainer(record.container);\n\n let claudeSession: AgentSessionInfo | null = null;\n let codexSession: AgentSessionInfo | null = null;\n let opencodeSession: AgentSessionInfo | null = null;\n let shellSessions: ShellSessionSummary[] = [];\n if (state === 'running') {\n try {\n claudeSession = await agentSession('claude', record.container);\n } catch {\n claudeSession = null;\n }\n try {\n codexSession = await agentSession('codex', record.container);\n } catch {\n codexSession = null;\n }\n try {\n opencodeSession = await agentSession('opencode', record.container);\n } catch {\n opencodeSession = null;\n }\n shellSessions = await listShellSessions(record.container);\n }\n\n const hostPaths = await getHostPaths(record);\n const engine = await detectEngine();\n const persistedStatus = await readBoxStatus(record);\n const endpoints = await getBoxEndpoints(record, engine, persistedStatus);\n\n return {\n record,\n state,\n snapshotSizeBytes,\n dockerInspect: dockerJson,\n claudeSession,\n codexSession,\n opencodeSession,\n shellSessions,\n persistedStatus,\n hostPaths,\n endpoints,\n };\n}\n\nexport interface DestroyOptions {\n keepSnapshot?: boolean;\n}\n\nexport interface DestroyResult {\n record: BoxRecord;\n removedContainer: boolean;\n removedVolumes: string[];\n removedSnapshot: string | null;\n}\n\nexport async function destroyBox(\n idOrName: string,\n opts: DestroyOptions = {},\n): Promise<DestroyResult> {\n const box = await resolveBox(idOrName);\n\n // Each step is best-effort. We collect what actually went away so the CLI\n // can show a truthful summary even if e.g. the container was gone already.\n if (box.relayToken) {\n try {\n await forgetBoxFromRelay(box.id);\n } catch {\n // best-effort — relay may be down or already wiped the entry\n }\n }\n // Remove the Portless routes so they don't dangle in the user's proxy\n // config. Web alias + VNC alias are independent — drop whichever was set.\n if (box.portlessAlias) {\n try {\n await portlessUnalias(box.portlessAlias);\n } catch {\n // best-effort — Portless may be uninstalled or the route already gone\n }\n }\n if (box.portlessVncAlias) {\n try {\n await portlessUnalias(box.portlessVncAlias);\n } catch {\n // best-effort\n }\n }\n // Deregister each in-container worktree from the host main repo. Skip\n // Every docker box — including checkpoint-restored ones — now owns a FRESH,\n // per-box worktree + branch (checkpoint restore mints its own via\n // regenerateRestoredWorktrees rather than reusing the source's), so the host\n // `.git/worktrees/<name>` registration is this box's to clean up. Skipping it\n // (the old `!checkpointImage` gate, from when restores shared the source's\n // worktree) would leak a registration per restore. Best-effort + container-\n // only paths, so it resolves to a `git worktree prune` on the host.\n for (const w of box.gitWorktrees ?? []) {\n try {\n await removeInBoxWorktree({\n hostMainRepo: w.hostMainRepo,\n gitWorktreePath: w.gitWorktreePath,\n });\n } catch {\n // best-effort\n }\n }\n const beforeContainer = await inspectContainerStatus(box.container);\n await removeContainer(box.container);\n const afterContainer = await inspectContainerStatus(box.container);\n const removedContainer = beforeContainer !== 'missing' && afterContainer === 'missing';\n\n const removedVolumes: string[] = [];\n // A per-box agent config volume is box-private and safe to remove. The SHARED\n // one holds user identity (auth, skills, plugins) across every box, so it is\n // never auto-removed — users delete it by hand if they want to.\n //\n // Driven off the registry rather than three named constants: the shared name\n // IS `spec.dockerVolume`, so naming it again here was a second copy that a\n // fourth agent would silently not be part of.\n for (const { volume } of boxAgentConfigVolumes(box)) {\n if (!volume) continue;\n await removeVolume(volume);\n removedVolumes.push(volume);\n }\n // Per-box `.vscode-server` and `.cursor-server` volumes. The shared\n // SHARED_*_EXTENSIONS_VOLUMEs are never auto-removed (parallel reasoning to\n // the shared claude volume).\n const perBoxIdeVolumes = [\n box.vscodeServerVolume ?? vscodeServerVolumeName(box.id),\n box.cursorServerVolume ?? cursorServerVolumeName(box.id),\n ];\n for (const v of perBoxIdeVolumes) {\n await removeVolume(v);\n removedVolumes.push(v);\n }\n // Per-box dockerd data root. Skip when this box used the shared cache —\n // wiping it would also remove image layers other boxes (or future ones)\n // depend on. The shared volume is allowlisted in `pruneBoxes --all` too.\n if (box.dockerVolume && !box.dockerCacheShared) {\n await removeVolume(box.dockerVolume);\n removedVolumes.push(box.dockerVolume);\n }\n\n let removedSnapshot: string | null = null;\n if (box.snapshotDir && !opts.keepSnapshot) {\n try {\n await rm(box.snapshotDir, { recursive: true, force: true });\n removedSnapshot = box.snapshotDir;\n } catch {\n removedSnapshot = null;\n }\n }\n\n // The per-box runtime dir holds the ctl socket plus the workspace export\n // dir used by `agentbox open`. Wipe the whole thing so destroy leaves no\n // residue under ~/.agentbox/boxes/.\n try {\n await rm(boxRunDirFor(box), { recursive: true, force: true });\n } catch {\n // best-effort\n }\n\n await removeBoxRecord(box.id);\n // Drop this box's `~/.agentbox/ssh/config` alias (regenerated from state, which\n // no longer lists it). Best-effort — a stale alias is harmless (points at a\n // dead loopback port) but confusing. No-op for boxes that never had sshd.\n if (box.ssh) {\n try {\n await syncAgentboxSshConfig();\n } catch {\n /* best-effort */\n }\n }\n\n return { record: box, removedContainer, removedVolumes, removedSnapshot };\n}\n\nexport interface PruneOptions {\n dryRun?: boolean;\n all?: boolean;\n}\n\nexport interface PruneResult {\n removedRecords: string[];\n removedContainers: string[];\n removedVolumes: string[];\n removedSnapshotDirs: string[];\n removedBoxDirs: string[];\n removedCheckpointImages: string[];\n dryRun: boolean;\n}\n\nasync function listSnapshotDirs(): Promise<string[]> {\n try {\n const entries = await readdir(SNAPSHOTS_ROOT, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => join(SNAPSHOTS_ROOT, e.name));\n } catch {\n return [];\n }\n}\n\nasync function listBoxDirs(): Promise<string[]> {\n try {\n const entries = await readdir(BOXES_ROOT, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => join(BOXES_ROOT, e.name));\n } catch {\n return [];\n }\n}\n\n/**\n * Local Docker image *tags* that look like checkpoint images\n * (`agentbox-ckpt-<projectHash>:<name>`). Used by `prune --all` to find\n * candidates for reaping. An image is reapable only when **both** of these\n * are true: no surviving box's `checkpointImage` points at it, **and** no\n * on-disk manifest under `~/.agentbox/checkpoints/<projectHash>/<name>/`\n * names it as its `image` (see `listAllCheckpointImages`) — otherwise a\n * `destroy` + `prune --all` would silently break checkpoints the user still\n * intends to start new boxes from. Best-effort: returns empty on docker\n * errors.\n */\nasync function listCheckpointImageTags(): Promise<string[]> {\n const r = await execa(\n 'docker',\n ['image', 'ls', '--format', '{{.Repository}}:{{.Tag}}', `${CHECKPOINT_IMAGE_PREFIX}*`],\n { reject: false },\n );\n if (r.exitCode !== 0) return [];\n return (r.stdout ?? '')\n .split('\\n')\n .map((s) => s.trim())\n .filter((s) => s.startsWith(CHECKPOINT_IMAGE_PREFIX));\n}\n\nexport async function pruneBoxes(opts: PruneOptions = {}): Promise<PruneResult> {\n const dryRun = opts.dryRun ?? false;\n const all = opts.all ?? false;\n\n const { boxes } = await readState();\n\n // Step 1: missing-state records. Docker boxes only — a cloud box has no host\n // container (`container` is the synthetic `cloud:<sandboxId>`), so inspecting\n // it always fails and would class every live cloud box as an orphan record.\n // Their liveness is a provider question; `prune --provider <cloud>` answers it\n // by listing the remote sandboxes instead. Same guard `listBoxes` applies\n // before any docker probe.\n //\n // Persistent boxes are excluded outright: an always-on box that is currently\n // stopped (host rebooted, relay not up yet) reads as `missing` until the\n // reconcile runs, and prune would drop the only record of it — losing the box.\n // Its container/volumes stay in the `expected*` sets below via `survivingBoxes`.\n const dockerBoxes = boxes.filter(\n (b) => (b.provider ?? 'docker') === 'docker' && b.persistent !== true,\n );\n const stateChecks = await Promise.all(\n dockerBoxes.map(async (b) => ({ box: b, status: await inspectContainerStatus(b.container) })),\n );\n const missingRecords = stateChecks.filter((c) => c.status === 'missing').map((c) => c.box);\n\n // Step 2 (only with --all): orphan docker containers / volumes / snapshot\n // dirs / per-box dirs / unreferenced checkpoint images.\n let orphanContainers: string[] = [];\n let orphanVolumes: string[] = [];\n let orphanSnapshots: string[] = [];\n let orphanBoxDirs: string[] = [];\n let orphanCheckpointImages: string[] = [];\n\n if (all) {\n const liveContainers = await listAgentboxContainers();\n const liveVolumes = await listAgentboxVolumes();\n const liveSnapshotDirs = await listSnapshotDirs();\n const liveBoxDirs = await listBoxDirs();\n const liveCheckpointImages = await listCheckpointImageTags();\n // Manifests on disk are the durable source of truth for \"this checkpoint\n // exists\" — `destroyBox` leaves them alone on purpose, so an image whose\n // source box was destroyed is still pinned as long as its manifest is\n // there.\n const manifestPinnedImages = await listAllCheckpointImages();\n // The state we'd have AFTER step 1 runs: missing-state records gone.\n const survivingBoxes = boxes.filter((b) => !missingRecords.some((m) => m.id === b.id));\n const expectedContainers = new Set<string>([\n ...survivingBoxes.map((b) => b.container),\n // The relay no longer runs as a container; leftovers are collected\n // below.\n ]);\n const expectedVolumes = new Set<string>([\n // Every agent's volume, not three by name: an isolated volume missing\n // from this set is deleted as an orphan, so a fourth or plugin agent's\n // per-box config store would be pruned out from under a live box.\n ...survivingBoxes.flatMap((b) =>\n AGENT_SYNC_SPECS.map((spec) => agentConfigVolume(b, spec.id)).filter(\n (v): v is string => typeof v === 'string',\n ),\n ),\n ...survivingBoxes\n .map((b) => b.vscodeServerVolume)\n .filter((v): v is string => typeof v === 'string'),\n ...survivingBoxes\n .map((b) => b.cursorServerVolume)\n .filter((v): v is string => typeof v === 'string'),\n ...survivingBoxes\n .map((b) => b.dockerVolume)\n .filter((v): v is string => typeof v === 'string'),\n // Every agent's SHARED config volume holds user identity (auth, skills,\n // plugins) across boxes; never reap one via prune even when no surviving\n // box references it. From the registry, so a new agent is covered without\n // an edit here.\n ...AGENT_SYNC_SPECS.map((spec) => spec.dockerVolume),\n // The shared agents-config volume — holds the cross-agent ~/.agents skills.\n SHARED_AGENTS_VOLUME,\n // Shared across boxes: downloaded IDE extensions. Same reasoning.\n SHARED_VSCODE_EXTENSIONS_VOLUME,\n SHARED_CURSOR_EXTENSIONS_VOLUME,\n // Shared in-box docker image cache — opt-in via `box.dockerCacheShared`,\n // never auto-removed (image layers may be reused by future boxes).\n SHARED_DOCKER_CACHE_VOLUME,\n ]);\n const expectedSnapshots = new Set(\n survivingBoxes\n .filter((b): b is BoxRecord & { snapshotDir: string } => typeof b.snapshotDir === 'string')\n .map((b) => b.snapshotDir),\n );\n const expectedBoxDirs = new Set(survivingBoxes.map((b) => boxRunDirFor(b)));\n // Checkpoint images: keep any tag that either a surviving box's\n // `checkpointImage` points at, or that any on-disk manifest still claims\n // as its `image`. The manifest case is the one that matters most after\n // destroy: the source box is gone but the user still wants to seed new\n // boxes from the checkpoint. The surviving-box case stays as a fallback\n // for the edge where someone `rm -rf`'d a manifest dir while a box\n // restored from it is still running.\n const expectedCheckpointImages = new Set<string>([\n ...survivingBoxes\n .map((b) => b.checkpointImage)\n .filter((v): v is string => typeof v === 'string'),\n ...manifestPinnedImages,\n ]);\n orphanContainers = liveContainers.filter((c) => !expectedContainers.has(c));\n orphanVolumes = liveVolumes.filter((v) => !expectedVolumes.has(v));\n orphanSnapshots = liveSnapshotDirs.filter((d) => !expectedSnapshots.has(d));\n orphanBoxDirs = liveBoxDirs.filter((d) => !expectedBoxDirs.has(d));\n orphanCheckpointImages = liveCheckpointImages.filter((t) => !expectedCheckpointImages.has(t));\n }\n\n if (dryRun) {\n return {\n removedRecords: missingRecords.map((b) => b.id),\n removedContainers: orphanContainers,\n removedVolumes: orphanVolumes,\n removedSnapshotDirs: orphanSnapshots,\n removedBoxDirs: orphanBoxDirs,\n removedCheckpointImages: orphanCheckpointImages,\n dryRun: true,\n };\n }\n\n for (const b of missingRecords) await removeBoxRecord(b.id);\n for (const c of orphanContainers) await removeContainer(c);\n for (const v of orphanVolumes) await removeVolume(v);\n for (const d of orphanSnapshots) {\n try {\n await rm(d, { recursive: true, force: true });\n } catch {\n // best-effort\n }\n }\n for (const d of orphanBoxDirs) {\n try {\n await rm(d, { recursive: true, force: true });\n } catch {\n // best-effort\n }\n }\n for (const img of orphanCheckpointImages) {\n await removeImage(img, { force: true });\n }\n\n // Migration sweep: the relay used to be a docker container on a dedicated\n // network with its own image. None of those exist after this version of\n // agentbox; drop any leftovers from previous installs. Idempotent and\n // best-effort — these calls succeed silently if the objects are already\n // gone.\n if (all) {\n try {\n await removeContainer(RELAY_CONTAINER_NAME);\n } catch {\n // best-effort\n }\n try {\n await execa('docker', ['image', 'rm', RELAY_IMAGE_REF], { reject: false });\n } catch {\n // best-effort\n }\n try {\n await removeNetwork(RELAY_NETWORK_NAME);\n } catch {\n // best-effort\n }\n }\n\n return {\n removedRecords: missingRecords.map((b) => b.id),\n removedContainers: orphanContainers,\n removedVolumes: orphanVolumes,\n removedSnapshotDirs: orphanSnapshots,\n removedBoxDirs: orphanBoxDirs,\n removedCheckpointImages: orphanCheckpointImages,\n dryRun: false,\n };\n}\n\n// Help vitest / unit tests get to the snapshot-root constant without pulling\n// the whole snapshot module surface.\nexport { SNAPSHOTS_ROOT };\n\n// Re-export the file existence helper for inspect output; useful guard for\n// callers that want to know if a snapshot dir was ever created.\nexport async function snapshotPresent(path: string | null): Promise<boolean> {\n if (!path) return false;\n try {\n const s = await stat(path);\n return s.isDirectory();\n } catch {\n return false;\n }\n}\n","import { execa } from 'execa';\nimport {\n buildTermSafeTmuxExec,\n buildTmuxSessionArgs,\n CONTAINER_USER,\n} from './sync/agents/shared.js';\n\n/** Default tmux session name for `agentbox shell` (the box's first shell). */\nexport const DEFAULT_SHELL_SESSION = 'shell';\n\n/** Reserved prefix for non-default shell sessions: `shell-2`, `shell-build`, … */\nexport const SHELL_SESSION_PREFIX = `${DEFAULT_SHELL_SESSION}-`;\n\nexport interface StartShellSessionOptions {\n container: string;\n sessionName?: string;\n /** In-container user (default vscode). The tmux server is per-user, so every\n * helper here must agree on it. */\n user?: string;\n /** Pass `-l` to bash so the login profile loads (default true). */\n login?: boolean;\n}\n\nexport interface ShellSessionInfo {\n running: boolean;\n sessionName: string;\n}\n\nexport interface ShellSessionSummary {\n /** User-facing label: `shell` for the default, else the suffix (`2`, `build`). */\n label: string;\n /** Underlying tmux session name. */\n sessionName: string;\n /** Whether at least one client is attached. */\n attached: boolean;\n /** ISO-8601 creation time, or null when tmux didn't report it. */\n createdAt: string | null;\n}\n\n/**\n * Map a user-facing shell label to its tmux session name. The default shell\n * (`undefined` / empty / `shell`) is the bare `shell`; everything else is\n * `shell-<label>`, so every shell session shares the `shell` prefix.\n */\nexport function shellSessionName(label?: string): string {\n const l = (label ?? '').trim();\n if (l === '' || l === DEFAULT_SHELL_SESSION) return DEFAULT_SHELL_SESSION;\n return `${SHELL_SESSION_PREFIX}${l}`;\n}\n\n/** Inverse of {@link shellSessionName}: the user-facing label for a session. */\nexport function shellLabel(sessionName: string): string {\n return sessionName === DEFAULT_SHELL_SESSION\n ? DEFAULT_SHELL_SESSION\n : sessionName.slice(SHELL_SESSION_PREFIX.length);\n}\n\n/**\n * True iff a tmux session name belongs to a shell (vs the `claude` agent\n * session or a dashboard `*-dash` grouped sibling). Pure string rule — no\n * config dependency, never collides with the agent session.\n */\nexport function isShellSessionName(name: string): boolean {\n if (name === DEFAULT_SHELL_SESSION) return true;\n return name.startsWith(SHELL_SESSION_PREFIX) && !name.endsWith('-dash');\n}\n\n/**\n * Pick the lowest-free shell session name given the ones that already exist:\n * `shell`, then `shell-2`, `shell-3`, … (never recycles a name that is in use).\n */\nexport function allocateShellSessionName(existing: readonly string[]): string {\n const taken = new Set(existing);\n if (!taken.has(DEFAULT_SHELL_SESSION)) return DEFAULT_SHELL_SESSION;\n for (let n = 2; ; n++) {\n const candidate = `${SHELL_SESSION_PREFIX}${String(n)}`;\n if (!taken.has(candidate)) return candidate;\n }\n}\n\n/**\n * Parse the tab-separated output of `tmux list-sessions -F\n * '#{session_name}\\t#{session_created}\\t#{session_attached}'`, keeping only\n * shell sessions. Default `shell` sorts first, the rest by creation time.\n */\nexport function parseShellSessionList(stdout: string): ShellSessionSummary[] {\n const out: ShellSessionSummary[] = [];\n for (const line of stdout.split('\\n')) {\n if (line.trim() === '') continue;\n const [name, created, attached] = line.split('\\t');\n if (name === undefined || !isShellSessionName(name)) continue;\n let createdAt: string | null = null;\n const secs = Number.parseInt((created ?? '').trim(), 10);\n if (Number.isFinite(secs) && secs > 0) createdAt = new Date(secs * 1000).toISOString();\n out.push({\n label: shellLabel(name),\n sessionName: name,\n attached: Number.parseInt((attached ?? '0').trim(), 10) > 0,\n createdAt,\n });\n }\n out.sort((a, b) => {\n if (a.sessionName === DEFAULT_SHELL_SESSION) return -1;\n if (b.sessionName === DEFAULT_SHELL_SESSION) return 1;\n return (a.createdAt ?? '').localeCompare(b.createdAt ?? '');\n });\n return out;\n}\n\n/**\n * Enumerate a box's shell tmux sessions. Best-effort: a missing tmux server,\n * a stopped/paused container, or any error surfaces as `[]`.\n */\nexport async function listShellSessions(\n container: string,\n user?: string,\n): Promise<ShellSessionSummary[]> {\n const res = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n user ?? CONTAINER_USER,\n container,\n 'tmux',\n 'list-sessions',\n '-F',\n // Literal tabs reach tmux verbatim (execa array args, no host shell).\n '#{session_name}\\t#{session_created}\\t#{session_attached}',\n ],\n { reject: false },\n );\n if (res.exitCode !== 0) return [];\n return parseShellSessionList(res.stdout ?? '');\n}\n\n/**\n * Start a detached tmux session running `bash` inside the container — the shell\n * counterpart of `startClaudeSession`. The session survives client disconnects;\n * reattach with {@link buildShellSessionAttachArgv}.\n *\n * We forward the host's TERM (default xterm-256color) so the in-container tmux\n * picks the right terminal-overrides at session creation time — without this,\n * docker exec defaults TERM to `xterm` and tmux can't declare 24-bit color.\n */\nexport async function startShellSession(opts: StartShellSessionOptions): Promise<void> {\n const sessionName = opts.sessionName ?? DEFAULT_SHELL_SESSION;\n const user = opts.user ?? CONTAINER_USER;\n const login = opts.login !== false;\n const term = process.env['TERM'] ?? 'xterm-256color';\n // tmux runs a single-arg shell-command via `/bin/sh -c`; `bash -l` / `bash`\n // need no quoting.\n const cmd = login ? 'bash -l' : 'bash';\n const result = await execa(\n 'docker',\n [\n 'exec',\n '-e',\n `TERM=${term}`,\n '--user',\n user,\n opts.container,\n 'tmux',\n 'new-session',\n '-d',\n '-s',\n sessionName,\n cmd,\n ...buildTmuxSessionArgs(sessionName),\n ],\n { reject: false },\n );\n if (result.exitCode === 0) return;\n const stderr = (result.stderr ?? '').toString();\n if (result.exitCode === 127 || /command not found|tmux: not found/i.test(stderr)) {\n throw new Error(\n `tmux is missing from the box image. Rebuild with: docker rmi agentbox/box:dev && retry.`,\n );\n }\n throw new Error(\n `failed to start shell session in ${opts.container}: ${\n stderr.trim() || `exit ${String(result.exitCode)}`\n }`,\n );\n}\n\n/**\n * The `docker` argv that attaches an interactive terminal to a box's shell\n * tmux session. `user` must match the user the session was started as (the\n * tmux server is per-user). Handed to the node-pty wrapper by `agentbox shell`.\n */\nexport function buildShellSessionAttachArgv(\n container: string,\n sessionName?: string,\n user?: string,\n): string[] {\n const name = sessionName ?? DEFAULT_SHELL_SESSION;\n return buildTermSafeTmuxExec({\n container,\n user: user ?? CONTAINER_USER,\n tmuxScript: 'exec tmux attach -t \"$1\"',\n positionals: [name],\n });\n}\n\n/**\n * Best-effort: returns `{ running: false }` for any non-zero exit from\n * `tmux has-session` (covers \"no server running\" and \"no such session\").\n */\nexport async function shellSessionInfo(\n container: string,\n sessionName?: string,\n user?: string,\n): Promise<ShellSessionInfo> {\n const name = sessionName ?? DEFAULT_SHELL_SESSION;\n const has = await execa(\n 'docker',\n ['exec', '--user', user ?? CONTAINER_USER, container, 'tmux', 'has-session', '-t', name],\n { reject: false },\n );\n return { running: has.exitCode === 0, sessionName: name };\n}\n\n/**\n * Kill a box's shell tmux session (`tmux kill-session`). Returns true on a\n * clean kill, false when the session was already gone / no tmux server.\n */\nexport async function killShellSession(\n container: string,\n sessionName: string,\n user?: string,\n): Promise<boolean> {\n const res = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n user ?? CONTAINER_USER,\n container,\n 'tmux',\n 'kill-session',\n '-t',\n sessionName,\n ],\n { reject: false },\n );\n return res.exitCode === 0;\n}\n","import { join } from 'node:path';\nimport { loadConfig } from '@agentbox/ctl';\nimport type { BoxStatus } from '@agentbox/ctl';\nimport type { BoxEndpoint, BoxEndpoints, BoxRecord } from '@agentbox/core';\nimport type { DockerEngine } from './sync/host-export.js';\nimport { buildVncUrls, VNC_CONTAINER_PORT } from './vnc.js';\nimport { WEB_CONTAINER_PORT } from './web.js';\n\n// BoxEndpoint / BoxEndpoints are the provider-neutral network-surface shape;\n// they live in @agentbox/core. Re-exported so existing consumers are unchanged.\nexport type { BoxEndpoint, BoxEndpoints };\n\n/**\n * Build the box's user-facing network surface. Pure host-side: no docker exec,\n * no network — safe to call from `agentbox list` in a tight loop.\n *\n * Service ports come from the persisted status snapshot when available\n * (`~/.agentbox/boxes/<id>/status.json`, pushed by the in-box supervisor via\n * the relay). That snapshot resolves `ready_when.port` *inside the box*, so it\n * works even when `agentbox.yaml` lives only in the box and was never pulled to\n * the host. Falls back to parsing the host's `agentbox.yaml` for pre-relay\n * boxes (or ones that never pushed a snapshot).\n *\n * Missing config + no snapshot is non-fatal: the VNC entry (if any) is still\n * returned. Engine drives reachability — OrbStack auto-routes\n * `<container>.orb.local:<port>` for any in-box port; other engines see only\n * what we explicitly publish via `docker run -p`, which today is just VNC.\n */\nexport async function getBoxEndpoints(\n record: BoxRecord,\n engine: DockerEngine,\n persisted?: BoxStatus | null,\n): Promise<BoxEndpoints> {\n const domainIsOrb = engine === 'orbstack';\n const domain = domainIsOrb ? `${record.container}.orb.local` : '127.0.0.1';\n\n const endpoints: BoxEndpoint[] = [];\n\n if (record.vncEnabled && record.vncPassword) {\n const vncUrls = buildVncUrls(record, engine);\n // Preference: portless (stable name) > orb.local > loopback. Mirrors the\n // web endpoint's choice below and `agentbox screen`'s default.\n const url =\n engine === 'orbstack'\n ? (vncUrls.orbUrl ?? vncUrls.loopbackUrl)\n : (vncUrls.portlessUrl ?? vncUrls.loopbackUrl);\n endpoints.push({\n kind: 'vnc',\n name: 'vnc',\n containerPort: VNC_CONTAINER_PORT,\n url,\n reachable: Boolean(url),\n });\n }\n\n // The single `expose:`-flagged service, from the snapshot first (works when\n // agentbox.yaml lives only in the box), else the host yaml.\n let webServiceName: string | null = null;\n const persistedWeb = persisted?.services.find((s) => s.expose);\n if (persistedWeb) {\n webServiceName = persistedWeb.name;\n }\n\n const pushService = (name: string, port: number): void => {\n // The web service is surfaced as the dedicated `web` endpoint below;\n // don't also list it as a generic service.\n if (name === webServiceName) return;\n endpoints.push({\n kind: 'service',\n name,\n containerPort: port,\n // Only OrbStack auto-routes arbitrary in-box ports; on other engines we\n // don't publish service ports, so the URL isn't host-reachable.\n ...(domainIsOrb\n ? { url: `http://${domain}:${String(port)}`, reachable: true }\n : { reachable: false }),\n });\n };\n\n const persistedServices = persisted?.services.filter(\n (s): s is typeof s & { port: number } => typeof s.port === 'number',\n );\n if (persistedServices && persistedServices.length > 0) {\n for (const svc of persistedServices) pushService(svc.name, svc.port);\n } else {\n try {\n const cfg = await loadConfig(join(record.workspacePath, 'agentbox.yaml'));\n if (!webServiceName) {\n webServiceName = cfg.services.find((s) => s.expose)?.name ?? null;\n }\n for (const svc of cfg.services) {\n if (svc.readyWhen?.kind !== 'port') continue;\n pushService(svc.name, svc.readyWhen.port);\n }\n } catch {\n // No persisted snapshot and no host agentbox.yaml — skip service\n // endpoints. The VNC entry, if any, is unaffected.\n }\n }\n\n // Web endpoint: only for boxes that reserved container :80 at create. The\n // URL is the published loopback host port — uniform across engines, NOT\n // gated on OrbStack (requirement: don't rely on orb auto-DNS). No url until\n // both a service declares `expose:` and the host port is resolved; until\n // then it renders as \"reserved\".\n if (record.webContainerPort !== undefined) {\n const hasTarget = webServiceName !== null && record.webHostPort !== undefined;\n // A registered Portless alias gives the box a stable <name>.localhost URL\n // on non-OrbStack engines. `portlessUrl` is the real URL resolved from the\n // proxy at create/start (scheme + port vary); fall back to the https form\n // for records written before that field existed. No `portless` shell-out\n // here — this runs in a tight loop for `agentbox list`.\n const usePortless = record.portlessAlias !== undefined && engine !== 'orbstack';\n const webUrl = usePortless\n ? (record.portlessUrl ?? `https://${record.portlessAlias}.localhost`)\n : `http://127.0.0.1:${String(record.webHostPort)}`;\n endpoints.push({\n kind: 'web',\n name: webServiceName ?? 'web',\n containerPort: record.webContainerPort ?? WEB_CONTAINER_PORT,\n ...(hasTarget ? { url: webUrl, reachable: true } : { reachable: false }),\n });\n }\n\n return { domain, domainIsOrb, endpoints };\n}\n","import { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type { BoxResourceLimits, BoxResourceStats } from '@agentbox/core';\nimport { CHECKPOINT_IMAGE_PREFIX, checkpointImageTag } from './checkpoint.js';\nimport { inspectContainer, inspectContainerStatus, inspectVolumeMountpoint } from './docker.js';\nimport { detectEngine } from './sync/host-export.js';\nimport type { BoxRecord } from './state.js';\n\n/**\n * Parse one of Docker's human-formatted size tokens (`512MiB`, `1.2kB`,\n * `3.4GB`, `0B`, `--`). Returns null when unparseable. Docker mixes binary\n * (`KiB/MiB/GiB`) and decimal (`kB/MB/GB`) suffixes depending on the column, so\n * we handle both.\n */\nexport function parseDockerSize(raw: string): number | null {\n const s = raw.trim();\n if (!s || s === '--' || s === 'N/A') return null;\n const m = /^([\\d.]+)\\s*([A-Za-z]*)$/.exec(s);\n if (!m) return null;\n const n = Number(m[1]);\n if (!Number.isFinite(n)) return null;\n const unit = (m[2] ?? '').toLowerCase();\n const mult: Record<string, number> = {\n '': 1,\n b: 1,\n kb: 1e3,\n mb: 1e6,\n gb: 1e9,\n tb: 1e12,\n kib: 1024,\n mib: 1024 ** 2,\n gib: 1024 ** 3,\n tib: 1024 ** 4,\n };\n const factor = mult[unit];\n return factor === undefined ? null : n * factor;\n}\n\nfunction parsePercent(raw: string | undefined): number | null {\n if (!raw) return null;\n const n = Number(raw.replace('%', '').trim());\n return Number.isFinite(n) ? n : null;\n}\n\n/** Split Docker's \"<a> / <b>\" pair columns (MemUsage, NetIO, BlockIO). */\nfunction splitPair(raw: string | undefined): [string, string] | null {\n if (!raw) return null;\n const parts = raw.split('/');\n if (parts.length !== 2) return null;\n return [parts[0]!.trim(), parts[1]!.trim()];\n}\n\nasync function duBytes(path: string): Promise<number | null> {\n const result = await execa('du', ['-sk', path], { reject: false });\n if (result.exitCode !== 0) return null;\n const kb = Number.parseInt((result.stdout ?? '').split(/\\s+/)[0] ?? '', 10);\n return Number.isNaN(kb) ? null : kb * 1024;\n}\n\n/**\n * Best-effort on-host byte size of a Docker named volume. Fastest path first:\n * 1. OrbStack exposes volumes live at ~/OrbStack/docker/volumes/<name>/.\n * 2. `docker system df -v` (cheap-walked once; may report \"N/A\").\n * 3. The reported mountpoint, only when host-readable (Linux native Docker).\n * Returns null when no path is reachable from the host (the macOS VM case\n * where `system df` also has no number).\n */\nexport async function volumeSizeBytes(name: string): Promise<number | null> {\n if (!name) return null;\n const engine = await detectEngine();\n if (engine === 'orbstack') {\n const live = join(homedir(), 'OrbStack', 'docker', 'volumes', name);\n const sz = await duBytes(live);\n if (sz !== null) return sz;\n }\n const df = await execa('docker', ['system', 'df', '-v', '--format', '{{json .Volumes}}'], {\n reject: false,\n });\n if (df.exitCode === 0) {\n try {\n const vols = JSON.parse(df.stdout || '[]') as Array<{ Name?: string; Size?: string }>;\n const hit = vols.find((v) => v.Name === name);\n const parsed = hit?.Size ? parseDockerSize(hit.Size) : null;\n if (parsed !== null) return parsed;\n } catch {\n // fall through to mountpoint\n }\n }\n const mp = await inspectVolumeMountpoint(name);\n if (mp && !mp.startsWith('/var/lib/docker')) {\n return duBytes(mp);\n }\n return null;\n}\n\n/**\n * On-host byte size of a Docker image (sum of its own layer sizes — what\n * `docker images` reports). Null on docker errors.\n */\nasync function imageBytes(tag: string): Promise<number | null> {\n const r = await execa('docker', ['image', 'inspect', tag, '--format', '{{.Size}}'], {\n reject: false,\n });\n if (r.exitCode !== 0) return null;\n const n = Number.parseInt((r.stdout ?? '').trim(), 10);\n return Number.isFinite(n) ? n : null;\n}\n\n/**\n * Size of a project's most-recent checkpoint image (the head of the lineage,\n * resolved via the `checkpointImageTag` helper from a checkpoint *name*). The\n * caller passes the name because we don't enumerate manifests from this\n * module — that lives in checkpoint.ts. Null when the image isn't present.\n */\nexport async function projectCheckpointImageBytes(\n projectRoot: string,\n name: string,\n): Promise<number | null> {\n return imageBytes(checkpointImageTag(projectRoot, name));\n}\n\n/**\n * Total on-host bytes of every checkpoint image (the durable, cross-box\n * warm-state assets). Walks every image tag under `CHECKPOINT_IMAGE_PREFIX`.\n * Null when none exist.\n */\nexport async function allCheckpointImagesBytes(): Promise<number | null> {\n const r = await execa(\n 'docker',\n [\n 'image',\n 'ls',\n '--format',\n '{{.Repository}}:{{.Tag}}\\t{{.Size}}',\n `${CHECKPOINT_IMAGE_PREFIX}*`,\n ],\n { reject: false },\n );\n if (r.exitCode !== 0) return null;\n const lines = (r.stdout ?? '')\n .split('\\n')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (lines.length === 0) return null;\n let total = 0;\n let any = false;\n for (const line of lines) {\n const [, size] = line.split('\\t');\n const n = size ? parseDockerSize(size) : null;\n if (n !== null) {\n total += n;\n any = true;\n }\n }\n return any ? total : null;\n}\n\n/** On-host byte size of the whole ~/.agentbox state/runtime directory. */\nexport async function agentboxHomeBytes(): Promise<number | null> {\n return duBytes(join(homedir(), '.agentbox'));\n}\n\nfunction limitsFromRecord(record: BoxRecord): BoxResourceLimits {\n const r = record.resourceLimits;\n return {\n memoryBytes: r?.memoryBytes && r.memoryBytes > 0 ? r.memoryBytes : null,\n cpus: r?.cpus && r.cpus > 0 ? r.cpus : null,\n pidsLimit: r?.pidsLimit && r.pidsLimit > 0 ? r.pidsLimit : null,\n disk: r?.disk || null,\n };\n}\n\n/**\n * Cross-check persisted limits against the live container's HostConfig so an\n * externally `docker update`d box still reports the truth. The persisted\n * record stays the fallback when the container is gone.\n */\nfunction reconcileLimits(persisted: BoxResourceLimits, dockerJson: unknown): BoxResourceLimits {\n const hc = (dockerJson as { HostConfig?: Record<string, unknown> } | null)?.HostConfig;\n if (!hc) return persisted;\n const mem = typeof hc.Memory === 'number' && hc.Memory > 0 ? hc.Memory : null;\n const nano = typeof hc.NanoCpus === 'number' && hc.NanoCpus > 0 ? hc.NanoCpus : null;\n const pids = typeof hc.PidsLimit === 'number' && hc.PidsLimit > 0 ? hc.PidsLimit : null;\n return {\n memoryBytes: mem ?? persisted.memoryBytes,\n cpus: nano ? nano / 1e9 : persisted.cpus,\n pidsLimit: pids ?? persisted.pidsLimit,\n disk: persisted.disk,\n };\n}\n\ninterface DockerStatsLine {\n CPUPerc?: string;\n MemUsage?: string;\n MemPerc?: string;\n PIDs?: string;\n NetIO?: string;\n BlockIO?: string;\n}\n\n/**\n * Container writable-layer size from `docker ps --size`. With the overlay\n * gone, `/workspace` lives here (not in a named volume), so this is the\n * box's primary writable-surface number.\n */\nasync function containerWritableBytes(container: string): Promise<number | null> {\n const r = await execa(\n 'docker',\n ['ps', '-a', '--filter', `name=^${container}$`, '--format', '{{.Size}}', '--size'],\n { reject: false },\n );\n if (r.exitCode !== 0) return null;\n // `--size` produces `<rw> (virtual <total>)`; we want the first number.\n const first = (r.stdout ?? '').split('\\n')[0]?.trim();\n if (!first) return null;\n const m = /^([^()]+?)(?:\\s*\\(.*\\))?$/.exec(first);\n const sz = m ? m[1]!.trim() : first;\n return parseDockerSize(sz);\n}\n\n/**\n * Provider-agnostic resource snapshot for a box. CPU/mem/pids/IO come from\n * `docker stats --no-stream` (point-in-time sample; only when the container is\n * running). Disk is the container's writable layer (where `/workspace` lives\n * now that the overlay is gone) plus the in-box dockerd's data-root volume;\n * the per-box host snapshot dir and the checkpoint image lineage are\n * reported on their own fields.\n */\nexport async function boxResourceStats(record: BoxRecord): Promise<BoxResourceStats> {\n const warnings: string[] = [];\n const dockerJson = await inspectContainer(record.container);\n const limits = reconcileLimits(limitsFromRecord(record), dockerJson);\n\n const [diskContainer, diskDocker, snapshotDiskBytes, checkpointImageBytesValue] =\n await Promise.all([\n containerWritableBytes(record.container),\n record.dockerVolume ? volumeSizeBytes(record.dockerVolume) : Promise.resolve(null),\n record.snapshotDir ? duBytes(record.snapshotDir) : Promise.resolve(null),\n record.checkpointImage ? imageBytes(record.checkpointImage) : Promise.resolve(null),\n ]);\n const diskUsedBytes =\n diskContainer === null && diskDocker === null ? null : (diskContainer ?? 0) + (diskDocker ?? 0);\n if (diskUsedBytes === null) {\n warnings.push('disk usage unavailable on this engine');\n }\n\n const base: BoxResourceStats = {\n source: 'docker',\n live: false,\n cpuPercent: null,\n memUsedBytes: null,\n memLimitBytes: limits.memoryBytes,\n memPercent: null,\n pids: null,\n diskUsedBytes,\n snapshotDiskBytes,\n checkpointVolumeBytes: checkpointImageBytesValue,\n netRxBytes: null,\n netTxBytes: null,\n blockReadBytes: null,\n blockWriteBytes: null,\n limits,\n warnings,\n };\n\n if ((await inspectContainerStatus(record.container)) !== 'running') {\n return base;\n }\n\n const proc = await execa(\n 'docker',\n ['stats', '--no-stream', '--format', '{{json .}}', record.container],\n { reject: false },\n );\n if (proc.exitCode !== 0 || !proc.stdout.trim()) {\n return base;\n }\n let line: DockerStatsLine;\n try {\n line = JSON.parse(proc.stdout.trim().split('\\n')[0]!) as DockerStatsLine;\n } catch {\n return base;\n }\n\n const memPair = splitPair(line.MemUsage);\n const memUsedBytes = memPair ? parseDockerSize(memPair[0]) : null;\n const memEngineTotal = memPair ? parseDockerSize(memPair[1]) : null;\n const netPair = splitPair(line.NetIO);\n const blkPair = splitPair(line.BlockIO);\n\n return {\n ...base,\n live: true,\n cpuPercent: parsePercent(line.CPUPerc),\n memUsedBytes,\n // The applied limit when set; otherwise docker stats' own denominator\n // (the engine/host total).\n memLimitBytes: limits.memoryBytes ?? memEngineTotal,\n memPercent: parsePercent(line.MemPerc),\n pids: line.PIDs ? Number.parseInt(line.PIDs, 10) || null : null,\n netRxBytes: netPair ? parseDockerSize(netPair[0]) : null,\n netTxBytes: netPair ? parseDockerSize(netPair[1]) : null,\n blockReadBytes: blkPair ? parseDockerSize(blkPair[0]) : null,\n blockWriteBytes: blkPair ? parseDockerSize(blkPair[1]) : null,\n };\n}\n","/**\n * The docker provider's uniform `ProviderModule` surface (see\n * `@agentbox/sandbox-core`'s `ProviderModule`). Docker is the local provider:\n * no cloud backend, no credentials/login, no base-snapshot fingerprint — just\n * the provider plus its doctor probes (moved here from apps/cli so the CLI\n * dispatches to it generically).\n */\n\nimport { execa } from 'execa';\nimport {\n AGENT_SYNC_SPECS,\n errSummary,\n type CheckResult,\n type ProviderModule,\n} from '@agentbox/sandbox-core';\nimport { dockerProvider } from './docker-provider.js';\nimport { DEFAULT_BOX_IMAGE, imageInfo } from './image.js';\nimport { volumeExists } from './docker.js';\nimport { detectEngine } from './sync/host-export.js';\nimport { currentDockerBaseFileHashes } from './prepared-state.js';\nimport { detectPortless, portlessDoctorRow, portlessServiceStatus } from './portless.js';\n\nasync function probeVersion(bin: string, args: string[] = ['--version']): Promise<string | null> {\n try {\n const r = await execa(bin, args, { reject: false });\n if (r.exitCode !== 0) return null;\n const out = `${r.stdout ?? ''}${r.stderr ?? ''}`.trim().split('\\n')[0] ?? '';\n return out.length > 0 ? out : bin;\n } catch {\n return null;\n }\n}\n\n/** Local, offline-safe docker health probes for `agentbox doctor`. */\nexport async function dockerChecks(): Promise<CheckResult[]> {\n const linux = process.platform === 'linux';\n const cli = await probeVersion('docker');\n if (!cli) {\n return [\n {\n label: 'docker cli',\n status: 'warn',\n detail: 'not found',\n hint: linux\n ? 'install docker engine: https://docs.docker.com/engine/install/'\n : 'install Docker Desktop, OrbStack, or docker engine',\n },\n ];\n }\n const cliRes: CheckResult = { label: 'docker cli', status: 'ok', detail: cli };\n\n // Everything below is an independent round-trip to the daemon, and they were\n // issued one after another: two full `docker info`s (this one and the engine\n // probe), an image inspect, three volume inspects, and the portless probe.\n // That's cheap on OrbStack (~80ms each) but `docker info` alone routinely\n // takes ~2s on Docker Desktop, so serially it dominated `doctor`. Fire them\n // together and pay for the slowest, not the sum. A down daemon just means the\n // extra probes fail too — we discard them and report the daemon below.\n const [info, img, vols, portless] = await Promise.all([\n // Daemon reachability. On Linux the most common failure is not a stopped\n // daemon but the user missing from the `docker` group — `docker info` then\n // exits non-zero with \"permission denied\" on the socket.\n execa('docker', ['info'], { reject: false }),\n imageInfo(DEFAULT_BOX_IMAGE).then(\n (i) => ({ ok: true as const, i }),\n (err: unknown) => ({ ok: false as const, err }),\n ),\n Promise.all(\n // Every agent's shared config volume, from the registry — the doctor row\n // should report a new agent's volume without an edit here.\n AGENT_SYNC_SPECS.map(async (spec) => ({\n name: spec.dockerVolume,\n exists: await volumeExists(spec.dockerVolume).catch(() => false),\n })),\n ),\n // OrbStack serves per-box .orb.local URLs natively; Portless only matters on\n // plain Docker Desktop / Linux docker engine — so the engine decides whether\n // the row exists at all.\n (async (): Promise<CheckResult | null> => {\n const engine = await detectEngine().catch(() => 'other' as const);\n if (engine === 'orbstack') return null;\n return portlessDoctorRow(await detectPortless(), await portlessServiceStatus());\n })(),\n ]);\n\n if (info.exitCode !== 0) {\n const permDenied = `${info.stderr ?? ''}`.toLowerCase().includes('permission denied');\n let hint: string;\n if (permDenied && linux) {\n hint =\n 'add your user to the docker group: `sudo usermod -aG docker $USER`, then log out/in (or run `newgrp docker`)';\n } else if (linux) {\n hint = 'start Docker: `sudo systemctl start docker` (install docker engine if missing)';\n } else {\n hint = 'start Docker (Desktop / OrbStack)';\n }\n return [\n cliRes,\n {\n label: 'docker daemon',\n status: 'warn',\n detail: permDenied ? 'permission denied' : 'unreachable',\n hint,\n },\n ];\n }\n const daemonRes: CheckResult = { label: 'docker daemon', status: 'ok', detail: 'reachable' };\n\n const imgRes: CheckResult = !img.ok\n ? { label: 'box image', status: 'warn', detail: errSummary(img.err) }\n : img.i.exists\n ? { label: 'box image', status: 'ok', detail: `${DEFAULT_BOX_IMAGE} built` }\n : {\n label: 'box image',\n status: 'warn',\n detail: `${DEFAULT_BOX_IMAGE} not built`,\n hint: 'run `agentbox prepare --provider docker` (or let the wizard do it)',\n };\n\n const present = vols.filter((v) => v.exists).length;\n const volRes: CheckResult = {\n label: 'shared volumes',\n status: 'ok',\n detail: `${String(present)}/${String(vols.length)} present (seeded lazily)`,\n };\n\n const results = [cliRes, daemonRes, imgRes, volRes];\n if (portless) results.push(portless);\n return results;\n}\n\nexport const providerModule: ProviderModule = {\n provider: dockerProvider,\n // No `currentBaseFingerprintLive` — docker's base self-heals via ensureImage,\n // so it is never nagged about staleness. It still exposes the per-file hashes\n // so the System page can explain a `stale` docker row the same way it explains\n // a cloud one.\n currentBaseFileHashes: () => currentDockerBaseFileHashes(),\n doctorChecks: dockerChecks,\n};\n","/**\n * Docker implementations of the settings-propagate seams\n * (`@agentbox/sandbox-core` `agent-propagate.ts`): stage items *from* a config\n * volume and write items *into* a config volume, both via throwaway helper\n * containers so they work regardless of any box's run state (a shared-volume\n * write covers every docker box on that volume, running or paused).\n */\n\nimport { mkdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { execa } from 'execa';\nimport type { SettingsTarget, StagedItem } from '@agentbox/sandbox-core';\n\nconst posixDirname = (rel: string) => {\n const d = dirname(rel);\n return d === '.' ? '' : d;\n};\n\n/**\n * Copy `items` from a config volume into `stagingDir` (volume-style layout).\n * One helper-container run; `rsync --exclude=node_modules` for dirs (the box\n * carries platform binaries useless off-box), `cp -a` for files. Staged files\n * are chowned to the host user so the CLI can read/push them.\n */\nexport async function stageItemsFromVolume(\n volume: string,\n image: string,\n items: StagedItem[],\n stagingDir: string,\n): Promise<void> {\n if (items.length === 0) return;\n for (const item of items) {\n const parent = posixDirname(item.rel);\n if (parent) await mkdir(join(stagingDir, parent), { recursive: true });\n }\n const uid = process.getuid?.() ?? 0;\n const gid = process.getgid?.() ?? 0;\n const cmds = items.map((item) =>\n item.kind === 'dir'\n ? `mkdir -p '/stage/${item.rel}' && rsync -a --exclude=node_modules '/src/${item.rel}/' '/stage/${item.rel}/'`\n : `cp -a '/src/${item.rel}' '/stage/${item.rel}'`,\n );\n cmds.push(`chown -R ${String(uid)}:${String(gid)} /stage`);\n const r = await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:/src:ro`,\n '-v',\n `${stagingDir}:/stage`,\n image,\n 'sh',\n '-c',\n cmds.join(' && '),\n ],\n { reject: false },\n );\n if (r.exitCode !== 0) {\n throw new Error(\n `failed to stage items from volume ${volume}: ${(r.stderr ?? '').toString().trim() || `exit ${String(r.exitCode)}`}`,\n );\n }\n}\n\n/**\n * A `SettingsTarget` over a docker config volume. Every op is a helper\n * container; writes chown to the in-box uid 1000 (`vscode` in the box image).\n */\nexport function volumeSettingsTarget(volume: string, image: string, label: string): SettingsTarget {\n const run = (args: string[], input?: string) =>\n execa('docker', args, { reject: false, ...(input === undefined ? {} : { input }) });\n return {\n label,\n async exists(rel: string): Promise<boolean> {\n const r = await run([\n 'run',\n '--rm',\n '-v',\n `${volume}:/dst:ro`,\n image,\n 'test',\n '-e',\n `/dst/${rel}`,\n ]);\n return r.exitCode === 0;\n },\n async readText(rel: string): Promise<string | null> {\n const r = await run([\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:/dst:ro`,\n image,\n 'cat',\n `/dst/${rel}`,\n ]);\n return r.exitCode === 0 ? String(r.stdout ?? '') : null;\n },\n async writeText(rel: string, content: string, opts?: { mode?: number }): Promise<void> {\n const parent = posixDirname(rel);\n const chmod =\n opts?.mode !== undefined ? ` && chmod ${opts.mode.toString(8)} '/dst/${rel}'` : '';\n const r = await run(\n [\n 'run',\n '--rm',\n '-i',\n '--user',\n '0',\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n `${parent ? `mkdir -p '/dst/${parent}' && ` : ''}cat > '/dst/${rel}' && chown 1000:1000 '/dst/${rel}'${chmod}`,\n ],\n content,\n );\n if (r.exitCode !== 0) {\n throw new Error(\n `failed to write ${rel} into volume ${volume}: ${(r.stderr ?? '').toString().trim() || `exit ${String(r.exitCode)}`}`,\n );\n }\n },\n async copyIn(stagingAbs: string, rel: string, kind: 'dir' | 'file'): Promise<void> {\n const parent = posixDirname(rel);\n const script =\n `${parent ? `mkdir -p '/dst/${parent}' && ` : ''}` +\n (kind === 'dir'\n ? `mkdir -p '/dst/${rel}' && rsync -a --ignore-existing '/stage-item/' '/dst/${rel}/'`\n : `cp -a /stage-item '/dst/${rel}'`) +\n ` && chown -R 1000:1000 '/dst/${rel}'`;\n const r = await run([\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${stagingAbs}:/stage-item:ro`,\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n script,\n ]);\n if (r.exitCode !== 0) {\n throw new Error(\n `failed to copy ${rel} into volume ${volume}: ${(r.stderr ?? '').toString().trim() || `exit ${String(r.exitCode)}`}`,\n );\n }\n },\n };\n}\n","/**\n * The docker-side implementation of the hub's Portless (`agentbox.localhost`)\n * friendly-URL integration. The hub lifecycle itself lives in\n * `@agentbox/sandbox-core` and can't reach Portless (a docker-adjacent host\n * tool) directly, so it calls the `hub-hooks.ts` seam; the CLI installs\n * {@link dockerHubPortlessHooks} into that seam at startup. On a docker-free\n * host the seam is empty and the hub just advertises its loopback URL.\n *\n * Every function here is best-effort and never throws — a Portless failure\n * degrades to the loopback URL, exactly like the box path.\n */\nimport { mkdir, unlink, writeFile, readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { HubPortlessHooks } from '@agentbox/sandbox-core';\nimport { detectPortless, portlessAlias, portlessGetUrl, portlessUnalias } from './portless.js';\nimport { detectEngine } from './sync/host-export.js';\n\nconst STATE_DIR = join(homedir(), '.agentbox');\n\n/**\n * Portless alias for the hub itself. Unlike a box (a container that OrbStack can\n * reach at `<container>.orb.local`), the hub is a host loopback process, so\n * Portless is the only way to give it a friendly host URL. Fixed name → the URL\n * is always `https://agentbox.localhost` (kept static so the Next server-actions\n * origin allowlist can hard-code it). The resolved URL is cached to\n * `HUB_PORTLESS_FILE` so `current()` (read-only) knows the alias is actually\n * live — `portlessGetUrl` alone returns the deterministic fallback either way.\n */\nconst HUB_PORTLESS_ALIAS = 'agentbox';\nconst HUB_PORTLESS_FILE = join(STATE_DIR, 'hub', 'portless-url');\n\n/** The Portless URL cached by a prior `sync`, or null when unregistered. */\nasync function readHubPortlessUrl(): Promise<string | null> {\n try {\n const u = (await readFile(HUB_PORTLESS_FILE, 'utf8')).trim();\n return u.length > 0 ? u : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The hub's Portless URL *right now*, or null when it wouldn't resolve.\n *\n * Deliberately not just the cached file. The cache is written once, at hub\n * start, but both of its inputs can change underneath it: the proxy can die\n * (URL resolves to nothing) and it can come back in a different mode (the\n * no-root `:1355` no-TLS proxy vs the root `:443` HTTPS one), which changes the\n * URL's scheme *and* port. Callers — `agentbox hub status`, the tray app — get a\n * URL they can actually open, or none at all.\n */\nasync function currentHubPortlessUrl(): Promise<string | null> {\n const cached = await readHubPortlessUrl();\n if (cached === null) return null;\n const portless = await detectPortless();\n if (!portless.proxyRunning) return null;\n const url = await portlessGetUrl(HUB_PORTLESS_ALIAS);\n // Keep the cache honest for the next reader (and for anything that reads the\n // file directly) when the proxy came back in a different mode.\n if (url !== cached) await writeFile(HUB_PORTLESS_FILE, url, 'utf8').catch(() => {});\n return url;\n}\n\n/**\n * Register (or tear down) the hub's `agentbox.localhost` Portless alias and\n * return its resolved URL. Best-effort and never throws — a Portless failure\n * just leaves the hub on its loopback URL, exactly like the box path.\n *\n * Registers whenever Portless is installed and the engine isn't OrbStack, unless\n * `enabled === false` (explicit opt-out). `undefined` (never prompted) still\n * registers — the hub URL is a pure host-side convenience.\n *\n * Registering the route and *advertising* the URL are two different things. The\n * route is written whenever Portless is installed, proxy or no proxy: it costs\n * nothing and makes the URL work the moment a proxy comes up. The URL is only\n * returned when a proxy is actually live — otherwise `portless get` answers\n * from the persisted registry and the hub would print an address (`agentbox\n * .localhost:1355`) that nothing is listening on, which is precisely what a\n * reboot leaves behind.\n */\nasync function syncHubPortless(\n enabled: boolean | undefined,\n port: number,\n): Promise<string | undefined> {\n const teardown = async (): Promise<undefined> => {\n await portlessUnalias(HUB_PORTLESS_ALIAS).catch(() => {});\n await unlink(HUB_PORTLESS_FILE).catch(() => {});\n return undefined;\n };\n try {\n if (enabled === false) return await teardown();\n // The hub is a host process, so OrbStack's container-only .orb.local can't\n // reach it — and OrbStack users typically run no Portless proxy. Skip.\n if ((await detectEngine()) === 'orbstack') return await teardown();\n const portless = await detectPortless();\n if (!portless.installed) return await teardown();\n await portlessAlias(HUB_PORTLESS_ALIAS, port);\n const url = await portlessGetUrl(HUB_PORTLESS_ALIAS);\n // The file records that the hub *wants* a Portless URL (it is how a later\n // `hub status` knows the alias is ours rather than opted out); whether that\n // URL is usable is re-decided on every read against a live proxy.\n await mkdir(dirname(HUB_PORTLESS_FILE), { recursive: true });\n await writeFile(HUB_PORTLESS_FILE, url, 'utf8');\n return portless.proxyRunning ? url : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Best-effort teardown of the hub's Portless alias + its cached URL file. */\nasync function unregisterHubPortless(): Promise<void> {\n await portlessUnalias(HUB_PORTLESS_ALIAS).catch(() => {});\n await unlink(HUB_PORTLESS_FILE).catch(() => {});\n}\n\n/** The hooks the CLI installs into `@agentbox/sandbox-core`'s hub seam. */\nexport const dockerHubPortlessHooks: HubPortlessHooks = {\n sync: syncHubPortless,\n current: currentHubPortlessUrl,\n teardown: unregisterHubPortless,\n};\n","/**\n * The docker-side refresh the cloud create path calls through the\n * `@agentbox/sandbox-core` `credential-refresh.ts` seam: extract the freshest\n * agent tokens from the live docker shared credential volumes into the host\n * backups (`~/.agentbox/{claude,codex,opencode}-credentials.json`) before a\n * cloud create seeds a box from them.\n *\n * Why it exists: `agentbox create --provider <cloud>` reads the host backups to\n * seed cloud boxes, but only the docker create path keeps them current\n * (`syncClaudeCredentials` runs at `create.ts`). Without this refresh, cloud\n * creates push whatever access token the docker volume last extracted — often\n * expired by the time the user actually attaches → in-box `claude` says \"401\n * Invalid authentication credentials\" even though the box's `.credentials.json`\n * is present.\n *\n * The CLI installs this into the seam at startup; a docker-free host never does,\n * so the cloud seed there just uses the existing backup. Best-effort: every\n * helper swallows its own failures (no docker, missing volume) and returns a\n * noop result.\n *\n * Registry-driven. It used to name three agents in sequence — a claude sync\n * gated on claude's access-token expiry, then a codex extract, then an opencode\n * extract — so a fourth agent got no refresh at all and nothing said so. Each\n * agent now supplies its own step through `AgentSyncModule.refreshHostBackup`,\n * including the expiry gate that is claude's own business (skipping the ~1-2s\n * `docker run` when the token is still fresh).\n */\nimport type { DockerCredentialRefresher } from '@agentbox/sandbox-core';\nimport { registeredAgentSyncModules } from './sync/agents/module.js';\nimport { DEFAULT_BOX_IMAGE } from './image.js';\n\nexport const dockerCredentialRefresh: DockerCredentialRefresher = async (opts) => {\n const log = opts.onLog ?? (() => {});\n const image = DEFAULT_BOX_IMAGE;\n // Every registered agent, not three by name. Each decides for itself whether\n // there is anything to do — claude gates on its own token expiry, codex and\n // opencode are extract-only — and an agent that registers no module (or no\n // `refreshHostBackup`) is simply skipped rather than silently mishandled.\n for (const mod of registeredAgentSyncModules()) {\n try {\n await mod.refreshHostBackup?.(image, log);\n } catch {\n /* best-effort: one agent's refresh must never block another's, or a box start */\n }\n }\n};\n","// The agent contract this package RECEIVES rather than imports. See\n// `sync/agents/module.ts` for why the direction is inverted.\nexport {\n agentSyncModule,\n registerAgentSyncModule,\n registeredAgentSyncModules,\n requireAgentSyncModule,\n type AgentMountResult,\n type AgentSessionInfo,\n type AgentSyncModule,\n type AgentVolumeChoice,\n type EnsureAgentVolumeResult,\n} from './sync/agents/module.js';\n\n// Box plumbing shared by every agent (and by `agentbox shell`, which has no\n// agent at all) — deliberately not sourced from any one agent's module.\nexport {\n buildShellArgv,\n buildTermSafeTmuxExec,\n buildTmuxConfigShellSnippet,\n buildTmuxSessionArgs,\n CONTAINER_USER,\n TERM_FALLBACK_SNIPPET,\n} from './sync/agents/shared.js';\n\nexport { dockerProvider, type DockerCreateOptions } from './docker-provider.js';\nexport { providerModule, dockerChecks } from './provider-module.js';\nexport { downloadFromBox, uploadToBox, type BoxCpResult } from './box-cp.js';\nexport {\n createDockerSyncTransport,\n createDockerVolumeSyncTransport,\n type DockerSyncTransportInit,\n type DockerVolumeSyncTransportInit,\n} from './sync/sync-transport.js';\nexport { stageItemsFromVolume, volumeSettingsTarget } from './sync/settings-propagate.js';\nexport { makeDockerSync, type DockerSyncHandle } from './sync/docker-sync.js';\n\nexport {\n CREDENTIALS_BACKUP_FILE,\n CODEX_CREDENTIALS_BACKUP_FILE,\n OPENCODE_CREDENTIALS_BACKUP_FILE,\n hostBackupHasCredentials,\n isRealAgentCredential,\n parseSyncResult,\n parseExtractResult,\n parseVolumeClaudeCredentials,\n volumeClaudeCredentials,\n syncClaudeCredentials,\n extractVolumeAuthToBackup,\n extractCodexCredentials,\n extractOpencodeCredentials,\n type CredentialAgentKind,\n type CredentialSyncDirection,\n type SyncClaudeCredentialsResult,\n type VolumeClaudeCredentials,\n} from './sync/claude-credentials.js';\nexport {\n buildAgentsMounts,\n ensureAgentsVolume,\n resolveAgentsVolume,\n SHARED_AGENTS_VOLUME,\n type AgentsConfigSpec,\n type AgentsMountResult,\n type EnsureAgentsVolumeOptions,\n type EnsureAgentsVolumeResult,\n} from './sync/agents/skills.js';\nexport { createBox, type CreateBoxOptions, type CreatedBox } from './create.js';\nexport {\n agentboxHomeBytes,\n allCheckpointImagesBytes,\n boxResourceStats,\n parseDockerSize,\n projectCheckpointImageBytes,\n volumeSizeBytes,\n} from './stats.js';\nexport { getBoxEndpoints, type BoxEndpoint, type BoxEndpoints } from './endpoints.js';\nexport { execInBox, removeImage, type DockerExecResult } from './docker.js';\nexport {\n detectGitRepos,\n GitWorktreeError,\n pickFreshBranch,\n type DetectedGitRepo,\n} from './git-worktree.js';\nexport {\n bindWorktrees,\n collectRepoCarryOver,\n gitWorktreePathFor,\n removeInBoxWorktree,\n seedWorkspace,\n seedWorkspaceFromDir,\n WORKTREE_ROOT,\n type RepoCarryOver,\n type SeedWorkspaceOptions,\n type WorktreeBindSpec,\n} from './sync/in-box-git.js';\nexport {\n DEFAULT_BOX_IMAGE,\n BOX_IMAGE_REGISTRY,\n // The staged build context (Dockerfile.box + the COPY tree). The remote-docker\n // provider tars this and streams it to a remote `docker build -` on a registry\n // miss, so it needs the same context the local build uses.\n BUILD_CONTEXT_DIR,\n DOCKERFILE_PATH,\n registryRefForSha,\n ensureImage,\n buildDerivedAgentImage,\n variantImageRef,\n classifyDockerBaseFreshness,\n evaluateDockerBaseFreshness,\n type DockerBaseFreshness,\n pullOrBuild,\n pullImage,\n tagImage,\n imageExists,\n imageInfo,\n type ImageInfo,\n type EnsureImageOptions,\n type PullOrBuildOptions,\n} from './image.js';\nexport {\n computeDockerContextFingerprint,\n currentDockerBaseFileHashes,\n preparedMatches,\n readPreparedDockerState,\n resolveContextFiles,\n writePreparedDockerState,\n type PreparedDockerState,\n type ResolvedFingerprint,\n} from './prepared-state.js';\nexport { ensureVolume, volumeExists } from './docker.js';\nexport {\n clearRelayNotice,\n DEFAULT_RELAY_PORT,\n ensureRelay,\n forgetBoxFromRelay,\n generateRelayToken,\n getRelayStatus,\n mintHostInitiatedToken,\n registerBoxWithRelay,\n rehydrateRelayRegistry,\n relayEndpoint,\n relayPort,\n resolveRelayBin,\n RELAY_CONTAINER_NAME,\n RELAY_IMAGE_REF,\n RELAY_NETWORK_NAME,\n setRelayNotice,\n stopBoxPollerOnRelay,\n stopRelay,\n type EnsureRelayOptions,\n type RegisterBoxArgs,\n type RelayEndpoint,\n type RelayStatus,\n type StopRelayResult,\n} from './relay.js';\n// The hub lifecycle (ensureHub/getHubStatus/stopHub/resolveHubServer + types)\n// moved to `@agentbox/sandbox-core` (Step 12) so a docker-free host can start /\n// probe the hub without importing docker machinery. Consumers import them from\n// there now. This package only supplies the docker-side Portless hooks the CLI\n// installs into the hub seam.\nexport { dockerHubPortlessHooks } from './hub-portless.js';\nexport { skipWebProxyAlias } from './direct-web-url.js';\nexport { dockerCredentialRefresh } from './credential-refresh.js';\n// The host-config stage producers now live in the provider-neutral sync layer\n// (`@agentbox/sandbox-core`); cloud consumers import them from there. The claude\n// per-project path helpers + Stage types stay re-exported here (from core) for\n// existing `@agentbox/sandbox-docker` importers.\nexport {\n encodeClaudeProjectsKey,\n resolveClaudeMemoryDir,\n BOX_CLAUDE_PROJECT_DIR,\n type StageResult,\n} from '@agentbox/sandbox-core';\nexport {\n BOX_WORKFLOWS_DIR,\n BOX_MEMORY_DIR,\n BOX_DYNAMIC_SYNC_MANIFEST,\n buildHostSyncManifest,\n computeSyncDelta,\n stageDynamicSyncTarball,\n type DynamicSyncManifest,\n type DynamicSyncSet,\n type DynamicSyncSetName,\n type DynamicSyncDelta,\n type DynamicSyncUpload,\n type DynamicSyncDeletion,\n type HostSyncManifest,\n type StagedTarball,\n} from './sync/dynamic-sync.js';\nexport { EXCLUDE_DIRS, SNAPSHOTS_ROOT, snapshotPathFor } from './snapshot.js';\nexport {\n CHECKPOINTS_ROOT,\n CHECKPOINT_IMAGE_PREFIX,\n CheckpointError,\n checkpointImageTag,\n computeNextCheckpointName,\n createCheckpoint,\n listAllCheckpointImages,\n listAllCheckpoints,\n listCheckpoints,\n projectCheckpointsDir,\n removeCheckpoint,\n resolveCheckpoint,\n type CheckpointInfo,\n type CheckpointProjectGroup,\n type CheckpointManifest,\n type CheckpointType,\n type CreateCheckpointOptions,\n} from './checkpoint.js';\nexport {\n STATE_DIR,\n STATE_FILE,\n allocateProjectIndex,\n autoPickProjectBox,\n findBox,\n readState,\n recordBox,\n recordLastAgent,\n removeBoxRecord,\n resolveBoxRef,\n type BoxRecord,\n type FindBoxResult,\n type GitWorktreeRecord,\n type StateFile,\n} from './state.js';\nexport {\n attachedContainerUri,\n buildFlavorMounts,\n buildIdeMounts,\n buildVscodeMounts,\n cursorServerVolumeName,\n ensureAgentboxTasksFile,\n ensureIdeVolumes,\n ensureVscodeVolumes,\n ideProfile,\n IDE_FLAVORS,\n ideServerVolumeName,\n repairIdeOwnership,\n repairVscodeServerOwnership,\n SHARED_CURSOR_EXTENSIONS_VOLUME,\n SHARED_VSCODE_EXTENSIONS_VOLUME,\n vscodeServerVolumeName,\n type EnsureTasksFileResult,\n type IdeFlavor,\n type IdeMounts,\n type ServiceTailHint,\n type VscodeMounts,\n} from './vscode.js';\nexport {\n BOXES_ROOT,\n boxRunDirFor,\n boxStatusPathFor,\n readBoxStatus,\n buildHostEnvFindArgs,\n CONTAINER_EXPORT_MERGED,\n copyHostEnvFilesToBox,\n copyHostFilesToBox,\n orbstackVolumePath,\n DEFAULT_ENV_PATTERNS,\n carrySourceHash,\n copyCarryPathsToBox,\n detectEngine,\n getDockerContext,\n ExportError,\n getHostPaths,\n openInFinder,\n pullToHost,\n refreshExport,\n scanHostEnvFiles,\n setEngineOverride,\n type CopyCarryOptions,\n type CopyCarryResult,\n type DockerEngine,\n type HostPaths,\n type CopyHostEnvOptions,\n type CopyHostFilesOptions,\n type OpenOptions,\n type OpenResult,\n type PullOptions,\n type PullResult,\n type RefreshOptions,\n type RefreshResult,\n} from './sync/host-export.js';\nexport {\n detectPortless,\n ensurePortlessProxy,\n installPortless,\n installPortlessService,\n installPortlessServiceDetailed,\n serviceLogShowsConflict,\n portlessBrowserEnv,\n portlessAlias,\n portlessUnalias,\n portlessGetUrl,\n portlessInstallHint,\n portlessServiceHint,\n portlessServiceStatus,\n portlessStartHint,\n portlessDoctorRow,\n PORTLESS_PROXY_PORT,\n resetPortlessCache,\n resolvePortlessHostStateDir,\n startPortlessProxy,\n startPortlessProxyRoot,\n uninstallPortlessService,\n type PortlessBrowserEnvOptions,\n type PortlessServiceState,\n type PortlessState,\n type RootProxyStartResult,\n} from './portless.js';\nexport {\n AmbiguousBoxError,\n BoxNotFoundError,\n destroyBox,\n getBoxHostPaths,\n inspectBox,\n listBoxes,\n openBoxInFinder,\n pauseBox,\n pruneBoxes,\n refreshBoxSshd,\n resyncBox,\n snapshotPresent,\n startBox,\n stopBox,\n unpauseBox,\n type DestroyOptions,\n type DestroyResult,\n type InspectedBox,\n type ListedBox,\n type OpenedBox,\n type PruneOptions,\n type PruneResult,\n type StartedBox,\n} from './lifecycle.js';\nexport {\n buildVncUrls,\n generateVncPassword,\n launchVncDaemon,\n resolveVncViewerUrl,\n VNC_CONTAINER_PORT,\n type VncLaunchResult,\n type VncUrls,\n type VncViewerOptions,\n} from './vnc.js';\nexport {\n installAuthorizedKey,\n launchSshdDaemon,\n setUpBoxSshd,\n SSH_CONTAINER_PORT,\n type BoxSshSetup,\n type SshLaunchResult,\n} from './ssh.js';\nexport {\n browserSessionActive,\n desktopOpenCommand,\n ensureBoxBrowser,\n ensureBoxBrowserShowingApp,\n type BoxBrowserAppResult,\n type BoxBrowserResult,\n} from './browser.js';\nexport {\n allocateShellSessionName,\n buildShellSessionAttachArgv,\n DEFAULT_SHELL_SESSION,\n isShellSessionName,\n killShellSession,\n listShellSessions,\n parseShellSessionList,\n SHELL_SESSION_PREFIX,\n shellLabel,\n shellSessionInfo,\n shellSessionName,\n startShellSession,\n type ShellSessionInfo,\n type ShellSessionSummary,\n type StartShellSessionOptions,\n} from './shell-session.js';\nexport {\n dockerVolumeName,\n launchDockerdDaemon,\n SHARED_DOCKER_CACHE_VOLUME,\n type DockerdLaunchResult,\n} from './dockerd.js';\n\n// The new `dockerProvider` (implementing the provider-neutral `Provider`\n// interface from @agentbox/core) is exported from ./docker-provider.js at the\n// top of this file. The CLI resolves it via apps/cli/src/provider/registry.ts.\n\n// Pull-failure classification + the gh-token GHCR login used to retry a\n// throttled pull instead of silently rebuilding the base locally.\nexport {\n classifyPullFailure,\n isAuthRetryable,\n isGhcrTarget,\n loginToGhcrWithGh,\n GHCR_HOST,\n type PullFailure,\n type PullFailureKind,\n type GhcrLoginResult,\n} from './registry-auth.js';\n\nexport { seedAgentDeclaredFiles, seedLabels } from './sync/agents/seed.js';\n","/**\n * Incremental host -> box seed of Claude Code's *dynamic* config (global\n * `~/.claude/workflows/` scripts + the current project's `memory/` tree).\n *\n * The logic moved to the shared sync layer (`@agentbox/sandbox-core`'s\n * `sync/concerns/dynamic`) so the cloud `seedDynamicConfig` reuses it without\n * importing this package — the dependency leak the sync refactor closes. This\n * module re-exports it verbatim so existing `@agentbox/sandbox-docker` import\n * sites (the docker index, the dynamic-sync test) keep working.\n */\n\nexport {\n BOX_WORKFLOWS_DIR,\n BOX_DYNAMIC_SYNC_MANIFEST,\n BOX_MEMORY_DIR,\n buildHostSyncManifest,\n computeSyncDelta,\n stageDynamicSyncTarball,\n type DynamicSyncSetName,\n type DynamicSyncSet,\n type DynamicSyncManifest,\n type HostSyncManifest,\n type DynamicSyncUpload,\n type DynamicSyncDeletion,\n type DynamicSyncDelta,\n type StagedTarball,\n} from '@agentbox/sandbox-core';\n","import type { BoxRecord, Provider } from '@agentbox/core';\nimport { withServiceSignIn } from '@agentbox/sandbox-core';\nimport { execInBox } from './docker.js';\nimport { readBoxStatus } from './sync/host-export.js';\n\nexport interface BoxBrowserResult {\n up: boolean;\n /** True when a session was already active, so we left the agent's browser untouched. */\n alreadyRunning?: boolean;\n reason?: string;\n}\n\n/**\n * Decide whether `agent-browser session list` reports a live session. Pure so\n * it can be unit-tested without docker. `agent-browser` exits 0 and prints\n * \"No active sessions\" when nothing is running; any other exit-0 output lists\n * one or more sessions (a persistent Chromium is up).\n */\nexport function browserSessionActive(stdout: string, exitCode: number): boolean {\n return exitCode === 0 && !/no active sessions/i.test(stdout);\n}\n\n/**\n * Ensure the box's in-box browser (agent-browser's persistent default-session\n * Chromium) is running, so the VNC view shows a browser instead of a blank X\n * screen. Idempotent: if a session is already active we do nothing — the agent\n * may be mid-task and we must not navigate its page away. Otherwise we open\n * `targetUrl` (default `about:blank`) **headed** (agent-browser defaults to\n * headless — a headless Chromium renders nothing on the VNC display, defeating\n * the whole point), so the agent's subsequent `agent-browser open <url>` reuses\n * the same visible window (it just navigates it). `agentbox screen` passes the\n * box's own web-service URL (`http://localhost:<expose.port>`) so the app is\n * shown *inside* the VNC desktop rather than popped open on the host.\n *\n * Best-effort, mirroring {@link import('./vnc.js').launchVncDaemon} — the\n * caller warns on failure but never aborts (the noVNC client still connects).\n * On the launcher path (see {@link desktopOpenCommand}) `up` means the launch\n * is under way, not that a page is on screen yet: the browser appears on the\n * desktop behind the launcher's own progress window, which is also where a\n * failed launch reports itself.\n * `DISPLAY=:1` + `AGENT_BROWSER_EXECUTABLE_PATH` are image-baked env so the\n * exec inherits them; runs as `vscode` like the other in-box launches.\n *\n * When `targetUrl` is the box's Portless `<name>.localhost` URL, the in-box\n * browser (Google Chrome on x86_64, Playwright's Chromium on arm64 — both via\n * chromium-resolver) routes it back out to the host Portless proxy — the box's\n * `AGENT_BROWSER_ARGS` env (set at create, see `portlessBrowserEnv`) carries\n * the `--host-resolver-rules` that makes that work.\n */\n/** Local helper — sandbox-cloud's `quoteShellArg` would be a cross-package import. */\nfunction shellQuote(arg: string): string {\n return `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * Path of the in-box browser launcher that `agentbox-vnc-start` writes on every\n * VNC start (it wraps `agent-browser open` in an xterm progress window, which\n * doubles as the desktop dock's loading indicator while the first launch\n * downloads Chromium). `$HOME` is expanded in the box: the box user's home\n * differs per base image.\n */\nconst DESKTOP_LAUNCHER = '\"$HOME/.local/share/agentbox/desktop/open-browser\"';\n\n/**\n * The shell command that opens the box's browser at `target`, preferring the\n * desktop launcher.\n *\n * The launcher branch is backgrounded on purpose: it lives as long as the\n * launch does (its progress window is the whole point), and an arm64 box's\n * first launch — a ~150MB Playwright Chromium download; x86_64 boxes exec the\n * baked Google Chrome — outruns any exec timeout the caller would be willing\n * to wait on. It reports its own failures on the desktop, in\n * the window that showed the progress.\n *\n * The fallback branch (a box whose VNC never started, or an image baked before\n * the launcher existed) stays in the foreground, so its exit code still reaches\n * the caller the way it always did.\n */\nexport function desktopOpenCommand(target: string): string {\n const url = shellQuote(target);\n return (\n `if [ -x ${DESKTOP_LAUNCHER} ]; then nohup ${DESKTOP_LAUNCHER} ${url} >/dev/null 2>&1 & exit 0; fi; ` +\n `exec agent-browser open --headed ${url}`\n );\n}\n\nexport async function ensureBoxBrowser(\n container: string,\n timeoutMs = 8000,\n targetUrl = 'about:blank',\n): Promise<BoxBrowserResult> {\n const list = await execInBox(container, ['agent-browser', 'session', 'list'], {\n user: 'vscode',\n timeoutMs,\n });\n if (browserSessionActive(list.stdout, list.exitCode)) {\n return { up: true, alreadyRunning: true };\n }\n\n const open = await execInBox(container, ['bash', '-lc', desktopOpenCommand(targetUrl)], {\n user: 'vscode',\n timeoutMs,\n });\n if (open.exitCode === 0) return { up: true };\n return {\n up: false,\n reason: `agent-browser open failed: ${open.stderr || open.stdout || `exit ${String(open.exitCode)}`}`,\n };\n}\n\nexport interface BoxBrowserAppResult extends BoxBrowserResult {\n /** URL the in-box browser was pointed at (`about:blank` when no web service). */\n target: string;\n}\n\n/**\n * {@link ensureBoxBrowser} with the target derived from the box itself: the\n * box's exposed web service (Portless URL preferred, in-box loopback port as\n * fallback), or `about:blank` when nothing is exposed. This is the whole\n * \"the VNC desktop shows the app, not a blank X screen\" step — shared by\n * `agentbox screen`, the dashboard, and the hub's open-VNC action so every\n * surface that opens the VNC viewer gets a populated desktop.\n */\nexport async function ensureBoxBrowserShowingApp(\n box: BoxRecord & { portlessUrl?: string },\n provider?: Provider,\n): Promise<BoxBrowserAppResult> {\n const persisted = await readBoxStatus(box);\n const exposePort = persisted?.services.find((s) => s.expose)?.expose?.port;\n const base =\n exposePort !== undefined\n ? (box.portlessUrl ?? `http://localhost:${String(exposePort)}`)\n : 'about:blank';\n // A service agent's UI wants its token in the fragment, and the in-box\n // browser is as much a client of that as the host's is. Needs the provider to\n // read the token out of the box, so a caller that has none still gets the old\n // bare URL rather than an error.\n const target =\n provider && base !== 'about:blank' ? await withServiceSignIn(provider, box, base) : base;\n const res = await ensureBoxBrowser(box.container, undefined, target);\n return { ...res, target };\n}\n","import {\n type AgentActivityState,\n type AgentPlanPayload,\n type AgentQuestionPayload,\n type AgentStatusEntry,\n type AgentStatusMap,\n type AgentId,\n} from '@agentbox/core';\n\nexport type ServiceState =\n | 'pending'\n | 'waiting'\n | 'starting'\n | 'running'\n | 'ready'\n | 'unhealthy'\n | 'crashed'\n | 'backoff'\n | 'stopped';\n\nexport type TaskState = 'pending' | 'waiting' | 'running' | 'done' | 'failed' | 'skipped';\n\nexport interface ServiceStatus {\n name: string;\n state: ServiceState;\n pid: number | null;\n restarts: number;\n lastExitCode: number | null;\n startedAt: string | null;\n readyAt: string | null;\n nextRetryAt: string | null;\n blockedOn: string[];\n command: string;\n /**\n * Whether this service declares a `ready_when` probe. Same meaning — and the\n * same reason for existing — as {@link BoxStatusServiceEntry.probed}: a probed\n * service enters `running` the moment its process is spawned and only reaches\n * `ready` once the probe passes, so `running` does NOT mean \"up\" for it.\n *\n * The persisted snapshot has carried this for a while; the LIVE reply did not,\n * which let a host-side waiter accept a probed `running` service and report a\n * launch that had not happened yet.\n */\n probed: boolean;\n}\n\nexport interface StatusReply {\n services: ServiceStatus[];\n tasks: TaskStatus[];\n ports: BoxStatusPort[];\n}\n\nexport interface WaitReadyArgs {\n timeoutMs?: number;\n units?: string[];\n}\n\nexport type WaitReadyReply =\n | { ready: true }\n | { ready: false; timedOut: string[]; failed: string[] };\n\nexport interface TaskStatus {\n name: string;\n state: TaskState;\n pid: number | null;\n lastExitCode: number | null;\n startedAt: string | null;\n finishedAt: string | null;\n command: string;\n}\n\nexport interface LogEvent {\n service: string;\n ts: string;\n stream: 'stdout' | 'stderr';\n line: string;\n}\n\nexport interface ReloadResult {\n added: string[];\n removed: string[];\n changed: string[];\n}\n\n/**\n * The per-agent activity contract now lives in `@agentbox/core` — the leaf both\n * this daemon and the host relay can reach (ctl depends on relay, never the\n * reverse). ctl re-exports it so its own importers (the CLI, sandbox-docker,\n * the hub) resolve it from one place.\n *\n * These were also re-exported under claude-shaped aliases — `ClaudeActivityState`,\n * `ClaudePlanPayload`, `ClaudeQuestionPayload`, `BoxStatusClaude/Codex/Opencode`,\n * `CLAUDE_ACTIVITY_STATES`. None was ever claude-specific (codex and opencode\n * shared every state), so they are deleted rather than deprecated.\n */\nexport type {\n AgentActivityState,\n AgentPlanPayload,\n AgentQuestionPayload,\n AgentStatusEntry,\n AgentStatusMap,\n} from '@agentbox/core';\nexport { AGENT_ACTIVITY_STATES } from '@agentbox/core';\n\nexport interface BoxStatusServiceEntry {\n name: string;\n state: ServiceState;\n /** Configured `ready_when` port for this service, else null. */\n port: number | null;\n /**\n * Whether the service declares a `ready_when` probe (port OR log_match). A\n * probed service stays in `running` until its probe passes and only then\n * becomes `ready`, so `running` does NOT mean \"up\" for it — readers should\n * treat a probed `running` service as still warming up. Additive field:\n * absent (older snapshots) means treat as unprobed (i.e. `running` is up).\n */\n probed?: boolean;\n /**\n * The service's `expose:` mapping (container `as` → in-box `port`) when it is\n * the designated web service, else absent. Additive field — snapshots written\n * before this existed simply lack it (schema stays 1; treat absent as none).\n */\n expose?: { port: number; as: number };\n}\n\nexport interface BoxStatusTaskEntry {\n name: string;\n state: TaskState;\n}\n\nexport interface BoxStatusWebProxy {\n /** Container port the forwarder listens on (80, or 8080 on a cloud box). */\n port: number;\n /** In-box service port it forwards to, or null when nothing is exposed. */\n target: number | null;\n /** Message from the last failed bind; absent when the listener is healthy. */\n error?: string;\n}\n\nexport interface BoxStatusPort {\n port: number;\n /** Name of the service whose `ready_when` port matches, else null (ad-hoc). */\n service: string | null;\n}\n\n/**\n * Durable snapshot of a box's runtime status. The in-box daemon builds it and\n * pushes it to the host relay, which persists it to\n * `~/.agentbox/boxes/<id>/status.json` so `agentbox status` / `list` /\n * `inspect` can show it even when the box is paused or stopped.\n */\nexport interface BoxStatus {\n /** Schema version; bump on incompatible changes so old readers can reject. */\n schema: 1;\n boxId: string;\n /** ISO-8601 time the daemon built this snapshot. */\n timestamp: string;\n services: BoxStatusServiceEntry[];\n tasks: BoxStatusTaskEntry[];\n /** Live-discovered listening TCP ports inside the box. */\n ports: BoxStatusPort[];\n /**\n * The in-box web forwarder: the container port it listens on, the exposed\n * service port it forwards to, and the message from a bind that failed.\n *\n * Present so a broken publish is VISIBLE. The forwarder is best-effort by\n * design and a failed bind only reached a log file, so a box whose reserved\n * port was already taken still reported ready and still handed out a URL.\n * Additive field (schema stays 1): absent from snapshots written before it,\n * and from any box whose ctl predates it — treat absent as \"no information\",\n * never as \"healthy\".\n */\n webProxy?: BoxStatusWebProxy;\n /**\n * Every reporting agent, keyed by id. THE source of agent status — the named\n * fields below are a derived mirror of it.\n *\n * Additive (schema stays 1): a snapshot from a box baked before this field\n * existed simply lacks it, and `normalizeAgentStatus` reconstructs the map\n * from the named fields instead. Readers should go through that helper rather\n * than touching either shape directly.\n */\n agents?: AgentStatusMap;\n /**\n * The frozen legacy names, written as a MIRROR of `agents` so a host or hub\n * older than this build keeps reading activity. Skew runs both ways — a baked\n * ctl outlives the host that reads it, and a laptop CLI can be newer than a\n * control box's hub — and these drive decisions (the queue's working gate,\n * autopause, keepalive), not just display.\n *\n * Derived, never hand-maintained. A fourth agent appears only in `agents`,\n * which is correct: an old reader has no field for it either way.\n */\n claude?: AgentStatusEntry;\n codex?: AgentStatusEntry;\n opencode?: AgentStatusEntry;\n}\n\nexport const BOX_STATUS_SCHEMA = 1 as const;\n\n/** Relay event type carrying a `BoxStatus` payload. */\nexport const BOX_STATUS_EVENT = 'box-status';\n\n/**\n * Relay event type carrying a refreshed agent credential blob (the\n * credentials watcher's payload). The host relay mirrors this constant\n * (`packages/relay/src/server.ts`, like `box-status`) — it special-cases the\n * type so the secret payload never lands in the event ring buffer.\n */\nexport const CREDENTIALS_UPDATED_EVENT = 'credentials-updated';\n\nexport type CtlRequest =\n | { op: 'status' }\n | { op: 'task-status' }\n | { op: 'wait-ready'; timeoutMs?: number; units?: string[] }\n | { op: 'run-task'; name: string; force?: boolean }\n | { op: 'logs'; service: string; tail?: number; follow?: boolean }\n | { op: 'restart'; service: string }\n | { op: 'stop'; service: string }\n | { op: 'start'; service: string }\n | { op: 'reload' }\n | { op: 'ping' }\n | { op: 'agent-session'; sessionName?: string }\n | {\n /**\n * One op for every agent. The three `<agent>-state` CLI commands all send\n * this — the socket is intra-box (a short-lived `agentbox-ctl` process\n * talking to the daemon from the SAME binary), so the wire never spans two\n * builds and needs no per-agent spellings. The CLI command names are the\n * surface that does span builds; see `bin.ts`.\n */\n op: 'agent-state';\n agent: AgentId;\n state: AgentActivityState;\n /**\n * Optional payload from a pre-tool hook. For `end-plan` carries the plan\n * body; for `question` carries the question params. Cleared when the\n * matching post-tool hook fires with `state: 'working'` and\n * `clearPending: true`.\n */\n plan?: AgentPlanPayload;\n question?: AgentQuestionPayload;\n /**\n * Set by the matching post-tool hook (`--clear-pending`) to force-exit a\n * sticky end-plan/question state. The catchall pre-tool `working` hook\n * races with the matcher-specific `end-plan`/`question` hook on the same\n * tool invocation; sticky semantics in the reporter swallow that race, and\n * `clearPending` marks the legitimate post-tool transition out.\n */\n clearPending?: boolean;\n };\n\nexport type CtlResponse = { ok: true; data: unknown } | { ok: false; error: string };\n\n/**\n * Status of an in-container tmux session running an agent. The daemon doesn't\n * own the session lifecycle — it probes via `tmux has-session` and\n * `tmux display-message`. Missing tmux server / missing session both surface\n * as `running: false`.\n */\nexport interface AgentSessionStatus {\n running: boolean;\n sessionName: string;\n /** ISO-8601 timestamp from tmux's `#{session_created}`, or null when not running. */\n startedAt: string | null;\n /**\n * Sanitized tmux `#{pane_title}` (the title the agent set on its terminal),\n * or null when not running / no meaningful title.\n */\n title: string | null;\n}\n\nexport const DEFAULT_SOCKET_PATH = '/run/agentbox/ctl.sock';\nexport const DEFAULT_CONFIG_PATH = '/workspace/agentbox.yaml';\nexport const DEFAULT_LOG_DIR = '/var/log/agentbox';\n// Where run_once task completion markers live. On the box rootfs (survives\n// pause/stop/start and is captured by `docker commit` checkpoints) but NOT under\n// /workspace, so markers never show up as untracked git changes.\nexport const DEFAULT_STATE_DIR = '/var/lib/agentbox';\n// A per-agent constant table used to live here, one `DEFAULT_<AGENT>_SESSION_NAME`\n// each, feeding `BAKED_AGENT_SESSIONS`. The session name IS the agent id for\n// every agent the registry ships, so the table said nothing the id did not — and\n// ctl must not carry a per-agent table anyway: it is baked into the box image and\n// learns its agents from the host over `agents.list`.\n","import { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { createConnection, type Socket } from 'node:net';\nimport type { AgentId } from '@agentbox/core';\nimport type {\n AgentActivityState,\n AgentPlanPayload,\n AgentQuestionPayload,\n AgentSessionStatus,\n CtlRequest,\n CtlResponse,\n LogEvent,\n ReloadResult,\n ServiceStatus,\n StatusReply,\n TaskStatus,\n WaitReadyArgs,\n WaitReadyReply,\n} from './types.js';\n\nexport interface ConnectOptions {\n socketPath: string;\n /** Default 3000 ms. */\n timeoutMs?: number;\n}\n\ninterface NodeErrno extends Error {\n code?: string;\n}\n\n/**\n * Best-effort daemon respawn when the unix socket is dead. `docker exec -d`\n * leaves no log when the daemon crashes on startup and Node doesn't unlink\n * unix sockets on exit, so an orphaned file is the symptom we see most often.\n * Spawning the bin detached and polling for a fresh listener recovers without\n * needing host involvement — mirrors `ensureRelay()` on the host side.\n *\n * Gated on `AGENTBOX=1` (set on every box at `docker run`) so unit tests on\n * the host — which start an ephemeral server with no `agentbox-ctl` bin\n * anywhere on PATH — don't accidentally spawn anything.\n */\nasync function tryReviveDaemon(socketPath: string): Promise<boolean> {\n if (process.env.AGENTBOX !== '1') return false;\n try {\n const child = spawn('agentbox-ctl', ['daemon'], {\n detached: true,\n stdio: 'ignore',\n });\n child.unref();\n } catch {\n return false;\n }\n // The daemon `unlink`s any stale socket file before `listen()`, so once the\n // file reappears it's bound to a live listener.\n for (let i = 0; i < 50; i++) {\n await new Promise((r) => setTimeout(r, 100));\n if (existsSync(socketPath)) return true;\n }\n return false;\n}\n\nasync function connectOnce(opts: ConnectOptions): Promise<Socket> {\n const sock = createConnection(opts.socketPath);\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n sock.destroy();\n reject(new Error(`connect ${opts.socketPath} timed out`));\n }, opts.timeoutMs ?? 3000);\n sock.once('connect', () => {\n clearTimeout(timer);\n resolve();\n });\n sock.once('error', (err) => {\n clearTimeout(timer);\n reject(err);\n });\n });\n return sock;\n}\n\nasync function connect(opts: ConnectOptions): Promise<Socket> {\n try {\n return await connectOnce(opts);\n } catch (err) {\n // Only ECONNREFUSED (stale socket file, no listener) and ENOENT (no file\n // at all) suggest a missing daemon. Anything else (EACCES, ETIMEDOUT, …)\n // is a real failure we shouldn't try to paper over.\n const code = (err as NodeErrno).code;\n if (code !== 'ECONNREFUSED' && code !== 'ENOENT') throw err;\n const revived = await tryReviveDaemon(opts.socketPath);\n if (!revived) throw err;\n return await connectOnce(opts);\n }\n}\n\nasync function sendOneShot<T>(opts: ConnectOptions, req: CtlRequest): Promise<T> {\n const sock = await connect(opts);\n sock.write(`${JSON.stringify(req)}\\n`);\n let buf = '';\n sock.setEncoding('utf8');\n for await (const chunk of sock) {\n buf += chunk as string;\n const idx = buf.indexOf('\\n');\n if (idx !== -1) {\n const line = buf.slice(0, idx);\n sock.end();\n return parseResponse<T>(line);\n }\n }\n // Connection closed before we got a full line.\n if (buf.length > 0) return parseResponse<T>(buf);\n throw new Error('connection closed with no response');\n}\n\nfunction parseResponse<T>(line: string): T {\n const parsed = JSON.parse(line) as CtlResponse;\n if (parsed.ok) return parsed.data as T;\n throw new Error(parsed.error);\n}\n\nexport async function ping(opts: ConnectOptions): Promise<'pong'> {\n return sendOneShot<'pong'>(opts, { op: 'ping' });\n}\n\nexport async function status(opts: ConnectOptions): Promise<StatusReply> {\n return sendOneShot<StatusReply>(opts, { op: 'status' });\n}\n\nexport async function taskStatus(opts: ConnectOptions): Promise<TaskStatus[]> {\n return sendOneShot<TaskStatus[]>(opts, { op: 'task-status' });\n}\n\nexport async function waitReady(\n opts: ConnectOptions,\n args: WaitReadyArgs = {},\n): Promise<WaitReadyReply> {\n return sendOneShot<WaitReadyReply>(opts, {\n op: 'wait-ready',\n timeoutMs: args.timeoutMs,\n units: args.units,\n });\n}\n\nexport async function runTask(\n opts: ConnectOptions,\n name: string,\n force?: boolean,\n): Promise<TaskStatus> {\n return sendOneShot<TaskStatus>(opts, { op: 'run-task', name, force });\n}\n\nexport async function restart(opts: ConnectOptions, service: string): Promise<ServiceStatus> {\n return sendOneShot<ServiceStatus>(opts, { op: 'restart', service });\n}\n\nexport async function stop(opts: ConnectOptions, service: string): Promise<ServiceStatus> {\n return sendOneShot<ServiceStatus>(opts, { op: 'stop', service });\n}\n\nexport async function start(opts: ConnectOptions, service: string): Promise<ServiceStatus> {\n return sendOneShot<ServiceStatus>(opts, { op: 'start', service });\n}\n\nexport async function reload(opts: ConnectOptions): Promise<ReloadResult> {\n return sendOneShot<ReloadResult>(opts, { op: 'reload' });\n}\n\nexport async function agentSession(\n opts: ConnectOptions & { sessionName?: string },\n): Promise<AgentSessionStatus> {\n return sendOneShot<AgentSessionStatus>(opts, {\n op: 'agent-session',\n sessionName: opts.sessionName,\n });\n}\n\n/**\n * Report an agent's activity to the in-box daemon.\n *\n * One function for every agent: this socket is intra-box — a short-lived\n * `agentbox-ctl` process talking to the daemon from the SAME binary — so the\n * wire never spans two builds. The per-agent surface that DOES span builds is\n * the CLI command name, kept in `bin.ts`.\n */\nexport async function agentState(\n opts: ConnectOptions,\n agent: AgentId,\n state: AgentActivityState,\n payload?: {\n plan?: AgentPlanPayload;\n question?: AgentQuestionPayload;\n clearPending?: boolean;\n },\n): Promise<'ok'> {\n return sendOneShot<'ok'>(opts, {\n op: 'agent-state',\n agent,\n state,\n ...(payload?.plan ? { plan: payload.plan } : {}),\n ...(payload?.question ? { question: payload.question } : {}),\n ...(payload?.clearPending ? { clearPending: true } : {}),\n });\n}\n\nexport interface LogsResult {\n initial: LogEvent[];\n /**\n * When `follow: true` was passed, this async iterator yields further events\n * until the caller breaks out (which closes the socket).\n */\n follow?: AsyncIterableIterator<LogEvent>;\n}\n\nexport async function logs(\n opts: ConnectOptions,\n args: { service: string; tail?: number; follow?: boolean },\n): Promise<LogsResult> {\n const sock = await connect(opts);\n sock.write(`${JSON.stringify({ op: 'logs', ...args })}\\n`);\n\n const lines = createLineIterator(sock);\n const first = await lines.next();\n if (first.done) {\n sock.end();\n throw new Error('connection closed with no response');\n }\n const parsed = JSON.parse(first.value) as CtlResponse;\n if (!parsed.ok) {\n sock.end();\n throw new Error(parsed.error);\n }\n const data = parsed.data as { events: LogEvent[]; follow: boolean };\n if (!data.follow) {\n sock.end();\n return { initial: data.events };\n }\n\n const followGen = (async function* () {\n try {\n for await (const line of lines) {\n const p = JSON.parse(line) as CtlResponse;\n if (p.ok && p.data && typeof p.data === 'object' && 'event' in p.data) {\n yield (p.data as { event: LogEvent }).event;\n }\n }\n } finally {\n sock.end();\n }\n })();\n\n return { initial: data.events, follow: followGen };\n}\n\nasync function* createLineIterator(sock: Socket): AsyncIterableIterator<string> {\n let buf = '';\n sock.setEncoding('utf8');\n for await (const chunk of sock) {\n buf += chunk as string;\n let idx = buf.indexOf('\\n');\n while (idx !== -1) {\n yield buf.slice(0, idx);\n buf = buf.slice(idx + 1);\n idx = buf.indexOf('\\n');\n }\n }\n if (buf.length > 0) yield buf;\n}\n","import type { BoxStatusPort, ServiceStatus, TaskStatus } from './types.js';\n\nexport function renderStatusTable(rows: ServiceStatus[]): string {\n if (rows.length === 0) return '(no services configured)';\n const headers = ['NAME', 'STATE', 'PID', 'RESTARTS', 'LAST EXIT', 'BLOCKED ON', 'COMMAND'];\n const data: string[][] = rows.map((r) => [\n r.name,\n r.state,\n r.pid === null ? '-' : String(r.pid),\n String(r.restarts),\n r.lastExitCode === null ? '-' : String(r.lastExitCode),\n r.blockedOn.length === 0 ? '-' : r.blockedOn.join(','),\n truncate(r.command, 40),\n ]);\n return renderTable(headers, data);\n}\n\nexport function renderTaskTable(rows: TaskStatus[]): string {\n if (rows.length === 0) return '(no tasks configured)';\n const headers = ['NAME', 'STATE', 'EXIT', 'STARTED', 'FINISHED', 'COMMAND'];\n const data: string[][] = rows.map((r) => [\n r.name,\n r.state,\n r.lastExitCode === null ? '-' : String(r.lastExitCode),\n r.startedAt ?? '-',\n r.finishedAt ?? '-',\n truncate(r.command, 40),\n ]);\n return renderTable(headers, data);\n}\n\nexport function renderPortsTable(rows: BoxStatusPort[]): string {\n if (rows.length === 0) return '(no ports listening)';\n const named = rows.filter((r) => r.service);\n const other = rows\n .filter((r) => !r.service)\n .map((r) => r.port)\n .sort((a, b) => a - b);\n const lines: string[] = [];\n if (named.length > 0) {\n lines.push(\n renderTable(\n ['PORT', 'SERVICE'],\n named.map((r) => [`:${String(r.port)}`, r.service ?? '-']),\n ),\n );\n }\n // Collapse the unattributed ports (VNC, dev-tool worker IPC, multi-port\n // services like inngest) into one line so they don't drown the real services.\n if (other.length > 0) {\n lines.push(`other (${other.length}): ${other.join(', ')}`);\n }\n return lines.join('\\n');\n}\n\nfunction renderTable(headers: string[], data: string[][]): string {\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...data.map((row) => (row[i] ?? '').length)),\n );\n const fmt = (row: string[]): string =>\n row.map((cell, i) => cell.padEnd(widths[i] ?? cell.length)).join(' ');\n return [fmt(headers), ...data.map(fmt)].join('\\n');\n}\n\nfunction truncate(s: string, n: number): string {\n if (s.length <= n) return s;\n return s.slice(0, n - 1) + '…';\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport { parseReplacements, type ReplaceRule } from './replace.js';\n\nexport type RestartPolicy = 'always' | 'on-failure' | 'never';\nexport type ProbeOnTimeout = 'kill' | 'mark_unhealthy';\n\nexport interface BackoffSpec {\n initialMs: number;\n maxMs: number;\n factor: number;\n}\n\nexport interface PortProbe {\n kind: 'port';\n port: number;\n host: string;\n intervalMs: number;\n initialDelayMs: number;\n timeoutMs: number;\n onTimeout: ProbeOnTimeout;\n}\n\nexport interface LogMatchProbe {\n kind: 'log_match';\n pattern: RegExp;\n timeoutMs: number;\n onTimeout: ProbeOnTimeout;\n}\n\nexport interface HttpProbe {\n kind: 'http';\n url: string;\n expectStatus?: number;\n intervalMs: number;\n initialDelayMs: number;\n timeoutMs: number;\n onTimeout: ProbeOnTimeout;\n}\n\nexport type ReadyProbe = PortProbe | LogMatchProbe | HttpProbe;\n\nexport interface ExposeSpec {\n /** The port this service listens on inside the box. */\n port: number;\n /** Container port forwarded to it. Only 80 is reserved/published today. */\n as: number;\n}\n\n/**\n * Declarative \"run once\" for a task. The supervisor re-runs every task from\n * `pending` on each box start; `run_once` lets it skip a task that has already\n * succeeded.\n *\n * - `{ kind: 'marker' }` (from `run_once: true`) — the supervisor stores a\n * marker keyed by a hash of the resolved command; a warm boot skips while the\n * hash matches, and editing the command re-runs.\n * - `{ kind: 'check', command }` (from `run_once: { check: ... }`) — run the\n * probe before launching; exit 0 means already satisfied (skip). No marker:\n * the probe is the source of truth (right for data that lives outside the\n * checkpointed filesystem, e.g. a containerized DB).\n */\nexport type RunOnceSpec = { kind: 'marker' } | { kind: 'check'; command: string };\n\nexport interface TaskSpec {\n name: string;\n command: string | string[];\n cwd?: string;\n env?: Record<string, string>;\n needs: string[];\n runOnce?: RunOnceSpec;\n}\n\nexport interface ServiceSpec {\n name: string;\n command: string | string[];\n cwd?: string;\n env?: Record<string, string>;\n autostart: boolean;\n restart: RestartPolicy;\n backoff: BackoffSpec;\n needs: string[];\n readyWhen?: ReadyProbe;\n /** When set, container port `expose.as` forwards to `127.0.0.1:expose.port`. */\n expose?: ExposeSpec;\n /**\n * Declarative docker sidecar. When set, `command` is synthesized into a\n * `docker start`-or-`run` shell (the in-box dockerd container is reused by\n * name across restarts). Mutually exclusive with a user `command`. The other\n * `*image*` fields below are kept for introspection; `env` is baked into the\n * container's `-e` flags and not set as the process env.\n */\n image?: string;\n /** Port publishes (\"<host>:<container>\" or \"<port>\"); image services only. */\n ports?: string[];\n /** Extra args appended after the image (shell-tokenized); image services only. */\n args?: string;\n /** Container name (default = service name); image services only. */\n containerName?: string;\n}\n\nexport interface CtlConfig {\n services: ServiceSpec[];\n tasks: TaskSpec[];\n /** Named reusable replacement rule-sets (top-level `replacements:` block). */\n replacements: Record<string, ReplaceRule[]>;\n /**\n * Non-fatal issues — today, unknown keys (skipped, not applied). The daemon\n * logs these at startup and keeps running; `agentbox-ctl validate` prints them.\n * Empty on a clean parse.\n */\n warnings: string[];\n}\n\nexport const DEFAULT_BACKOFF: BackoffSpec = {\n initialMs: 500,\n maxMs: 30_000,\n factor: 2,\n};\n\nexport const DEFAULT_PROBE_INTERVAL_MS = 500;\nexport const DEFAULT_PROBE_INITIAL_DELAY_MS = 0;\nexport const DEFAULT_PROBE_TIMEOUT_MS = 60_000;\nexport const DEFAULT_PROBE_HOST = '127.0.0.1';\nexport const DEFAULT_PROBE_ON_TIMEOUT: ProbeOnTimeout = 'kill';\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigError';\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction parseEnv(raw: unknown, where: string): Record<string, string> | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where}.env must be a mapping of string → string`);\n }\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(raw)) {\n if (typeof v !== 'string' && typeof v !== 'number' && typeof v !== 'boolean') {\n throw new ConfigError(`${where}.env.${k} must be a scalar`);\n }\n out[k] = String(v);\n }\n return out;\n}\n\nfunction parseCommand(raw: unknown, where: string): string | string[] {\n if (typeof raw === 'string') {\n if (raw.trim().length === 0) {\n throw new ConfigError(`${where}.command must not be empty`);\n }\n return raw;\n }\n if (Array.isArray(raw)) {\n if (raw.length === 0) {\n throw new ConfigError(`${where}.command array must not be empty`);\n }\n const argv: string[] = [];\n for (const [i, item] of raw.entries()) {\n if (typeof item !== 'string') {\n throw new ConfigError(`${where}.command[${String(i)}] must be a string`);\n }\n argv.push(item);\n }\n return argv;\n }\n throw new ConfigError(`${where}.command must be a string or array of strings`);\n}\n\nfunction parseRestart(raw: unknown, where: string): RestartPolicy {\n if (raw === undefined) return 'on-failure';\n if (raw === 'always' || raw === 'on-failure' || raw === 'never') return raw;\n throw new ConfigError(`${where}.restart must be one of: always, on-failure, never`);\n}\n\nconst BACKOFF_KEYS = new Set(['initial_ms', 'max_ms', 'factor']);\n\nfunction parseBackoff(raw: unknown, where: string): BackoffSpec {\n if (raw === undefined) return { ...DEFAULT_BACKOFF };\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where}.backoff must be a mapping`);\n }\n warnUnknownKeys(raw, BACKOFF_KEYS, `${where}.backoff`);\n const initialMs = parseNonNegativeInt(\n raw.initial_ms,\n `${where}.backoff.initial_ms`,\n DEFAULT_BACKOFF.initialMs,\n );\n const maxMs = parseNonNegativeInt(raw.max_ms, `${where}.backoff.max_ms`, DEFAULT_BACKOFF.maxMs);\n const factor = parseFactor(raw.factor, `${where}.backoff.factor`, DEFAULT_BACKOFF.factor);\n if (maxMs < initialMs) {\n throw new ConfigError(`${where}.backoff.max_ms must be >= initial_ms`);\n }\n return { initialMs, maxMs, factor };\n}\n\n/**\n * Unknown keys are collected, not fatal. This parser ships INSIDE the box image\n * (`agentbox-ctl`), so a box baked from an older image reads an `agentbox.yaml`\n * written against a newer CLI. Throwing there would mean every key we add to the\n * schema bricks every existing box image. The key is skipped and reported;\n * everything else (wrong types, bad DAG, unknown `needs:` target) still throws.\n *\n * Module-scoped because the 8 call sites sit in nested parse helpers.\n * `parseConfig` is the single synchronous entry point and resets it on entry.\n */\nlet unknownKeyWarnings: string[] = [];\n\nfunction warnUnknownKeys(obj: Record<string, unknown>, allowed: Set<string>, where: string): void {\n for (const key of Object.keys(obj)) {\n if (!allowed.has(key)) {\n unknownKeyWarnings.push(\n `${where} has unknown key \"${key}\" — ignored (typo, or written by a newer agentbox)`,\n );\n }\n }\n}\n\nfunction parseNonNegativeInt(raw: unknown, where: string, fallback: number): number {\n if (raw === undefined) return fallback;\n if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 0) {\n throw new ConfigError(`${where} must be a non-negative number`);\n }\n return Math.floor(raw);\n}\n\nfunction parsePositiveInt(raw: unknown, where: string, fallback: number): number {\n if (raw === undefined) return fallback;\n if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 1) {\n throw new ConfigError(`${where} must be a positive integer`);\n }\n return Math.floor(raw);\n}\n\nfunction parseFactor(raw: unknown, where: string, fallback: number): number {\n if (raw === undefined) return fallback;\n if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 1) {\n throw new ConfigError(`${where} must be a number >= 1`);\n }\n return raw;\n}\n\nfunction parseOnTimeout(raw: unknown, where: string): ProbeOnTimeout {\n if (raw === undefined) return DEFAULT_PROBE_ON_TIMEOUT;\n if (raw === 'kill' || raw === 'mark_unhealthy') return raw;\n throw new ConfigError(`${where} must be one of: kill, mark_unhealthy`);\n}\n\nfunction parseNeeds(raw: unknown, where: string): string[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) {\n throw new ConfigError(`${where} must be an array of unit names`);\n }\n const seen = new Set<string>();\n const out: string[] = [];\n for (const [i, item] of raw.entries()) {\n if (typeof item !== 'string') {\n throw new ConfigError(`${where}[${String(i)}] must be a string`);\n }\n if (!/^[A-Za-z0-9_-]+$/.test(item)) {\n throw new ConfigError(`${where}[${String(i)}] \"${item}\" must match [A-Za-z0-9_-]+`);\n }\n if (seen.has(item)) continue;\n seen.add(item);\n out.push(item);\n }\n return out;\n}\n\nconst PROBE_KEYS = new Set([\n 'port',\n 'host',\n 'log_match',\n 'http',\n 'expect_status',\n 'interval_ms',\n 'initial_delay_ms',\n 'timeout_ms',\n 'on_timeout',\n]);\n\nfunction parseReadyWhen(raw: unknown, where: string): ReadyProbe | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where}.ready_when must be a mapping`);\n }\n warnUnknownKeys(raw, PROBE_KEYS, `${where}.ready_when`);\n\n const kinds: Array<'port' | 'log_match' | 'http'> = [];\n if (raw.port !== undefined) kinds.push('port');\n if (raw.log_match !== undefined) kinds.push('log_match');\n if (raw.http !== undefined) kinds.push('http');\n if (kinds.length === 0) {\n throw new ConfigError(`${where}.ready_when must declare exactly one of: port, log_match, http`);\n }\n if (kinds.length > 1) {\n throw new ConfigError(\n `${where}.ready_when may declare only one of: port, log_match, http (got ${kinds.join(', ')})`,\n );\n }\n\n const timeoutMs = parsePositiveInt(\n raw.timeout_ms,\n `${where}.ready_when.timeout_ms`,\n DEFAULT_PROBE_TIMEOUT_MS,\n );\n const onTimeout = parseOnTimeout(raw.on_timeout, `${where}.ready_when.on_timeout`);\n\n const kind = kinds[0]!;\n if (kind === 'log_match') {\n if (\n raw.host !== undefined ||\n raw.expect_status !== undefined ||\n raw.interval_ms !== undefined ||\n raw.initial_delay_ms !== undefined\n ) {\n throw new ConfigError(\n `${where}.ready_when.log_match cannot be combined with host/expect_status/interval_ms/initial_delay_ms`,\n );\n }\n const pat = assertString(raw.log_match, `${where}.ready_when.log_match`);\n let pattern: RegExp;\n try {\n pattern = new RegExp(pat);\n } catch (err) {\n throw new ConfigError(\n `${where}.ready_when.log_match is not a valid regex: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return { kind: 'log_match', pattern, timeoutMs, onTimeout };\n }\n\n const intervalMs = parsePositiveInt(\n raw.interval_ms,\n `${where}.ready_when.interval_ms`,\n DEFAULT_PROBE_INTERVAL_MS,\n );\n const initialDelayMs = parseNonNegativeInt(\n raw.initial_delay_ms,\n `${where}.ready_when.initial_delay_ms`,\n DEFAULT_PROBE_INITIAL_DELAY_MS,\n );\n\n if (kind === 'port') {\n if (raw.expect_status !== undefined) {\n throw new ConfigError(`${where}.ready_when.expect_status only applies to http probes`);\n }\n const port = parsePositiveInt(raw.port, `${where}.ready_when.port`, 0);\n if (port < 1 || port > 65535) {\n throw new ConfigError(`${where}.ready_when.port must be between 1 and 65535`);\n }\n const host =\n raw.host === undefined\n ? DEFAULT_PROBE_HOST\n : assertString(raw.host, `${where}.ready_when.host`);\n return { kind: 'port', port, host, intervalMs, initialDelayMs, timeoutMs, onTimeout };\n }\n\n if (raw.host !== undefined) {\n throw new ConfigError(`${where}.ready_when.host only applies to port probes`);\n }\n const url = assertString(raw.http, `${where}.ready_when.http`);\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new ConfigError(`${where}.ready_when.http must be a valid URL`);\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new ConfigError(`${where}.ready_when.http must use http(s):// (got ${parsed.protocol})`);\n }\n let expectStatus: number | undefined;\n if (raw.expect_status !== undefined) {\n expectStatus = parsePositiveInt(raw.expect_status, `${where}.ready_when.expect_status`, 0);\n if (expectStatus < 100 || expectStatus > 599) {\n throw new ConfigError(`${where}.ready_when.expect_status must be between 100 and 599`);\n }\n }\n return { kind: 'http', url, expectStatus, intervalMs, initialDelayMs, timeoutMs, onTimeout };\n}\n\n/**\n * The only container port AgentBox reserves + publishes for a web service today\n * (see `WEB_CONTAINER_PORT` host-side in @agentbox/sandbox-docker). A service's\n * `expose.as` must equal this — any other value would parse fine but be\n * unreachable from the host, so we reject it loudly.\n */\nexport const RESERVED_WEB_PORT = 80;\n\nconst SERVICE_KEYS = new Set([\n 'command',\n 'cwd',\n 'env',\n 'autostart',\n 'restart',\n 'backoff',\n 'needs',\n 'ready_when',\n 'expose',\n 'ide',\n 'image',\n]);\n\n// The container config nested under a service's `image:` (when it's a mapping).\nconst IMAGE_KEYS = new Set(['name', 'ports', 'env', 'args', 'container_name']);\n\n// Minimal POSIX single-quote escaping for values baked into a generated\n// `bash -c` docker command. (sandbox-cloud has an equivalent quoteShellArg, but\n// ctl can't depend on it — wrong direction.)\nfunction shQuote(s: string): string {\n if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(s)) return s;\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\nfunction parsePorts(raw: unknown, where: string): string[] | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!Array.isArray(raw)) {\n throw new ConfigError(`${where}.ports must be a list of \"<host>:<container>\" strings`);\n }\n const out: string[] = [];\n for (const [i, v] of raw.entries()) {\n const s = typeof v === 'number' ? String(v) : v;\n if (typeof s !== 'string' || !/^\\d+(:\\d+)?$/.test(s.trim())) {\n throw new ConfigError(\n `${where}.ports[${String(i)}] must be \"<host>\" or \"<host>:<container>\" (got ${JSON.stringify(v)})`,\n );\n }\n out.push(s.trim());\n }\n return out.length > 0 ? out : undefined;\n}\n\n// `args` is a string (appended raw, bash word-splits) or a list of strings\n// (joined with spaces, then bash word-splits) — so both `args: \"-c x=1\"` and\n// `args: [\"-c\", \"x=1\"]` produce the same docker invocation.\nfunction parseArgs(raw: unknown, where: string): string | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (typeof raw === 'string') return raw.trim().length > 0 ? raw : undefined;\n if (Array.isArray(raw)) {\n const parts: string[] = [];\n for (const [i, v] of raw.entries()) {\n if (typeof v !== 'string')\n throw new ConfigError(`${where}.args[${String(i)}] must be a string`);\n parts.push(v);\n }\n const joined = parts.join(' ').trim();\n return joined.length > 0 ? joined : undefined;\n }\n throw new ConfigError(`${where}.args must be a string or a list of strings`);\n}\n\n// Build the start-or-run shell for an `image:` service. Reuses the existing\n// container by name across restarts (data lives in the per-box /var/lib/docker);\n// a config change needs a manual `docker rm <name>`.\nfunction synthesizeImageCommand(opts: {\n image: string;\n name: string;\n ports?: string[];\n env?: Record<string, string>;\n args?: string;\n}): string {\n const name = shQuote(opts.name);\n const run = ['docker', 'run', '--name', name];\n for (const p of opts.ports ?? []) run.push('-p', shQuote(p));\n for (const [k, v] of Object.entries(opts.env ?? {})) run.push('-e', `${k}=${shQuote(v)}`);\n run.push(shQuote(opts.image));\n let runLine = run.join(' ');\n if (opts.args) runLine += ` ${opts.args}`; // raw — bash word-splits\n return [\n 'set -e',\n `if docker container inspect ${name} >/dev/null 2>&1; then`,\n ` docker start ${name} >/dev/null`,\n ` exec docker logs -f ${name}`,\n 'else',\n ` exec ${runLine}`,\n 'fi',\n ].join('\\n');\n}\n\ninterface ParsedImage {\n name: string;\n ports?: string[];\n env?: Record<string, string>;\n args?: string;\n containerName: string;\n}\n\n// Parse a service's `image:` — either a bare ref string (shorthand) or a mapping\n// `{ name, ports?, env?, args?, container_name? }`. `defaultName` (the service\n// name) is the default container name.\nfunction parseImage(raw: unknown, where: string, defaultName: string): ParsedImage {\n if (typeof raw === 'string') {\n const name = raw.trim();\n if (name.length === 0) throw new ConfigError(`${where}.image must not be empty`);\n return { name, containerName: defaultName };\n }\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where}.image must be an image ref string or a mapping`);\n }\n warnUnknownKeys(raw, IMAGE_KEYS, `${where}.image`);\n const name = assertString(raw.name, `${where}.image.name`).trim();\n if (name.length === 0) throw new ConfigError(`${where}.image.name must not be empty`);\n const ports = parsePorts(raw.ports, `${where}.image`);\n const args = parseArgs(raw.args, `${where}.image`);\n const env = parseEnv(raw.env, `${where}.image`);\n const containerName =\n raw.container_name === undefined\n ? defaultName\n : assertString(raw.container_name, `${where}.image.container_name`).trim();\n if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(containerName)) {\n throw new ConfigError(\n `${where}.image.container_name \"${containerName}\" is not a valid docker container name`,\n );\n }\n const out: ParsedImage = { name, containerName };\n if (ports !== undefined) out.ports = ports;\n if (env !== undefined) out.env = env;\n if (args !== undefined) out.args = args;\n return out;\n}\n\nconst EXPOSE_KEYS = new Set(['port', 'as']);\n\nfunction parseExpose(raw: unknown, where: string): ExposeSpec | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where}.expose must be a mapping`);\n }\n warnUnknownKeys(raw, EXPOSE_KEYS, `${where}.expose`);\n if (raw.port === undefined) {\n throw new ConfigError(`${where}.expose.port is required`);\n }\n const port = parsePortNumber(raw.port, `${where}.expose.port`);\n const as =\n raw.as === undefined ? RESERVED_WEB_PORT : parsePortNumber(raw.as, `${where}.expose.as`);\n if (as !== RESERVED_WEB_PORT) {\n throw new ConfigError(\n `${where}.expose.as must be ${String(RESERVED_WEB_PORT)} (the only container port AgentBox publishes)`,\n );\n }\n return { port, as };\n}\n\nfunction parsePortNumber(raw: unknown, where: string): number {\n if (typeof raw !== 'number' || !Number.isInteger(raw) || raw < 1 || raw > 65535) {\n throw new ConfigError(`${where} must be an integer between 1 and 65535`);\n }\n return raw;\n}\n\nfunction parseService(name: string, raw: unknown): ServiceSpec {\n const where = `services.${name}`;\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where} must be a mapping`);\n }\n warnUnknownKeys(raw, SERVICE_KEYS, where);\n\n const hasImage = raw.image !== undefined && raw.image !== null;\n const hasCommand = raw.command !== undefined && raw.command !== null;\n if (hasImage && hasCommand) {\n throw new ConfigError(`${where} sets both command and image — use exactly one`);\n }\n if (!hasImage && !hasCommand) {\n throw new ConfigError(`${where} must set either command or image`);\n }\n\n const cwd = raw.cwd === undefined ? undefined : assertString(raw.cwd, `${where}.cwd`);\n const autostart =\n raw.autostart === undefined ? true : assertBool(raw.autostart, `${where}.autostart`);\n const restart = parseRestart(raw.restart, where);\n const backoff = parseBackoff(raw.backoff, where);\n const needs = parseNeeds(raw.needs, `${where}.needs`);\n const readyWhen = parseReadyWhen(raw.ready_when, where);\n const expose = parseExpose(raw.expose, where);\n\n if (hasImage) {\n if (raw.env !== undefined) {\n throw new ConfigError(`${where}.env is not valid for an image service — use image.env`);\n }\n const img = parseImage(raw.image, where, name);\n const command = synthesizeImageCommand({\n image: img.name,\n name: img.containerName,\n ports: img.ports,\n env: img.env,\n args: img.args,\n });\n const spec: ServiceSpec = {\n name,\n command,\n cwd,\n autostart,\n restart,\n backoff,\n needs,\n readyWhen,\n expose,\n image: img.name,\n containerName: img.containerName,\n };\n if (img.ports !== undefined) spec.ports = img.ports;\n if (img.args !== undefined) spec.args = img.args;\n return spec;\n }\n\n const command = parseCommand(raw.command, where);\n const env = parseEnv(raw.env, where);\n return { name, command, cwd, env, autostart, restart, backoff, needs, readyWhen, expose };\n}\n\nconst TASK_KEYS = new Set(['command', 'cwd', 'env', 'needs', 'run_once']);\n\nfunction parseRunOnce(raw: unknown, where: string): RunOnceSpec | undefined {\n if (raw === undefined || raw === null || raw === false) return undefined;\n if (raw === true) return { kind: 'marker' };\n if (isPlainObject(raw)) {\n const keys = Object.keys(raw);\n if (keys.length !== 1 || keys[0] !== 'check') {\n throw new ConfigError(`${where}.run_once object form must be exactly { check: <command> }`);\n }\n const check = raw.check;\n if (typeof check !== 'string' || check.trim().length === 0) {\n throw new ConfigError(`${where}.run_once.check must be a non-empty command string`);\n }\n return { kind: 'check', command: check };\n }\n throw new ConfigError(`${where}.run_once must be true or { check: <command> }`);\n}\n\nfunction parseTask(name: string, raw: unknown): TaskSpec {\n const where = `tasks.${name}`;\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where} must be a mapping`);\n }\n warnUnknownKeys(raw, TASK_KEYS, where);\n const command = parseCommand(raw.command, where);\n const cwd = raw.cwd === undefined ? undefined : assertString(raw.cwd, `${where}.cwd`);\n const env = parseEnv(raw.env, where);\n const needs = parseNeeds(raw.needs, `${where}.needs`);\n const runOnce = parseRunOnce(raw.run_once, where);\n const spec: TaskSpec = { name, command, cwd, env, needs };\n if (runOnce !== undefined) spec.runOnce = runOnce;\n return spec;\n}\n\nfunction assertString(raw: unknown, where: string): string {\n if (typeof raw !== 'string') throw new ConfigError(`${where} must be a string`);\n return raw;\n}\n\nfunction assertBool(raw: unknown, where: string): boolean {\n if (typeof raw !== 'boolean') throw new ConfigError(`${where} must be a boolean`);\n return raw;\n}\n\n// `defaults` is the host-side config layer (read by @agentbox/config) — the\n// supervisor doesn't touch it, but we accept it here so `ctl validate` doesn't\n// flag it as unknown. Strict typo-detection still applies (top-level keys\n// outside this set are rejected).\n// `carry` is the host-side declarative file-carry block (read by the apps/cli\n// layer via @agentbox/ctl/carry, applied at create time). The supervisor never\n// reads it — listing it here only suppresses the unknown-key error so a project\n// yaml that declares `carry:` still parses cleanly inside the box.\n// `replacements` is the top-level reusable replacement-rule block, consumed by\n// the in-box `agentbox-ctl render` CLI and host-side `carry:` rule refs. We\n// parse + validate it here (regex compile-check) so a typo fails loud in-box.\n// `tools` is the host-side host-tool REQUEST block (read by the apps/cli layer\n// via @agentbox/ctl/tools-spec, approved at create time). Same deal as `carry`:\n// the supervisor never reads it, listing it here only keeps a project yaml that\n// declares `tools:` parsing cleanly inside the box.\n// A service agent's `configRender.overlayKey` is a legitimate top-level key too,\n// but WHICH key that is only exists on the host's agent registry — so it arrives\n// over `agents.list` and is passed in as `extraTopLevelKeys` rather than being\n// hardcoded here. Unknown keys are non-fatal warnings, so a ctl that never got\n// the descriptor still parses the file; it just says so.\nconst TOP_LEVEL_KEYS = new Set([\n 'services',\n 'tasks',\n 'ide',\n 'defaults',\n 'carry',\n 'replacements',\n 'tools',\n]);\n\n/** Options both parsers take. */\nexport interface ParseConfigOptions {\n /**\n * Extra legal top-level keys, from the agent descriptors (`overlayKey`).\n * Their CONTENTS are never validated here — the agent's own `validate`\n * command is the real gate, and ctl does not know the tool's schema.\n */\n extraTopLevelKeys?: readonly string[];\n}\n\n/**\n * Exported so the agent-unit merge can validate the COMBINED graph before\n * handing it to the supervisor — units synthesized from `agents.list` join the\n * same namespace as the workspace's, and a dangling `needs:` there would block a\n * unit forever instead of failing loudly.\n */\nexport function validateUnitGraph(tasks: TaskSpec[], services: ServiceSpec[]): void {\n const names = new Set<string>();\n for (const t of tasks) {\n if (names.has(t.name)) {\n throw new ConfigError(\n `unit name \"${t.name}\" declared more than once (task vs service collision)`,\n );\n }\n names.add(t.name);\n }\n for (const s of services) {\n if (names.has(s.name)) {\n throw new ConfigError(\n `unit name \"${s.name}\" declared more than once (task vs service collision)`,\n );\n }\n names.add(s.name);\n }\n\n const deps = new Map<string, string[]>();\n for (const t of tasks) deps.set(t.name, t.needs);\n for (const s of services) deps.set(s.name, s.needs);\n\n for (const [unit, list] of deps) {\n for (const dep of list) {\n if (!names.has(dep)) {\n throw new ConfigError(`unit \"${unit}\" needs unknown unit \"${dep}\"`);\n }\n if (dep === unit) {\n throw new ConfigError(`unit \"${unit}\" cannot depend on itself`);\n }\n }\n }\n\n // DFS with three-color marking; record the cycle path in the error.\n const WHITE = 0,\n GRAY = 1,\n BLACK = 2;\n const color = new Map<string, number>();\n for (const name of deps.keys()) color.set(name, WHITE);\n const stack: string[] = [];\n\n function visit(name: string): void {\n color.set(name, GRAY);\n stack.push(name);\n for (const dep of deps.get(name)!) {\n const c = color.get(dep) ?? WHITE;\n if (c === GRAY) {\n const startIdx = stack.indexOf(dep);\n const cycle = stack.slice(startIdx).concat(dep).join(' → ');\n throw new ConfigError(`cyclic dependency: ${cycle}`);\n }\n if (c === WHITE) visit(dep);\n }\n stack.pop();\n color.set(name, BLACK);\n }\n\n for (const name of deps.keys()) {\n if (color.get(name) === WHITE) visit(name);\n }\n}\n\nexport function parseConfig(text: string, opts: ParseConfigOptions = {}): CtlConfig {\n unknownKeyWarnings = [];\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch (err) {\n throw new ConfigError(`yaml parse error: ${err instanceof Error ? err.message : String(err)}`);\n }\n if (doc === null || doc === undefined) {\n return { services: [], tasks: [], replacements: {}, warnings: [] };\n }\n if (!isPlainObject(doc)) {\n throw new ConfigError('top-level config must be a mapping');\n }\n const topLevel =\n opts.extraTopLevelKeys && opts.extraTopLevelKeys.length > 0\n ? new Set([...TOP_LEVEL_KEYS, ...opts.extraTopLevelKeys])\n : TOP_LEVEL_KEYS;\n warnUnknownKeys(doc, topLevel, '(root)');\n\n const services: ServiceSpec[] = [];\n const servicesRaw = doc.services;\n if (servicesRaw !== undefined && servicesRaw !== null) {\n if (!isPlainObject(servicesRaw)) {\n throw new ConfigError('services must be a mapping of name → service');\n }\n for (const [name, raw] of Object.entries(servicesRaw)) {\n if (!/^[A-Za-z0-9_-]+$/.test(name)) {\n throw new ConfigError(`service name \"${name}\" must match [A-Za-z0-9_-]+`);\n }\n services.push(parseService(name, raw));\n }\n }\n\n const tasks: TaskSpec[] = [];\n const tasksRaw = doc.tasks;\n if (tasksRaw !== undefined && tasksRaw !== null) {\n if (!isPlainObject(tasksRaw)) {\n throw new ConfigError('tasks must be a mapping of name → task');\n }\n for (const [name, raw] of Object.entries(tasksRaw)) {\n if (!/^[A-Za-z0-9_-]+$/.test(name)) {\n throw new ConfigError(`task name \"${name}\" must match [A-Za-z0-9_-]+`);\n }\n tasks.push(parseTask(name, raw));\n }\n }\n\n // ide: parsed only enough to confirm it's an object; contents are host-side\n // and the supervisor doesn't touch them. Schema is permissive here too.\n if (doc.ide !== undefined && doc.ide !== null && !isPlainObject(doc.ide)) {\n throw new ConfigError('ide must be a mapping');\n }\n\n // defaults: host-side layered-config block. We only require it to be a\n // mapping here; @agentbox/config validates the leaves strictly when the\n // host loads the file. Letting ctl deep-validate would force a circular\n // dependency on the host-only @agentbox/config package — see CLAUDE.md.\n if (doc.defaults !== undefined && doc.defaults !== null && !isPlainObject(doc.defaults)) {\n throw new ConfigError('defaults must be a mapping');\n }\n\n validateUnitGraph(tasks, services);\n\n const exposed = services.filter((s) => s.expose);\n if (exposed.length > 1) {\n throw new ConfigError(\n `at most one service may set expose: (got: ${exposed.map((s) => s.name).join(', ')})`,\n );\n }\n\n let replacements: Record<string, ReplaceRule[]>;\n try {\n replacements = parseReplacements(doc.replacements);\n } catch (err) {\n throw new ConfigError(err instanceof Error ? err.message : String(err));\n }\n\n return { services, tasks, replacements, warnings: unknownKeyWarnings };\n}\n\nexport async function loadConfig(path: string, opts: ParseConfigOptions = {}): Promise<CtlConfig> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { services: [], tasks: [], replacements: {}, warnings: [] };\n }\n throw err;\n }\n return parseConfig(text, opts);\n}\n\nexport function describeCommand(cmd: string | string[]): string {\n return Array.isArray(cmd) ? cmd.join(' ') : cmd;\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml, parseDocument } from 'yaml';\nimport { parseReplacements, ReplaceError, type ReplaceRule } from '@agentbox/core';\n\n// Re-export the pure engine (defined in @agentbox/core so the host carry path\n// can share it without a dependency cycle) so in-box code keeps importing from\n// a single `./replace.js` surface.\nexport {\n applyReplacements,\n substitutePlaceholders,\n placeholderContextFromEnv,\n parseReplaceRule,\n parseReplaceRules,\n parseReplacements,\n resolveRuleRefs,\n parseRuleArg,\n PLACEHOLDER_KEYS,\n ReplaceError,\n} from '@agentbox/core';\nexport type { ReplaceRule, ApplyReplacementsOptions, PlaceholderKey } from '@agentbox/core';\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** Parse the top-level `replacements:` block out of raw agentbox.yaml text. */\nexport function parseReplacementsSection(text: string): Record<string, ReplaceRule[]> {\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch (err) {\n throw new ReplaceError(`yaml parse error: ${err instanceof Error ? err.message : String(err)}`);\n }\n if (doc === null || doc === undefined) return {};\n if (!isPlainObject(doc)) throw new ReplaceError('top-level config must be a mapping');\n return parseReplacements(doc.replacements);\n}\n\n/** Load the `replacements:` block from an agentbox.yaml path (missing → {}). */\nexport async function loadReplacementsSection(\n path: string,\n): Promise<Record<string, ReplaceRule[]>> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw err;\n }\n return parseReplacementsSection(text);\n}\n\n/**\n * Remove one named rule-set from an `agentbox.yaml` document, and any comment\n * line carrying `sentinel`.\n *\n * Exists for `agentbox clone`. A bot's `identity` rules name the SOURCE bot\n * (\"rewrite Ada to this box's name\"), so copying them into a clone leaves rules\n * that match a name the clone's own files no longer contain — the NEXT clone\n * then rewrites nothing and keeps introducing itself as its grandparent. The\n * sentinel goes with them, because it is what stops the box facts nudging the\n * new bot to write rules of its own.\n *\n * Document surgery rather than a re-serialize: `agentbox.yaml` is the user's\n * file, and a clone has no business reformatting the rest of it or dropping\n * their comments. Returns the text unchanged when there is nothing to remove.\n */\nexport function removeReplacementsSet(text: string, name: string, sentinel?: string): string {\n let out = text;\n let doc;\n try {\n doc = parseDocument(text);\n } catch {\n return text; // not our file to fix\n }\n // `parseDocument` does NOT throw on malformed yaml -- it collects errors and\n // then refuses to stringify, which would take a clone down over a file the\n // user broke. Leave theirs exactly as it is.\n if (doc.errors.length > 0) return text;\n if (doc.hasIn(['replacements', name])) {\n doc.deleteIn(['replacements', name]);\n const rest = doc.getIn(['replacements']);\n // An emptied `replacements:` would serialize as a null key, which the\n // parser then rejects as a malformed section.\n if (isEmptyMap(rest)) doc.delete('replacements');\n out = String(doc);\n }\n if (sentinel) {\n out = out\n .split('\\n')\n .filter((line) => !(line.trimStart().startsWith('#') && line.includes(sentinel)))\n .join('\\n');\n }\n return out;\n}\n\n/** True for a yaml map node with no entries left. */\nfunction isEmptyMap(node: unknown): boolean {\n return (\n typeof node === 'object' &&\n node !== null &&\n 'items' in node &&\n Array.isArray((node as { items: unknown[] }).items) &&\n (node as { items: unknown[] }).items.length === 0\n );\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { parse as parseYaml } from 'yaml';\nimport type { CarryItem } from '@agentbox/core';\nimport { parseReplacementsSection, parseReplaceRules, type ReplaceRule } from './replace.js';\n\n// Re-exported so `@agentbox/ctl`'s existing importers are unchanged; the type\n// itself moved to @agentbox/core because the host-side carry resolver lives in\n// @agentbox/sandbox-core, which this package cannot be imported by (ctl ->\n// relay -> sandbox-core would cycle).\nexport type { CarryItem };\n\nexport class CarryConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CarryConfigError';\n }\n}\n\nconst ITEM_KEYS = new Set([\n 'src',\n 'dest',\n 'mode',\n 'user',\n 'exclude',\n 'optional',\n 'replaceEnvs',\n 'replace',\n 'rules',\n]);\n\n// Parse a YAML field into a list of trimmed non-empty strings (undefined when\n// empty/absent). Shared by `exclude` and `rules`; `desc` names the element kind\n// in the error message.\nfunction parseStringList(raw: unknown, where: string, desc: string): string[] | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!Array.isArray(raw)) {\n throw new CarryConfigError(`${where} must be a list of ${desc}`);\n }\n const out: string[] = [];\n for (const [i, v] of raw.entries()) {\n if (typeof v !== 'string' || v.trim().length === 0) {\n throw new CarryConfigError(`${where}[${String(i)}] must be a non-empty string`);\n }\n out.push(v.trim());\n }\n return out.length > 0 ? out : undefined;\n}\n\nfunction parseUser(raw: unknown, where: string): number | undefined {\n if (raw === undefined || raw === null) return undefined;\n let n: number;\n if (typeof raw === 'number') {\n if (!Number.isInteger(raw) || raw < 0) {\n throw new CarryConfigError(\n `${where}.user must be a non-negative integer uid (got ${String(raw)})`,\n );\n }\n n = raw;\n } else if (typeof raw === 'string') {\n const trimmed = raw.trim();\n if (!/^[0-9]+$/.test(trimmed)) {\n throw new CarryConfigError(\n `${where}.user \"${raw}\" must be a numeric uid (e.g. 1000). Usernames not supported — look up the uid first.`,\n );\n }\n n = parseInt(trimmed, 10);\n } else {\n throw new CarryConfigError(`${where}.user must be a non-negative integer uid`);\n }\n if (n > 65535) {\n throw new CarryConfigError(`${where}.user must be between 0 and 65535 (got ${String(n)})`);\n }\n return n;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction assertSrcShape(src: string, where: string): void {\n if (src.length === 0) {\n throw new CarryConfigError(`${where}.src must not be empty`);\n }\n if (!src.startsWith('/') && !src.startsWith('~/') && !src.startsWith('./')) {\n throw new CarryConfigError(\n `${where}.src \"${src}\" must start with /, ~/, or ./ (bare relative paths are rejected to avoid surprises)`,\n );\n }\n}\n\nfunction assertDestShape(dest: string, where: string): void {\n if (dest.length === 0) {\n throw new CarryConfigError(`${where}.dest must not be empty`);\n }\n if (!dest.startsWith('/') && !dest.startsWith('~/')) {\n throw new CarryConfigError(\n `${where}.dest \"${dest}\" must start with / or ~/ (relative box-side paths are not allowed)`,\n );\n }\n}\n\nfunction parseMode(raw: unknown, where: string): number | undefined {\n if (raw === undefined || raw === null) return undefined;\n let n: number;\n if (typeof raw === 'number') {\n if (!Number.isInteger(raw) || raw < 0) {\n throw new CarryConfigError(\n `${where}.mode must be a non-negative integer (got ${String(raw)})`,\n );\n }\n n = raw;\n } else if (typeof raw === 'string') {\n const trimmed = raw.trim();\n if (trimmed.length === 0) {\n throw new CarryConfigError(`${where}.mode must not be empty`);\n }\n // Accept \"0600\", \"600\", \"0o600\". Always interpreted as octal.\n const cleaned =\n trimmed.startsWith('0o') || trimmed.startsWith('0O') ? trimmed.slice(2) : trimmed;\n if (!/^[0-7]+$/.test(cleaned)) {\n throw new CarryConfigError(\n `${where}.mode \"${raw}\" must be an octal number (e.g. 0o600, \"0600\", \"600\")`,\n );\n }\n n = parseInt(cleaned, 8);\n } else {\n throw new CarryConfigError(`${where}.mode must be a number or octal string`);\n }\n if (n < 0 || n > 0o7777) {\n throw new CarryConfigError(`${where}.mode must be between 0 and 0o7777 (got ${n.toString(8)})`);\n }\n return n;\n}\n\nfunction parseShorthand(raw: string, where: string): CarryItem {\n // Split on first '=', so values containing '=' survive in dest.\n const eq = raw.indexOf('=');\n let src: string;\n let dest: string;\n if (eq === -1) {\n src = raw;\n dest = raw;\n } else {\n src = raw.slice(0, eq);\n dest = raw.slice(eq + 1);\n }\n src = src.trim();\n dest = dest.trim();\n assertSrcShape(src, where);\n if (eq === -1) {\n // Shorthand without explicit dest: src must be absolute or ~/ so dest\n // can mirror it. `./relative` shorthand has no meaningful in-box dest.\n if (src.startsWith('./')) {\n throw new CarryConfigError(\n `${where} shorthand \"${raw}\" must specify an explicit dest (use \"src=dest\") when src starts with ./`,\n );\n }\n }\n assertDestShape(dest, where);\n return { src, dest, optional: false };\n}\n\nfunction parseMapping(raw: Record<string, unknown>, where: string): CarryItem {\n for (const key of Object.keys(raw)) {\n if (!ITEM_KEYS.has(key)) {\n throw new CarryConfigError(`${where} has unknown key \"${key}\"`);\n }\n }\n const srcRaw = raw.src;\n if (typeof srcRaw !== 'string') {\n throw new CarryConfigError(`${where}.src must be a string`);\n }\n const src = srcRaw.trim();\n assertSrcShape(src, where);\n\n let dest: string;\n if (raw.dest === undefined || raw.dest === null) {\n if (src.startsWith('./')) {\n throw new CarryConfigError(\n `${where}.dest is required when src starts with ./ (no sensible in-box default)`,\n );\n }\n dest = src;\n } else {\n if (typeof raw.dest !== 'string') {\n throw new CarryConfigError(`${where}.dest must be a string`);\n }\n dest = raw.dest.trim();\n }\n assertDestShape(dest, where);\n\n const mode = parseMode(raw.mode, where);\n const user = parseUser(raw.user, where);\n const exclude = parseStringList(raw.exclude, `${where}.exclude`, 'glob/name strings');\n\n let optional = false;\n if (raw.optional !== undefined && raw.optional !== null) {\n if (typeof raw.optional !== 'boolean') {\n throw new CarryConfigError(`${where}.optional must be a boolean`);\n }\n optional = raw.optional;\n }\n\n let replaceEnvs: boolean | undefined;\n if (raw.replaceEnvs !== undefined && raw.replaceEnvs !== null) {\n if (typeof raw.replaceEnvs !== 'boolean') {\n throw new CarryConfigError(`${where}.replaceEnvs must be a boolean`);\n }\n replaceEnvs = raw.replaceEnvs;\n }\n let replace: ReplaceRule[] | undefined;\n if (raw.replace !== undefined && raw.replace !== null) {\n try {\n const rules = parseReplaceRules(raw.replace, `${where}.replace`);\n if (rules.length > 0) replace = rules;\n } catch (err) {\n throw new CarryConfigError(err instanceof Error ? err.message : String(err));\n }\n }\n const rules = parseStringList(raw.rules, `${where}.rules`, 'replacements rule-set names');\n\n const out: CarryItem = { src, dest, optional };\n if (mode !== undefined) out.mode = mode;\n if (user !== undefined) out.user = user;\n if (exclude !== undefined) out.exclude = exclude;\n if (replaceEnvs !== undefined) out.replaceEnvs = replaceEnvs;\n if (replace !== undefined) out.replace = replace;\n if (rules !== undefined) out.rules = rules;\n return out;\n}\n\nexport function parseCarryRaw(raw: unknown): CarryItem[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) {\n throw new CarryConfigError('carry must be a list of strings or mappings');\n }\n const out: CarryItem[] = [];\n for (const [i, item] of raw.entries()) {\n const where = `carry[${String(i)}]`;\n if (typeof item === 'string') {\n out.push(parseShorthand(item, where));\n } else if (isPlainObject(item)) {\n out.push(parseMapping(item, where));\n } else {\n throw new CarryConfigError(`${where} must be a string or mapping`);\n }\n }\n return out;\n}\n\nexport function parseCarrySection(text: string): CarryItem[] {\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch (err) {\n throw new CarryConfigError(\n `yaml parse error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (doc === null || doc === undefined) return [];\n if (!isPlainObject(doc)) {\n throw new CarryConfigError('top-level config must be a mapping');\n }\n return parseCarryRaw(doc.carry);\n}\n\nexport async function loadCarrySection(path: string): Promise<CarryItem[]> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n return parseCarrySection(text);\n}\n\n/**\n * Both halves the carry gate needs, from one read of `<projectRoot>/agentbox.yaml`.\n *\n * The gate itself lives in `@agentbox/sandbox-core`, which cannot import this\n * package (ctl -> relay -> sandbox-core would cycle), so parsing stays here and\n * the gate takes the result. A missing file is not an error: it means no carry.\n */\nexport async function loadCarrySpec(\n projectRoot: string,\n): Promise<{ items: CarryItem[]; replacements: Record<string, ReplaceRule[]> }> {\n let text = '';\n try {\n text = await readFile(join(projectRoot, 'agentbox.yaml'), 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n return { items: parseCarrySection(text), replacements: parseReplacementsSection(text) };\n}\n","/**\n * Supervisor units synthesized from a `surface: 'service'` agent's descriptor.\n *\n * The wire block (`AgentServiceSpec`, `@agentbox/core`) mirrors ctl's own\n * `ServiceSpec`/`TaskSpec` field-for-field, so this is a FIELD COPY plus the\n * defaults ctl's yaml parser would have applied — not a translation layer. Every\n * decision it makes beyond copying is one of those defaults.\n *\n * Defensive throughout: the payload comes from a host that may be newer than\n * this baked ctl. A malformed unit is DROPPED with a warning rather than thrown,\n * because the alternative is a box whose supervisor refuses to start over an\n * agent it did not have to run at all.\n */\n\nimport {\n DEFAULT_BACKOFF,\n DEFAULT_PROBE_HOST,\n DEFAULT_PROBE_INITIAL_DELAY_MS,\n DEFAULT_PROBE_INTERVAL_MS,\n DEFAULT_PROBE_ON_TIMEOUT,\n DEFAULT_PROBE_TIMEOUT_MS,\n validateUnitGraph,\n type CtlConfig,\n type ReadyProbe,\n type RestartPolicy,\n type RunOnceSpec,\n type ServiceSpec,\n type TaskSpec,\n} from './config.js';\n\n/** The units one service agent contributes. */\nexport interface AgentUnits {\n /** The agent this came from, for warning text. */\n agent: string;\n services: ServiceSpec[];\n tasks: TaskSpec[];\n}\n\nconst UNIT_NAME_RE = /^[A-Za-z0-9_-]+$/;\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction wireCommand(raw: unknown): string | string[] | null {\n if (typeof raw === 'string' && raw.trim().length > 0) return raw;\n if (Array.isArray(raw) && raw.length > 0 && raw.every((x) => typeof x === 'string')) {\n return raw as string[];\n }\n return null;\n}\n\nfunction wireEnv(raw: unknown): Record<string, string> | undefined {\n if (!isPlainObject(raw)) return undefined;\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(raw)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean')\n out[k] = String(v);\n }\n return out;\n}\n\nfunction wireNeeds(raw: unknown): string[] {\n if (!Array.isArray(raw)) return [];\n return raw.filter((x): x is string => typeof x === 'string' && x.length > 0);\n}\n\nfunction wireRestart(raw: unknown): RestartPolicy {\n return raw === 'always' || raw === 'never' || raw === 'on-failure' ? raw : 'on-failure';\n}\n\nfunction wireRunOnce(raw: unknown): RunOnceSpec | undefined {\n if (raw === 'marker') return { kind: 'marker' };\n if (isPlainObject(raw) && typeof raw.check === 'string' && raw.check.trim().length > 0) {\n return { kind: 'check', command: raw.check };\n }\n return undefined;\n}\n\n/**\n * `readyWhen` → ctl's `ReadyProbe`, with the same defaults the yaml parser\n * applies. Precedence http > port > logMatch: the descriptor declares one, and\n * ranking them beats silently picking whichever key iteration happened to hit.\n */\nfunction wireProbe(\n raw: unknown,\n onWarn: (m: string) => void,\n where: string,\n): ReadyProbe | undefined {\n if (!isPlainObject(raw)) return undefined;\n const common = {\n intervalMs: DEFAULT_PROBE_INTERVAL_MS,\n initialDelayMs: DEFAULT_PROBE_INITIAL_DELAY_MS,\n timeoutMs: DEFAULT_PROBE_TIMEOUT_MS,\n onTimeout: DEFAULT_PROBE_ON_TIMEOUT,\n };\n if (typeof raw.http === 'string' && raw.http.length > 0) {\n return { kind: 'http', url: raw.http, ...common };\n }\n if (typeof raw.port === 'number' && Number.isInteger(raw.port)) {\n return { kind: 'port', port: raw.port, host: DEFAULT_PROBE_HOST, ...common };\n }\n if (typeof raw.logMatch === 'string' && raw.logMatch.length > 0) {\n try {\n return {\n kind: 'log_match',\n pattern: new RegExp(raw.logMatch),\n timeoutMs: common.timeoutMs,\n onTimeout: common.onTimeout,\n };\n } catch {\n onWarn(`${where}.readyWhen.logMatch is not a valid regex; ignoring the probe`);\n return undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Narrow one agent's wire `service` block into supervisor units.\n *\n * Returns null when the block is unusable — no name, no command, or a name that\n * would not have been a legal unit name in `agentbox.yaml`.\n */\nexport function agentUnitsFromWire(\n agent: string,\n raw: unknown,\n onWarn: (m: string) => void,\n): AgentUnits | null {\n if (!isPlainObject(raw)) return null;\n const where = `agents.list[${agent}].service`;\n const name = typeof raw.name === 'string' ? raw.name : '';\n if (!UNIT_NAME_RE.test(name)) {\n onWarn(`${where}.name \"${name}\" is not a valid unit name; skipping this agent's units`);\n return null;\n }\n const command = wireCommand(raw.command);\n if (!command) {\n onWarn(`${where}.command is missing or malformed; skipping this agent's units`);\n return null;\n }\n\n const tasks: TaskSpec[] = [];\n for (const t of Array.isArray(raw.tasks) ? raw.tasks : []) {\n if (!isPlainObject(t)) continue;\n const tName = typeof t.name === 'string' ? t.name : '';\n const tCommand = wireCommand(t.command);\n if (!UNIT_NAME_RE.test(tName) || !tCommand) {\n onWarn(`${where}.tasks[${tName || '?'}] is malformed; skipping it`);\n continue;\n }\n const runOnce = wireRunOnce(t.runOnce);\n const task: TaskSpec = {\n name: tName,\n command: tCommand,\n cwd: typeof t.cwd === 'string' ? t.cwd : undefined,\n env: wireEnv(t.env),\n needs: wireNeeds(t.needs),\n };\n if (runOnce) task.runOnce = runOnce;\n tasks.push(task);\n }\n\n const service: ServiceSpec = {\n name,\n command,\n cwd: typeof raw.cwd === 'string' ? raw.cwd : undefined,\n env: wireEnv(raw.env),\n autostart: true,\n restart: wireRestart(raw.restart),\n backoff: { ...DEFAULT_BACKOFF },\n needs: wireNeeds(raw.needs),\n readyWhen: wireProbe(raw.readyWhen, onWarn, where),\n };\n const expose = raw.expose;\n if (\n isPlainObject(expose) &&\n typeof expose.port === 'number' &&\n Number.isInteger(expose.port) &&\n typeof expose.as === 'number' &&\n Number.isInteger(expose.as)\n ) {\n service.expose = { port: expose.port, as: expose.as };\n }\n\n return { agent, services: [service], tasks };\n}\n\n/**\n * Fold a service agent's units into the workspace config.\n *\n * THE WORKSPACE ALWAYS WINS. A unit whose name already exists in\n * `/workspace/agentbox.yaml` is dropped here, so a user can override the\n * synthesized service (or task) simply by declaring one with the same name —\n * which is the documented escape hatch and the reason the agent's unit names are\n * part of its public surface.\n *\n * The `expose:` collision is called out rather than resolved silently: only one\n * service may publish the box's web port, so the agent's `expose` is dropped\n * with a loud warning when the workspace already claims it. A silent drop here\n * reads to the user as \"the box URL is broken for no reason\".\n *\n * Returns the base config unchanged if the merge would produce an invalid unit\n * graph — a dangling `needs:` or a cycle must not cost the box the services it\n * already had.\n */\nexport function mergeAgentUnits(\n base: CtlConfig,\n units: readonly AgentUnits[],\n onWarn: (m: string) => void,\n): CtlConfig {\n if (units.length === 0) return base;\n const taken = new Set<string>([\n ...base.services.map((s) => s.name),\n ...base.tasks.map((t) => t.name),\n ]);\n const workspaceExposes = base.services.find((s) => s.expose);\n\n const services = [...base.services];\n const tasks = [...base.tasks];\n for (const u of units) {\n for (const t of u.tasks) {\n if (taken.has(t.name)) {\n onWarn(\n `agent \"${u.agent}\": task \"${t.name}\" is declared in agentbox.yaml; the workspace wins`,\n );\n continue;\n }\n taken.add(t.name);\n tasks.push(t);\n }\n for (const s of u.services) {\n if (taken.has(s.name)) {\n onWarn(\n `agent \"${u.agent}\": service \"${s.name}\" is declared in agentbox.yaml; the workspace wins`,\n );\n continue;\n }\n taken.add(s.name);\n if (s.expose && workspaceExposes) {\n onWarn(\n `agent \"${u.agent}\": service \"${s.name}\" wants expose: but \"${workspaceExposes.name}\" in agentbox.yaml already publishes the box web port; ` +\n `the agent's expose is dropped. Remove one of the two.`,\n );\n services.push({ ...s, expose: undefined });\n continue;\n }\n services.push(s);\n }\n }\n\n const merged: CtlConfig = { ...base, services, tasks };\n try {\n validateUnitGraph(merged.tasks, merged.services);\n } catch (err) {\n onWarn(\n `agent units rejected (${err instanceof Error ? err.message : String(err)}); keeping the workspace config`,\n );\n return base;\n }\n return merged;\n}\n","/**\n * The half of `agentbox-ctl agent render <id>` that AgentBox keeps for itself:\n * WHICH overlay keys it is asserting on this run.\n *\n * The merge itself is delegated to the tool (`configRender.applyCmd`), so there\n * is deliberately no format parser and no 3-way merge engine here. What is left\n * is a diff between two overlays — the one in `agentbox.yaml` now, and the one\n * this command applied last time — and that diff is what decides whether an\n * in-box hand edit survives:\n *\n * a key the user did NOT change in agentbox.yaml is not in the patch, the\n * patch does not name it, and the tool leaves the file's value alone.\n *\n * Pure and disk-free so it can be unit-tested on values.\n */\n\nexport type JsonValue = null | boolean | number | string | JsonValue[] | { [k: string]: JsonValue };\n\nexport function isPlainObject(v: unknown): v is Record<string, JsonValue> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** Structural equality, enough for parsed JSON/YAML values. */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((x, i) => deepEqual(x, b[i]));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const ka = Object.keys(a);\n const kb = Object.keys(b);\n if (ka.length !== kb.length) return false;\n return ka.every((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));\n }\n return false;\n}\n\nexport interface OverlayPatch {\n /** The object sent to the tool's patch command on stdin. */\n patch: Record<string, JsonValue>;\n /** Dotted paths the patch touches, for the render's own output. */\n paths: string[];\n /** Dotted paths dropped from the overlay since the last apply. */\n removed: string[];\n}\n\n/**\n * Keys whose OVERLAY value changed since the last apply.\n *\n * A key the user REMOVED from `agentbox.yaml` is sent as `null`, because the\n * patch protocol reads null as \"delete this path\" and deletion is the only way\n * an overlay edit is reversible: without it, a value AgentBox once asserted\n * would be asserted forever and removing it from the yaml would do nothing. It\n * restores the tool's own default, not some AgentBox default — which is the\n * behaviour the overlay model promises.\n *\n * Arrays and scalars replace whole; only objects recurse. Element-wise merging\n * of a list whose entries have no identity produces results nobody predicts, and\n * the tool's own patch command makes the same choice.\n */\nexport function overlayPatch(previous: JsonValue | undefined, next: JsonValue): OverlayPatch {\n const paths: string[] = [];\n const removed: string[] = [];\n\n function walk(\n prev: Record<string, JsonValue> | undefined,\n cur: Record<string, JsonValue>,\n prefix: string,\n ): Record<string, JsonValue> {\n const out: Record<string, JsonValue> = {};\n const keys = new Set([...Object.keys(prev ?? {}), ...Object.keys(cur)]);\n for (const k of keys) {\n const path = prefix ? `${prefix}.${k}` : k;\n const before = prev?.[k];\n if (!Object.hasOwn(cur, k)) {\n out[k] = null;\n paths.push(path);\n removed.push(path);\n continue;\n }\n const after = cur[k] as JsonValue;\n if (before !== undefined && deepEqual(before, after)) continue;\n if (isPlainObject(before) && isPlainObject(after)) {\n const nested = walk(before, after, path);\n if (Object.keys(nested).length > 0) out[k] = nested;\n continue;\n }\n out[k] = after;\n paths.push(path);\n }\n return out;\n }\n\n const cur = isPlainObject(next) ? next : {};\n const prev = isPlainObject(previous) ? previous : undefined;\n return { patch: walk(prev, cur, ''), paths, removed };\n}\n\n/**\n * Keys and values that look like a real secret rather than a reference to one.\n *\n * A warning, never an error: the overlay is opaque to ctl, so this cannot be a\n * schema rule. But `agentbox.yaml` is a committed file, and a token pasted into\n * it is committed with it — the documented path is a `carry:` entry into a 0600\n * env file that the overlay references BY NAME.\n */\nconst SECRET_KEY_RE = /(secret|token|password|passwd|apikey|api_key|credential|private_key)/i;\n/** Long opaque strings, and the vendor prefixes that are unambiguous on sight. */\nconst SECRET_VALUE_RES = [\n /^(sk|rk|pk)-[A-Za-z0-9_-]{16,}$/,\n /^gh[pousr]_[A-Za-z0-9]{20,}$/,\n /^xox[abposr]-[A-Za-z0-9-]{10,}$/,\n /^eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\./,\n /^[A-Za-z0-9+/]{40,}={0,2}$/,\n /^[0-9a-f]{40,}$/i,\n];\n\n/** A value that names a secret instead of being one is exactly what we want. */\nfunction isReference(value: string): boolean {\n return value.includes('{{') || /^\\$\\{?[A-Za-z_][A-Za-z0-9_]*\\}?$/.test(value);\n}\n\n/**\n * Dotted paths under the overlay whose value looks like a literal secret.\n *\n * Exported for its own test: the rule is a heuristic, and a heuristic nobody can\n * see the boundaries of gets ignored the first time it cries wolf.\n */\nexport function lintOverlaySecrets(overlay: JsonValue, prefix = ''): string[] {\n const hits: string[] = [];\n if (Array.isArray(overlay)) {\n overlay.forEach((v, i) => hits.push(...lintOverlaySecrets(v, `${prefix}[${String(i)}]`)));\n return hits;\n }\n if (!isPlainObject(overlay)) return hits;\n for (const [k, v] of Object.entries(overlay)) {\n const path = prefix ? `${prefix}.${k}` : k;\n if (typeof v === 'string' && !isReference(v)) {\n const keyLooksSecret = SECRET_KEY_RE.test(k) && v.length >= 8;\n if (keyLooksSecret || SECRET_VALUE_RES.some((re) => re.test(v))) hits.push(path);\n continue;\n }\n hits.push(...lintOverlaySecrets(v, path));\n }\n return hits;\n}\n","import { request as httpRequest } from 'node:http';\nimport { request as httpsRequest } from 'node:https';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { relayEnvFilePath, resolveRelayEnv } from './relay-env.js';\n\n/**\n * Shared HTTP RPC poster for in-box ctl commands (git, checkpoint, cp,\n * download). Mirrors the wire shape of `packages/relay/src/server.ts`'s\n * `/rpc`: bearer-auth POST with `{ method, params }`, response is a\n * `{ exitCode, stdout, stderr }` JSON or an `{ error }` shape.\n *\n * Two relay shapes are supported transparently:\n * - block mode (laptop relay): the relay holds the connection while a prompt\n * is open, then returns the `{exitCode,…}` result. No client timeout.\n * - poll mode (hosted control plane): the relay replies `202 {promptId}` and\n * this client polls `GET /rpc/status/:promptId` until the host answers.\n * A box never has to know which mode it's talking to.\n */\nconst POLL_INTERVAL_MS = 1500;\nconst POLL_MAX_MS = 10 * 60 * 1000; // give a human ~10 min to answer before giving up\nexport interface RelayRpcResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface PostRpcOptions {\n /** Override label used in error prefixes (default: 'agentbox-ctl rpc'). */\n errorPrefix?: string;\n}\n\nexport interface PostRpcOutcome<TResult> {\n /** HTTP status the relay returned (0 on transport error). */\n status: number;\n /** Parsed JSON body when it matched TResult; null otherwise. */\n parsed: TResult | null;\n /** Raw response body (for diagnostics on parse failure). */\n raw: string;\n /** Internal exit code suggestion: 65 for env/URL errors, 126 for transport. */\n internalExitCode: number | null;\n}\n\n/**\n * Low-level: returns the raw outcome. Most callers want `postRpcAndExit`.\n */\ninterface RelayTarget {\n url: URL;\n token: string;\n transport: typeof httpRequest;\n port: number;\n}\n\n/** Resolve the relay endpoint from env or the 0600 relay.env file, or null (after writing the error). */\nfunction resolveRelayTarget(prefix: string): RelayTarget | null {\n const { url: urlStr, token } = resolveRelayEnv();\n if (!urlStr || !token) {\n process.stderr.write(\n `${prefix}: AGENTBOX_RELAY_URL / AGENTBOX_RELAY_TOKEN not set (and ${relayEnvFilePath()} absent); no relay configured for this box.\\n`,\n );\n return null;\n }\n let url: URL;\n try {\n url = new URL(urlStr);\n } catch {\n process.stderr.write(`${prefix}: invalid AGENTBOX_RELAY_URL: ${urlStr}\\n`);\n return null;\n }\n const isHttps = url.protocol === 'https:';\n return {\n url,\n token,\n transport: isHttps ? httpsRequest : httpRequest,\n port: url.port.length > 0 ? Number.parseInt(url.port, 10) : isHttps ? 443 : 80,\n };\n}\n\nfunction parseRpcResult(text: string): RelayRpcResult | null {\n try {\n const v = JSON.parse(text) as unknown;\n if (v && typeof v === 'object' && typeof (v as RelayRpcResult).exitCode === 'number') {\n return v as RelayRpcResult;\n }\n } catch {\n /* fall through */\n }\n return null;\n}\n\nexport function postRpc<TParams>(\n method: string,\n params: TParams,\n opts: PostRpcOptions = {},\n): Promise<PostRpcOutcome<RelayRpcResult>> {\n const prefix = opts.errorPrefix ?? 'agentbox-ctl rpc';\n const target = resolveRelayTarget(prefix);\n if (!target) return Promise.resolve({ status: 0, parsed: null, raw: '', internalExitCode: 65 });\n\n const body = JSON.stringify({ method, params });\n\n return new Promise<PostRpcOutcome<RelayRpcResult>>((resolve) => {\n const req = target.transport(\n {\n host: target.url.hostname,\n port: target.port,\n method: 'POST',\n path: `${target.url.pathname.replace(/\\/$/, '')}/rpc`,\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(body).toString(),\n Authorization: `Bearer ${target.token}`,\n },\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (c: Buffer) => chunks.push(c));\n res.on('end', () => {\n const status = res.statusCode ?? 0;\n const text = Buffer.concat(chunks).toString('utf8');\n resolve({ status, parsed: parseRpcResult(text), raw: text, internalExitCode: null });\n });\n },\n );\n req.on('error', (err) => {\n process.stderr.write(`${prefix}: ${String(err.message ?? err)}\\n`);\n resolve({ status: 0, parsed: null, raw: '', internalExitCode: 126 });\n });\n req.write(body);\n req.end();\n });\n}\n\ninterface RpcStatusReply {\n /** 'pending' while awaiting the host answer; 'done' once resolved. */\n status?: 'pending' | 'done';\n result?: RelayRpcResult;\n}\n\n/** GET /rpc/status/:promptId once. Returns null + writes the error on transport failure. */\nfunction getRpcStatus(promptId: string, prefix: string): Promise<RpcStatusReply | null> {\n const target = resolveRelayTarget(prefix);\n if (!target) return Promise.resolve(null);\n return new Promise<RpcStatusReply | null>((resolve) => {\n const req = target.transport(\n {\n host: target.url.hostname,\n port: target.port,\n method: 'GET',\n path: `${target.url.pathname.replace(/\\/$/, '')}/rpc/status/${encodeURIComponent(promptId)}`,\n headers: { Authorization: `Bearer ${target.token}` },\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (c: Buffer) => chunks.push(c));\n res.on('end', () => {\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')) as RpcStatusReply);\n } catch {\n resolve(null);\n }\n });\n },\n );\n req.on('error', () => resolve(null));\n req.end();\n });\n}\n\n/**\n * Convenience: POST + write stdout/stderr + return the exit code. Used by\n * every ctl subcommand that just forwards a relay RPC verbatim. Callers\n * `process.exit(await postRpcAndExit(...))`.\n *\n * Exit-code mapping:\n * - parsed `{exitCode}` from relay → that value (incl. 10 = denied by user)\n * - `internalExitCode` set on env/transport error → that value (65 / 126)\n * - relay returned non-2xx with no parseable body → 1\n * - relay returned 2xx with no parseable body → 0\n */\n/**\n * POST + (on a 202, poll /rpc/status) → the final `{exitCode,stdout,stderr}`,\n * WITHOUT writing stdout/stderr. Callers that just forward use\n * {@link postRpcAndExit}; callers that need to consume the result body (e.g.\n * `git.lease-token`, whose stdout is the lease JSON) use this directly.\n */\nexport async function postRpcAwait<TParams>(\n method: string,\n params: TParams,\n opts: PostRpcOptions = {},\n): Promise<RelayRpcResult> {\n const prefix = opts.errorPrefix ?? 'agentbox-ctl rpc';\n const out = await postRpc(method, params, opts);\n if (out.internalExitCode !== null) {\n // postRpc already wrote the env/transport error to stderr.\n return { exitCode: out.internalExitCode, stdout: '', stderr: '' };\n }\n if (out.status === 202) return pollParkedResult(out.raw, prefix);\n if (out.parsed) return out.parsed;\n if (out.status >= 200 && out.status < 300) return { exitCode: 0, stdout: '', stderr: '' };\n return {\n exitCode: 1,\n stdout: '',\n stderr: `${prefix}: relay returned ${String(out.status)}: ${out.raw}\\n`,\n };\n}\n\nexport async function postRpcAndExit<TParams>(\n method: string,\n params: TParams,\n opts: PostRpcOptions = {},\n): Promise<number> {\n const result = await postRpcAwait(method, params, opts);\n if (result.stdout) process.stdout.write(result.stdout);\n if (result.stderr) process.stderr.write(result.stderr);\n return result.exitCode;\n}\n\n/** Poll /rpc/status until the host answers the parked approval; return the result. */\nasync function pollParkedResult(raw202: string, prefix: string): Promise<RelayRpcResult> {\n let promptId = '';\n try {\n const v = JSON.parse(raw202) as { promptId?: unknown };\n if (typeof v.promptId === 'string') promptId = v.promptId;\n } catch {\n /* handled below */\n }\n if (!promptId) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `${prefix}: relay parked the action but returned no promptId\\n`,\n };\n }\n process.stderr.write(`${prefix}: waiting for approval on the host…\\n`);\n const deadline = Date.now() + POLL_MAX_MS;\n while (Date.now() < deadline) {\n await delay(POLL_INTERVAL_MS + Math.floor(Math.random() * 400));\n const reply = await getRpcStatus(promptId, prefix);\n if (reply && reply.status === 'done' && reply.result) {\n return reply.result;\n }\n // null (transient transport error) or pending → keep polling.\n }\n return {\n exitCode: 124,\n stdout: '',\n stderr:\n `${prefix}: timed out after 10m waiting for the host.\\n` +\n `This action runs on your PC (host relay): either your PC/relay isn't running, or a host\\n` +\n `approval prompt went unanswered. Operations like cp, download, and checkpoint need your PC\\n` +\n `on even for an independent (git.pushMode=direct) box — only git push/pull run in the box.\\n`,\n };\n}\n","import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\n/**\n * Default location of the per-box relay URL + token file. Under `/run`\n * (tmpfs): rewritten on every daemon start and never captured in a\n * checkpoint/snapshot. `0600`, owned by the daemon user.\n */\nconst DEFAULT_RELAY_ENV_FILE = '/run/agentbox/relay.env';\n\n/**\n * Resolve the relay-env file path at call time (not import time) so tests can\n * point `AGENTBOX_RELAY_ENV_FILE` at a temp file per-case.\n *\n * The file backs in-box `agentbox-ctl` invocations that don't inherit the ctl\n * daemon's process env — the interactive agent (launched via a tmux login\n * shell) and the host-driven `agentbox git push <box>`. On docker boxes the\n * relay env is global (`docker run -e`), so this file is unused; on cloud boxes\n * there's no global env, so the daemon writes it (`writeRelayEnvFile`) and the\n * readers below fall back to it.\n */\nexport function relayEnvFilePath(): string {\n return process.env.AGENTBOX_RELAY_ENV_FILE ?? DEFAULT_RELAY_ENV_FILE;\n}\n\n/**\n * Resolve the relay URL + token: prefer the process env, fall back to the\n * `0600` file the cloud daemon writes. A missing/unreadable file leaves the\n * corresponding value undefined (env-only behavior, as before).\n */\nexport function resolveRelayEnv(env: NodeJS.ProcessEnv = process.env): {\n url?: string;\n token?: string;\n} {\n let url = env.AGENTBOX_RELAY_URL;\n let token = env.AGENTBOX_RELAY_TOKEN;\n if (url && token) return { url, token };\n\n try {\n const text = readFileSync(relayEnvFilePath(), 'utf8');\n for (const line of text.split('\\n')) {\n const eq = line.indexOf('=');\n if (eq === -1) continue;\n const key = line.slice(0, eq).trim();\n const value = line.slice(eq + 1).trim();\n if (key === 'AGENTBOX_RELAY_URL') url ??= value;\n else if (key === 'AGENTBOX_RELAY_TOKEN') token ??= value;\n }\n } catch {\n // file absent/unreadable → env-only\n }\n return { url, token };\n}\n\n/**\n * Persist the relay URL + token to the relay-env file (`0600`). Called by the\n * cloud ctl daemon once it has validated its own per-box token. Deliberately\n * NOT the bridge token — that authenticates the host poller to `/bridge/*` and\n * is consumed only by the daemon's process env. Throws are the caller's to\n * swallow (a failure only costs the file fallback, not the relay).\n */\nexport function writeRelayEnvFile(url: string, token: string): void {\n const path = relayEnvFilePath();\n mkdirSync(dirname(path), { recursive: true });\n const body = `AGENTBOX_RELAY_URL=${url}\\nAGENTBOX_RELAY_TOKEN=${token}\\n`;\n writeFileSync(path, body, { mode: 0o600 });\n // mode on writeFileSync only applies when creating the file; enforce it in\n // case the file already existed with looser perms.\n chmodSync(path, 0o600);\n}\n","import { lstat, mkdir, readdir, readlink, symlink, unlink } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Materialize one `/…/bin/<tool>` symlink per granted host tool, all pointing\n * at the single baked `agentbox-tool-shim`.\n *\n * This is what makes the feature work without an image rebake: the shim is\n * baked once, and the *set* of tools is just a set of symlinks the in-box\n * daemon keeps in sync with the host's grant list. Approving a\n * `tool request` makes the command appear in a running box.\n *\n * The links land in `~/.local/bin` rather than `/usr/local/bin` for a\n * concrete reason: the ctl daemon runs as `vscode`, not root, so it cannot\n * write `/usr/local/bin`. `~/.local/bin` is vscode-owned and is already\n * FIRST on PATH on every provider (the Dockerfile `ENV PATH` and each cloud\n * provider's `/etc/profile.d/agentbox.sh` both prepend it), so a link there\n * wins resolution against anything in `/usr/bin`.\n */\n\n/** Where the baked multi-call shim lives in every image. */\nexport const TOOL_SHIM_PATH = '/usr/local/bin/agentbox-tool-shim';\n\nexport function toolLinkDir(): string {\n return join(process.env['HOME'] ?? homedir(), '.local', 'bin');\n}\n\nexport interface ToolLinkSyncResult {\n added: string[];\n removed: string[];\n /** Names skipped because a real file already owns the name. */\n conflicts: string[];\n}\n\nexport interface SyncToolLinksOptions {\n dir?: string;\n shim?: string;\n /**\n * Which existing links this call is allowed to remove. Defaults to \"any of\n * ours\", which is what a full reconcile wants.\n *\n * Two processes sync these links: the daemon's reconciler and an approved\n * in-box `tool request`. Both make the directory match a list, so a\n * reconciler tick holding a list fetched *before* a grant landed would\n * delete the symlink the request just created — the exact opposite of the\n * immediate-use guarantee. Passing a snapshot taken before the list was\n * fetched confines pruning to links that already existed then, so a link\n * created during the fetch survives to the next tick.\n */\n prunable?: readonly string[];\n}\n\n/**\n * Make `~/.local/bin` hold exactly one shim symlink per name in `names`.\n *\n * Only touches links this function created (targets resolving to\n * `TOOL_SHIM_PATH`). A real binary sitting at the same name is reported as a\n * conflict and left alone — silently shadowing a user's own `terraform` with\n * a host proxy would be a nasty surprise, and the reverse (clobbering it)\n * would lose their install.\n */\nexport async function syncToolLinks(\n names: readonly string[],\n opts: SyncToolLinksOptions = {},\n): Promise<ToolLinkSyncResult> {\n const dir = opts.dir ?? toolLinkDir();\n const shim = opts.shim ?? TOOL_SHIM_PATH;\n const wanted = new Set(names.filter((n) => VALID_NAME.test(n)));\n const result: ToolLinkSyncResult = { added: [], removed: [], conflicts: [] };\n\n await mkdir(dir, { recursive: true });\n\n // Remove links we own that are no longer granted (a revoked grant should\n // make the command stop resolving, not linger until the box restarts).\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n entries = [];\n }\n const prunable = opts.prunable ? new Set(opts.prunable) : null;\n for (const entry of entries) {\n if (wanted.has(entry)) continue;\n if (prunable && !prunable.has(entry)) continue;\n if (await isOurLink(join(dir, entry), shim)) {\n await unlink(join(dir, entry)).catch(() => undefined);\n result.removed.push(entry);\n }\n }\n\n for (const name of wanted) {\n const path = join(dir, name);\n const existing = await lstat(path).catch(() => null);\n if (existing) {\n if (await isOurLink(path, shim)) continue; // already correct\n result.conflicts.push(name);\n continue;\n }\n try {\n await symlink(shim, path);\n result.added.push(name);\n } catch {\n result.conflicts.push(name);\n }\n }\n return result;\n}\n\nasync function isOurLink(path: string, shim: string): Promise<boolean> {\n try {\n const st = await lstat(path);\n if (!st.isSymbolicLink()) return false;\n return (await readlink(path)) === shim;\n } catch {\n return false;\n }\n}\n\nconst VALID_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._+-]{0,63}$/;\n\n/**\n * The tool links currently present in `dir`. Used by the reconciler to\n * snapshot state *before* it fetches the grant list, so it never prunes a\n * link that appeared while it was asking.\n */\nexport async function listToolLinks(opts: { dir?: string; shim?: string } = {}): Promise<string[]> {\n const dir = opts.dir ?? toolLinkDir();\n const shim = opts.shim ?? TOOL_SHIM_PATH;\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return [];\n }\n const out: string[] = [];\n for (const entry of entries) {\n if (await isOurLink(join(dir, entry), shim)) out.push(entry);\n }\n return out;\n}\n","import { postRpcAwait } from './relay-rpc.js';\nimport { listToolLinks, syncToolLinks } from './tool-links.js';\n\n/**\n * Keeps the box's per-tool shim symlinks in sync with the host's grant list.\n *\n * Reconciles ONCE at daemon start and then waits to be told. It used to poll\n * every 60s because the RPC was \"the one channel every provider already has\" —\n * but `Provider.exec` is a required interface method, so the host can simply run\n * `agentbox-ctl tool relink` in the box when a grant changes. Being told beats\n * asking: instant instead of up-to-a-minute, and on a control box every tick was\n * a WAN round trip per box per minute.\n *\n * What the startup reconcile covers is exactly what a push cannot: a box that was\n * paused or stopped when the grant changed, and a box created afterwards.\n *\n * Failures are silent by design: a box whose relay is briefly unreachable should\n * keep the links it already has, not tear them down.\n */\n\n/** Ceiling for the startup retry backoff (see {@link ToolLinksWatcher.scheduleRetry}). */\nconst RETRY_CEILING_MS = 60_000;\n\nexport interface ToolLinksWatcherOptions {\n /** Ceiling for the startup retry backoff. Tests shorten it. */\n retryCeilingMs?: number;\n /** Container path used to resolve which project's grants apply. */\n cwd?: string;\n onChange?: (added: string[], removed: string[], conflicts: string[]) => void;\n}\n\ninterface ToolListPayload {\n tools?: { name?: unknown; bin?: unknown }[];\n}\n\nexport class ToolLinksWatcher {\n private timer: NodeJS.Timeout | null = null;\n private retryTimer: NodeJS.Timeout | null = null;\n private running = false;\n private failures = 0;\n private readonly retryCeilingMs: number;\n /** True between start() and stop(); gates the startup retry timer. */\n private active = false;\n private readonly cwd: string;\n private readonly onChange: ToolLinksWatcherOptions['onChange'];\n /**\n * Signature of the last list we synced, or null for \"unknown\".\n *\n * NOT `''` for unknown: that is the signature of an empty grant list, so a\n * relink after revoking the last tool would compare equal and skip the sync,\n * leaving the shim in place on a box that no longer polls.\n */\n private lastSignature: string | null = null;\n\n constructor(opts: ToolLinksWatcherOptions = {}) {\n this.retryCeilingMs = opts.retryCeilingMs ?? RETRY_CEILING_MS;\n this.cwd = opts.cwd ?? '/workspace';\n this.onChange = opts.onChange;\n }\n\n start(): void {\n if (this.active) return;\n this.active = true;\n void this.tick();\n }\n\n stop(): void {\n this.active = false;\n if (this.retryTimer) {\n clearTimeout(this.retryTimer);\n this.retryTimer = null;\n }\n }\n\n /**\n * Re-sync now, whatever the last result was — the entry point the host pushes\n * to via `agentbox-ctl tool relink`.\n *\n * Clears the cached signature first: a push means \"something changed\", and the\n * skip-if-identical shortcut would otherwise ignore a link a user deleted by\n * hand, or one this box failed to create last time.\n */\n async relink(): Promise<'ok' | 'unavailable'> {\n this.lastSignature = null;\n return this.tick();\n }\n\n /**\n * A reconcile that couldn't reach the relay retries on a short backoff. This\n * is the startup case and it is the only reason a timer exists at all: the box\n * comes up, the daemon's first attempt may race the relay, and a tool granted\n * before the box existed must not stay missing. Reset by any success.\n */\n private scheduleRetry(): void {\n if (!this.active || this.retryTimer) return;\n this.failures += 1;\n const delay = Math.min(1_000 * 2 ** (this.failures - 1), this.retryCeilingMs);\n this.retryTimer = setTimeout(() => {\n this.retryTimer = null;\n void this.tick();\n }, delay);\n this.retryTimer.unref?.();\n }\n\n /**\n * Exposed so `tool request` can refresh links the moment it is approved, and\n * so `tool relink` can report whether it actually managed to.\n *\n * `unavailable` means the grant list could not be read — the links are left\n * exactly as they were, and the caller decides whether that is worth an error.\n */\n async tick(): Promise<'ok' | 'unavailable'> {\n if (this.running) return 'ok';\n this.running = true;\n try {\n // Snapshot BEFORE asking, so a link created while the RPC is in flight\n // (an approved `tool request` re-linking itself) is never pruned by\n // this tick's now-stale list.\n const prunable = await listToolLinks();\n const res = await postRpcAwait(\n 'tool.list',\n { path: this.cwd, format: 'json' },\n { errorPrefix: 'agentbox-ctl tool-links' },\n );\n if (res.exitCode !== 0) {\n this.scheduleRetry();\n return 'unavailable';\n }\n const names = parseToolNames(res.stdout);\n if (names === null) {\n this.scheduleRetry();\n return 'unavailable';\n }\n this.failures = 0;\n const signature = names.join(',');\n if (signature === this.lastSignature) return 'ok';\n const result = await syncToolLinks(names, { prunable });\n this.lastSignature = signature;\n if (result.added.length || result.removed.length || result.conflicts.length) {\n this.onChange?.(result.added, result.removed, result.conflicts);\n }\n return 'ok';\n } catch {\n // Keep whatever links exist; retry shortly.\n this.scheduleRetry();\n return 'unavailable';\n } finally {\n this.running = false;\n }\n }\n}\n\n/** `null` on a payload we can't read — the caller then leaves links alone. */\nexport function parseToolNames(stdout: string): string[] | null {\n let doc: unknown;\n try {\n doc = JSON.parse(stdout);\n } catch {\n return null;\n }\n const tools = (doc as ToolListPayload | null)?.tools;\n if (!Array.isArray(tools)) return null;\n return tools\n .map((t) => (typeof t?.name === 'string' ? t.name : null))\n .filter((n): n is string => n !== null)\n .sort();\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\n\n/**\n * The host-side `tools:` block in `agentbox.yaml` — a project's *request*\n * for host CLIs its agents need.\n *\n * A request is not a grant. `agentbox.yaml` is committed, so a cloned repo\n * declaring `tools: [aws]` must not be able to reach the host's AWS\n * credentials on its own. The host CLI prompts once at create time (the same\n * shape as the `carry:` gate) and writes the approved entries to the\n * host-only grant file; the relay reads only that. See docs/host-tools.md.\n *\n * Parsed here (rather than host-side) for the same reason `carry` is: the\n * supervisor must be able to parse a yaml that declares the block without\n * tripping the unknown-top-level-key check, and `ctl validate` should fail\n * loud on a typo while the user is still in the box.\n */\nexport interface ToolRequest {\n /** Command name the agent types in the box; also the shim symlink name. */\n name: string;\n /** Host binary to execute. Defaults to `name`. */\n bin?: string;\n /** Argv patterns (regex) that run without a host prompt. */\n allow?: string[];\n /** Argv patterns (regex) refused outright, on top of the built-in deny list. */\n deny?: string[];\n /** Per-call wall-clock budget in ms. */\n timeoutMs?: number;\n}\n\nexport class ToolsConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ToolsConfigError';\n }\n}\n\nconst ITEM_KEYS = new Set(['bin', 'allow', 'deny', 'timeoutMs']);\n\n/**\n * Same shape rule as the grant store's `isValidToolName`: the name becomes a\n * `~/.local/bin/<name>` symlink, so it must be a plain command name.\n * Duplicated rather than imported because `@agentbox/ctl` ships inside the\n * box and does not depend on `@agentbox/config`.\n */\nconst TOOL_NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9._+-]{0,63}$/;\n\nexport function parseToolsRaw(raw: unknown): ToolRequest[] {\n if (raw === undefined || raw === null) return [];\n // Two accepted spellings: a bare list of names (`tools: [terraform, aws]`)\n // and a mapping of name -> options. The list form covers the common case\n // where the project just needs the binary with default gating.\n if (Array.isArray(raw)) {\n return raw.map((item, i) => {\n if (typeof item !== 'string') {\n throw new ToolsConfigError(\n `tools[${String(i)}] must be a tool name string (use the mapping form for options)`,\n );\n }\n return { name: assertName(item.trim(), `tools[${String(i)}]`) };\n });\n }\n if (!isPlainObject(raw)) {\n throw new ToolsConfigError('tools must be a list of names or a mapping of name -> options');\n }\n const out: ToolRequest[] = [];\n for (const [name, value] of Object.entries(raw)) {\n const where = `tools.${name}`;\n assertName(name, where);\n if (value === null || value === undefined) {\n out.push({ name });\n continue;\n }\n if (!isPlainObject(value)) {\n throw new ToolsConfigError(`${where} must be a mapping of options (or empty)`);\n }\n for (const key of Object.keys(value)) {\n if (!ITEM_KEYS.has(key)) {\n throw new ToolsConfigError(\n `${where}.${key} is not a known option (allowed: ${[...ITEM_KEYS].join(', ')})`,\n );\n }\n }\n const req: ToolRequest = { name };\n if (value['bin'] !== undefined) {\n if (typeof value['bin'] !== 'string' || value['bin'].trim().length === 0) {\n throw new ToolsConfigError(`${where}.bin must be a non-empty string`);\n }\n const bin = value['bin'].trim();\n // Must be a bare command name resolved on the host's PATH — never a\n // path. A committed yaml that could say `bin: ./scripts/thing` would\n // get a script from its own checkout executed on the host with the\n // host's credentials, which is exactly what the request-vs-grant split\n // exists to prevent. (`agentbox tools add --bin` is unrestricted: that\n // is the user typing on their own machine.)\n if (!TOOL_NAME_RE.test(bin)) {\n throw new ToolsConfigError(\n `${where}.bin \"${bin}\" must be a bare command name resolved on PATH, not a path`,\n );\n }\n req.bin = bin;\n }\n const allow = parsePatternList(value['allow'], `${where}.allow`);\n if (allow) req.allow = allow;\n const deny = parsePatternList(value['deny'], `${where}.deny`);\n if (deny) req.deny = deny;\n if (value['timeoutMs'] !== undefined) {\n const n = value['timeoutMs'];\n if (typeof n !== 'number' || !Number.isInteger(n) || n <= 0) {\n throw new ToolsConfigError(`${where}.timeoutMs must be a positive integer (milliseconds)`);\n }\n req.timeoutMs = n;\n }\n out.push(req);\n }\n return out;\n}\n\nexport function parseToolsSection(text: string): ToolRequest[] {\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch (err) {\n throw new ToolsConfigError(\n `yaml parse error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (doc === null || doc === undefined) return [];\n if (!isPlainObject(doc)) {\n throw new ToolsConfigError('top-level config must be a mapping');\n }\n return parseToolsRaw(doc['tools']);\n}\n\nexport async function loadToolsSection(path: string): Promise<ToolRequest[]> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n return parseToolsSection(text);\n}\n\n// Patterns are compiled here so a typo in agentbox.yaml fails at parse time\n// rather than silently never matching (an unmatched `deny` would be a hole).\nfunction parsePatternList(raw: unknown, where: string): string[] | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!Array.isArray(raw)) {\n throw new ToolsConfigError(`${where} must be a list of regex patterns`);\n }\n const out: string[] = [];\n for (const [i, v] of raw.entries()) {\n if (typeof v !== 'string' || v.trim().length === 0) {\n throw new ToolsConfigError(`${where}[${String(i)}] must be a non-empty string`);\n }\n const pattern = v.trim();\n try {\n new RegExp(pattern);\n } catch (err) {\n throw new ToolsConfigError(\n `${where}[${String(i)}] is not a valid regex: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n out.push(pattern);\n }\n return out.length > 0 ? out : undefined;\n}\n\nfunction assertName(name: string, where: string): string {\n if (!TOOL_NAME_RE.test(name)) {\n throw new ToolsConfigError(\n `${where}: \"${name}\" is not a valid tool name (plain command name, no path separators)`,\n );\n }\n return name;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AIgBA,SAAS,aAAa;ACftB,SAAS,OAAO,aAAa;AAC7B,SAAS,UAAU,QAAAA,aAAY;AAC/B,SAAS,SAAAC,cAAa;AEHtB,SAAS,eAAe;AACxB,SAAS,QAAAC,aAAY;ACDrB,SAAS,SAAAC,cAA0B;ACoBnC,SAAS,wBAAwB;AACjC,SAAS,SAAS,UAAU;AAC5B,SAAS,cAAc;AACvB,SAAS,QAAAC,cAAY;AACrB,SAAS,SAAAD,cAAa;ACxBt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ir","basename","join","resolve","execa","readFile","parseYaml","readFile","parseYaml","parseYaml","isPlainObject","name","restart","command","parseYaml","parseReplacements","readFile","rules","ITEM_KEYS","isPlainObject","parseYaml","isPlainObject","execa","existsSync","readFile","stat","homedir","join","execa","execa","mkdir","readdir","rm","stat","homedir","join","resolve","mkdir","mkdtemp","readFile","readdir","rm","homedir","tmpdir","basename","join","execa","stat","execa","execa","randomBytes","existsSync","mkdir","readFile","readdir","rm","writeFile","homedir","dirname","join","resolve","execa","readdir","rm","stat","join","execa","join","homedir","join","execa","mkdir","dirname","join","execa","unlink","writeFile","readFile","homedir","join","execa","resolveAgentSpec","cp","BOX_HOME","basename","loadEffectiveConfig","homedir","mkdir","dirname","chmod","r","existsSync","stat","readFile","resolve","sanitizeMnemonic","readdir","rm","mkdtemp","tmpdir","shellSingleQuote","STATE_DIR","writeFile","pidAlive","randomBytes","pathExists","branch","gitWorktreePath","AGENT_SYNC_SPECS","makeSyncContext","relayPort","loadConfig","normalizeAgentStatus","persisted","buildNoVncUrl","endpoints","syncAgentboxSshConfig","record","posixDirname","cached","unlink","shellQuote"]}
|