@madarco/agentbox 0.31.2 → 0.31.4
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 +18 -0
- package/README.md +2 -0
- package/dist/_cloud-attach-B3BCOZ7U.js +31 -0
- package/dist/{chunk-LBBPEDRD.js → chunk-2MBELUE6.js} +9 -9
- package/dist/{chunk-AUBVCSFL.js → chunk-4LSLXBFN.js} +7 -7
- package/dist/{chunk-QUD42WO2.js → chunk-4NO5MO2P.js} +6 -6
- package/dist/{chunk-3LJH547J.js → chunk-4Y365UYP.js} +2 -2
- package/dist/{chunk-2756BRPK.js → chunk-5UX2HAF4.js} +31 -31
- package/dist/{chunk-HDSUUWTX.js → chunk-75JF44DH.js} +2 -2
- package/dist/{chunk-CDY4CMZX.js → chunk-AAMPHDB2.js} +6 -6
- package/dist/{chunk-7N3CJNR5.js → chunk-AWFTAHGF.js} +20 -7
- package/dist/chunk-AWFTAHGF.js.map +1 -0
- package/dist/{chunk-NS4DBXZR.js → chunk-AYREFYEF.js} +5 -5
- package/dist/{chunk-ERLTFI35.js → chunk-BYZPRB7U.js} +5 -5
- package/dist/{chunk-DS4K7ISX.js → chunk-C67DVYWA.js} +9 -4
- package/dist/chunk-C67DVYWA.js.map +1 -0
- package/dist/{chunk-RBEELJCJ.js → chunk-CUIJ2PIN.js} +10 -10
- package/dist/{chunk-67JVG72A.js → chunk-ENFWBFBI.js} +4 -4
- package/dist/{chunk-TMFNWCUQ.js → chunk-EP4IFSV5.js} +8 -6
- package/dist/chunk-EP4IFSV5.js.map +1 -0
- package/dist/{chunk-OUKDAUKX.js → chunk-EXF4PLBN.js} +3 -3
- package/dist/{chunk-6F6OUFLD.js → chunk-GCS5XAPC.js} +4 -4
- package/dist/{chunk-QYUHZOIW.js → chunk-IF4VXKJK.js} +4 -4
- package/dist/{chunk-TQL4VWVV.js → chunk-IFPTD73K.js} +2 -2
- package/dist/{chunk-IZTWZJMF.js → chunk-IQ6BQ2LX.js} +4 -4
- package/dist/{chunk-UMK4HA6G.js → chunk-IQMDGAMB.js} +4 -4
- package/dist/{chunk-QOFQZRDG.js → chunk-KCDLAP5Q.js} +4 -4
- package/dist/{chunk-ABKHJ2QL.js → chunk-L567TKOK.js} +6 -6
- package/dist/{chunk-FUJRTZBN.js → chunk-LR5RNEVO.js} +3 -3
- package/dist/{chunk-NGUNB6M2.js → chunk-M6VAID7T.js} +3 -3
- package/dist/{chunk-BNMTBKQJ.js → chunk-MBZ4UOWF.js} +4 -4
- package/dist/{chunk-BBQ3VYLV.js → chunk-MJZPECVQ.js} +3 -3
- package/dist/{chunk-3T4CPP3U.js → chunk-NKHRFR5G.js} +17 -17
- package/dist/{chunk-IQJ6OUN5.js → chunk-OXBWZG2N.js} +4 -4
- package/dist/{chunk-BKTP27TW.js → chunk-PXH3DERD.js} +3 -3
- package/dist/{chunk-BT7OQHZ4.js → chunk-QDVIMN57.js} +4 -4
- package/dist/{chunk-EK32GLP5.js → chunk-QT4MOS6R.js} +22 -22
- package/dist/{chunk-LFN6QCM6.js → chunk-QWWDG5B7.js} +6 -6
- package/dist/{chunk-NWIQQB6U.js → chunk-RUKTOHK7.js} +3 -3
- package/dist/{chunk-FDHOIH3V.js → chunk-VOVRWIBC.js} +11 -11
- package/dist/{chunk-3S5RZCIG.js → chunk-VQONUZE4.js} +4 -4
- package/dist/{chunk-MH63I6AL.js → chunk-VWJBQGXD.js} +6 -6
- package/dist/{chunk-KKTCDNRO.js → chunk-X6SZPGL5.js} +7 -7
- package/dist/{chunk-H3BU75PN.js → chunk-YL3VEQTS.js} +6 -6
- package/dist/{chunk-N5LNX6X2.js → chunk-YSC4VY43.js} +4 -4
- package/dist/{chunk-S3LDXOIT.js → chunk-ZUTC2JZM.js} +5 -5
- package/dist/{cli-JRP3VNEM.js → cli-7JW54ZTA.js} +9 -9
- package/dist/{cli-BILGBUVD.js → cli-7Z7BD23R.js} +8 -8
- package/dist/{cli-MCXZDAEN.js → cli-HFLU5QTD.js} +8 -8
- package/dist/{cli-YXG2QKDM.js → cli-KT5X4J74.js} +9 -9
- package/dist/{cli-UUPHZRKG.js → cli-XRF7WFE5.js} +9 -9
- package/dist/cloud-backends.js +5 -5
- package/dist/{control-plane-54U2RAMT.js → control-plane-DGLF4MBB.js} +20 -20
- package/dist/{cp-hub-upload-7GJQO4FY.js → cp-hub-upload-7YESYCVS.js} +7 -7
- package/dist/{custody-client-G4SNQYTT.js → custody-client-P7SCEDU2.js} +5 -5
- package/dist/{deploy-hetzner-X6WUZPPJ.js → deploy-hetzner-FOCNRRB2.js} +9 -9
- package/dist/{dist-MY3UXECL.js → dist-2CAWJQT5.js} +6 -6
- package/dist/{dist-JLQLHSN6.js → dist-36WLI6E2.js} +7 -7
- package/dist/{dist-VBOFIW7E.js → dist-54VRDCUU.js} +8 -8
- package/dist/{dist-F3HWDZ32.js → dist-63YBVZW4.js} +9 -9
- package/dist/{dist-MBPDLQUR.js → dist-BUCKUE4V.js} +2 -2
- package/dist/{dist-V3P3SIBU.js → dist-CBPQZPQN.js} +8 -8
- package/dist/{dist-JCVHBCEV.js → dist-E4VLIH3H.js} +8 -8
- package/dist/{dist-TSPUGLQM.js → dist-FHPNYDCF.js} +3 -3
- package/dist/{dist-NC2UMRWF.js → dist-MITAKWKQ.js} +8 -8
- package/dist/{dist-RWC4EWSU.js → dist-TJJ6KBNZ.js} +4 -4
- package/dist/{dist-HPXCGKM4.js → dist-XSAPZOEG.js} +8 -8
- package/dist/{host-reach-drainer-CF7YGFI4.js → host-reach-drainer-XFLSMTSX.js} +2 -2
- package/dist/hub-OMGLWQEV.js +39 -0
- package/dist/{hub-adopt-OQUIDTUW.js → hub-adopt-IYZ3WXYN.js} +7 -7
- package/dist/{hub-api-client-WBXO4BUG.js → hub-api-client-WOZ2BQ6H.js} +4 -4
- package/dist/{hub-docker-target-JHOIAOIF.js → hub-docker-target-IQHX6OYX.js} +14 -14
- package/dist/index.js +61 -61
- package/dist/{plugin-update-FZKBBDMJ.js → plugin-update-2ACFHFUI.js} +5 -5
- package/dist/prepare-OOZF37J6.js +45 -0
- package/dist/prepared-custody-E7CSZJ6V.js +39 -0
- package/dist/{prepared-state-FO74QUCP-RX7DKZ7J.js → prepared-state-FO74QUCP-PZLOM6HD.js} +4 -4
- package/dist/{publish-credentials-GKZGTWEI.js → publish-credentials-TO5IIW2T.js} +9 -9
- package/dist/{registry-IKU6MBLX.js → registry-X33JZU6B.js} +5 -5
- package/dist/relay-7D5NOFKS.js +22 -0
- package/dist/{remote-docker-share-YWI2UXGS.js → remote-docker-share-YADHIHXV.js} +11 -11
- package/dist/{tool-grant-push-KMMSJPGK.js → tool-grant-push-7G2QAN3J.js} +3 -3
- package/package.json +1 -1
- package/runtime/_shared/ctl.cjs +26 -8
- package/runtime/digitalocean/ctl.cjs +26 -8
- package/runtime/docker/packages/ctl/dist/bin.cjs +26 -8
- package/runtime/e2b/ctl.cjs +26 -8
- package/runtime/hetzner/ctl.cjs +26 -8
- package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
- package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
- package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0vg6gvw._.js +22 -22
- 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/ssr/_14-qzbg._.js +1 -1
- 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/middleware-build-manifest.js +3 -3
- package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
- package/runtime/hub/apps/hub/{chunk-FQY5OEWX.js → chunk-2LE76CT3.js} +19 -6
- package/runtime/hub/apps/hub/{chunk-6CRH52LO.js → chunk-7IIG6MIB.js} +9 -9
- package/runtime/hub/apps/hub/{chunk-V6HJFB7G.js → chunk-7JBH42LK.js} +3 -3
- package/runtime/hub/apps/hub/{chunk-MIEBOFHZ.js → chunk-AAF4CYVH.js} +6 -6
- package/runtime/hub/apps/hub/{chunk-IDIFPYTE.js → chunk-AIFVVQPX.js} +7 -5
- package/runtime/hub/apps/hub/{chunk-NHYDZVES.js → chunk-F6GOERHP.js} +4 -4
- package/runtime/hub/apps/hub/{chunk-V4YXLMFI.js → chunk-SM2XYDPL.js} +8 -3
- package/runtime/hub/apps/hub/{dist-RW6RLHQK.js → dist-BKCL4HAA.js} +5 -5
- package/runtime/hub/apps/hub/{dist-FM26NQ4V.js → dist-D36FTGG6.js} +1 -1
- package/runtime/hub/apps/hub/{dist-I275RO6P.js → dist-DS5LGBGK.js} +2 -2
- package/runtime/hub/apps/hub/{dist-VOIDY4IM.js → dist-H7NIUVBD.js} +6 -6
- package/runtime/hub/apps/hub/{dist-C2JJTBDD.js → dist-LV6CHJVA.js} +5 -5
- package/runtime/hub/apps/hub/{dist-SINRABCR.js → dist-MQADLEEQ.js} +5 -5
- package/runtime/hub/apps/hub/{dist-BIXUQKSK.js → dist-RJBPZWSZ.js} +5 -5
- package/runtime/hub/apps/hub/{dist-K4GLZWXS.js → dist-VENYRIRW.js} +5 -5
- package/runtime/hub/apps/hub/{dist-B5IUHK2B.js → dist-YG4RVC24.js} +6 -6
- package/runtime/hub/apps/hub/{dist-VLKRF6NH.js → dist-YOTRYCRK.js} +4 -4
- package/runtime/hub/apps/hub/{hub-worker-HSKRQMH5.js → hub-worker-DLFLGKCV.js} +7 -7
- package/runtime/hub/apps/hub/{prepared-state-FO74QUCP-UL4TQJT4.js → prepared-state-FO74QUCP-FZ6PT4LA.js} +3 -3
- package/runtime/hub/apps/hub/server.js +13 -13
- package/runtime/relay/bin.cjs +26 -8
- package/runtime/vercel/ctl.cjs +26 -8
- package/dist/_cloud-attach-N3JJD7JF.js +0 -31
- package/dist/chunk-7N3CJNR5.js.map +0 -1
- package/dist/chunk-DS4K7ISX.js.map +0 -1
- package/dist/chunk-TMFNWCUQ.js.map +0 -1
- package/dist/hub-PITRE4LQ.js +0 -39
- package/dist/prepare-WAIDHKO3.js +0 -45
- package/dist/prepared-custody-ALF6YHQC.js +0 -39
- package/dist/relay-7VSUDQPP.js +0 -22
- /package/dist/{_cloud-attach-N3JJD7JF.js.map → _cloud-attach-B3BCOZ7U.js.map} +0 -0
- /package/dist/{chunk-LBBPEDRD.js.map → chunk-2MBELUE6.js.map} +0 -0
- /package/dist/{chunk-AUBVCSFL.js.map → chunk-4LSLXBFN.js.map} +0 -0
- /package/dist/{chunk-QUD42WO2.js.map → chunk-4NO5MO2P.js.map} +0 -0
- /package/dist/{chunk-3LJH547J.js.map → chunk-4Y365UYP.js.map} +0 -0
- /package/dist/{chunk-2756BRPK.js.map → chunk-5UX2HAF4.js.map} +0 -0
- /package/dist/{chunk-HDSUUWTX.js.map → chunk-75JF44DH.js.map} +0 -0
- /package/dist/{chunk-CDY4CMZX.js.map → chunk-AAMPHDB2.js.map} +0 -0
- /package/dist/{chunk-NS4DBXZR.js.map → chunk-AYREFYEF.js.map} +0 -0
- /package/dist/{chunk-ERLTFI35.js.map → chunk-BYZPRB7U.js.map} +0 -0
- /package/dist/{chunk-RBEELJCJ.js.map → chunk-CUIJ2PIN.js.map} +0 -0
- /package/dist/{chunk-67JVG72A.js.map → chunk-ENFWBFBI.js.map} +0 -0
- /package/dist/{chunk-OUKDAUKX.js.map → chunk-EXF4PLBN.js.map} +0 -0
- /package/dist/{chunk-6F6OUFLD.js.map → chunk-GCS5XAPC.js.map} +0 -0
- /package/dist/{chunk-QYUHZOIW.js.map → chunk-IF4VXKJK.js.map} +0 -0
- /package/dist/{chunk-TQL4VWVV.js.map → chunk-IFPTD73K.js.map} +0 -0
- /package/dist/{chunk-IZTWZJMF.js.map → chunk-IQ6BQ2LX.js.map} +0 -0
- /package/dist/{chunk-UMK4HA6G.js.map → chunk-IQMDGAMB.js.map} +0 -0
- /package/dist/{chunk-QOFQZRDG.js.map → chunk-KCDLAP5Q.js.map} +0 -0
- /package/dist/{chunk-ABKHJ2QL.js.map → chunk-L567TKOK.js.map} +0 -0
- /package/dist/{chunk-FUJRTZBN.js.map → chunk-LR5RNEVO.js.map} +0 -0
- /package/dist/{chunk-NGUNB6M2.js.map → chunk-M6VAID7T.js.map} +0 -0
- /package/dist/{chunk-BNMTBKQJ.js.map → chunk-MBZ4UOWF.js.map} +0 -0
- /package/dist/{chunk-BBQ3VYLV.js.map → chunk-MJZPECVQ.js.map} +0 -0
- /package/dist/{chunk-3T4CPP3U.js.map → chunk-NKHRFR5G.js.map} +0 -0
- /package/dist/{chunk-IQJ6OUN5.js.map → chunk-OXBWZG2N.js.map} +0 -0
- /package/dist/{chunk-BKTP27TW.js.map → chunk-PXH3DERD.js.map} +0 -0
- /package/dist/{chunk-BT7OQHZ4.js.map → chunk-QDVIMN57.js.map} +0 -0
- /package/dist/{chunk-EK32GLP5.js.map → chunk-QT4MOS6R.js.map} +0 -0
- /package/dist/{chunk-LFN6QCM6.js.map → chunk-QWWDG5B7.js.map} +0 -0
- /package/dist/{chunk-NWIQQB6U.js.map → chunk-RUKTOHK7.js.map} +0 -0
- /package/dist/{chunk-FDHOIH3V.js.map → chunk-VOVRWIBC.js.map} +0 -0
- /package/dist/{chunk-3S5RZCIG.js.map → chunk-VQONUZE4.js.map} +0 -0
- /package/dist/{chunk-MH63I6AL.js.map → chunk-VWJBQGXD.js.map} +0 -0
- /package/dist/{chunk-KKTCDNRO.js.map → chunk-X6SZPGL5.js.map} +0 -0
- /package/dist/{chunk-H3BU75PN.js.map → chunk-YL3VEQTS.js.map} +0 -0
- /package/dist/{chunk-N5LNX6X2.js.map → chunk-YSC4VY43.js.map} +0 -0
- /package/dist/{chunk-S3LDXOIT.js.map → chunk-ZUTC2JZM.js.map} +0 -0
- /package/dist/{cli-BILGBUVD.js.map → cli-7JW54ZTA.js.map} +0 -0
- /package/dist/{cli-JRP3VNEM.js.map → cli-7Z7BD23R.js.map} +0 -0
- /package/dist/{cli-MCXZDAEN.js.map → cli-HFLU5QTD.js.map} +0 -0
- /package/dist/{cli-UUPHZRKG.js.map → cli-KT5X4J74.js.map} +0 -0
- /package/dist/{cli-YXG2QKDM.js.map → cli-XRF7WFE5.js.map} +0 -0
- /package/dist/{control-plane-54U2RAMT.js.map → control-plane-DGLF4MBB.js.map} +0 -0
- /package/dist/{cp-hub-upload-7GJQO4FY.js.map → cp-hub-upload-7YESYCVS.js.map} +0 -0
- /package/dist/{custody-client-G4SNQYTT.js.map → custody-client-P7SCEDU2.js.map} +0 -0
- /package/dist/{deploy-hetzner-X6WUZPPJ.js.map → deploy-hetzner-FOCNRRB2.js.map} +0 -0
- /package/dist/{dist-F3HWDZ32.js.map → dist-2CAWJQT5.js.map} +0 -0
- /package/dist/{dist-HPXCGKM4.js.map → dist-36WLI6E2.js.map} +0 -0
- /package/dist/{dist-VBOFIW7E.js.map → dist-54VRDCUU.js.map} +0 -0
- /package/dist/{dist-JLQLHSN6.js.map → dist-63YBVZW4.js.map} +0 -0
- /package/dist/{dist-MBPDLQUR.js.map → dist-BUCKUE4V.js.map} +0 -0
- /package/dist/{dist-MY3UXECL.js.map → dist-CBPQZPQN.js.map} +0 -0
- /package/dist/{dist-JCVHBCEV.js.map → dist-E4VLIH3H.js.map} +0 -0
- /package/dist/{dist-NC2UMRWF.js.map → dist-FHPNYDCF.js.map} +0 -0
- /package/dist/{dist-RWC4EWSU.js.map → dist-MITAKWKQ.js.map} +0 -0
- /package/dist/{dist-TSPUGLQM.js.map → dist-TJJ6KBNZ.js.map} +0 -0
- /package/dist/{dist-V3P3SIBU.js.map → dist-XSAPZOEG.js.map} +0 -0
- /package/dist/{host-reach-drainer-CF7YGFI4.js.map → host-reach-drainer-XFLSMTSX.js.map} +0 -0
- /package/dist/{hub-PITRE4LQ.js.map → hub-OMGLWQEV.js.map} +0 -0
- /package/dist/{hub-adopt-OQUIDTUW.js.map → hub-adopt-IYZ3WXYN.js.map} +0 -0
- /package/dist/{hub-api-client-WBXO4BUG.js.map → hub-api-client-WOZ2BQ6H.js.map} +0 -0
- /package/dist/{hub-docker-target-JHOIAOIF.js.map → hub-docker-target-IQHX6OYX.js.map} +0 -0
- /package/dist/{plugin-update-FZKBBDMJ.js.map → plugin-update-2ACFHFUI.js.map} +0 -0
- /package/dist/{prepare-WAIDHKO3.js.map → prepare-OOZF37J6.js.map} +0 -0
- /package/dist/{prepared-custody-ALF6YHQC.js.map → prepared-custody-E7CSZJ6V.js.map} +0 -0
- /package/dist/{prepared-state-FO74QUCP-RX7DKZ7J.js.map → prepared-state-FO74QUCP-PZLOM6HD.js.map} +0 -0
- /package/dist/{publish-credentials-GKZGTWEI.js.map → publish-credentials-TO5IIW2T.js.map} +0 -0
- /package/dist/{registry-IKU6MBLX.js.map → registry-X33JZU6B.js.map} +0 -0
- /package/dist/{relay-7VSUDQPP.js.map → relay-7D5NOFKS.js.map} +0 -0
- /package/dist/{remote-docker-share-YWI2UXGS.js.map → remote-docker-share-YADHIHXV.js.map} +0 -0
- /package/dist/{tool-grant-push-KMMSJPGK.js.map → tool-grant-push-7G2QAN3J.js.map} +0 -0
- /package/runtime/hub/apps/hub/.next/static/{cXSQmUIAB12u7BgxO4JPy → o9_g9S5JH-r8bfNfmPa5H}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{cXSQmUIAB12u7BgxO4JPy → o9_g9S5JH-r8bfNfmPa5H}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{cXSQmUIAB12u7BgxO4JPy → o9_g9S5JH-r8bfNfmPa5H}/_ssgManifest.js +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/agent-registry/src/specs/claude.ts","../../../packages/agent-registry/src/specs/codex.ts","../../../packages/agent-registry/src/specs/example.ts","../../../packages/agent-registry/src/specs/openclaw.ts","../../../packages/agent-registry/src/specs/opencode.ts","../../../packages/agent-registry/src/specs/_codex-import.ts","../../../packages/agent-registry/src/specs/pi.ts","../../../packages/agent-registry/src/plugin-agents.ts","../../../packages/agent-registry/src/index.ts","../../../packages/core/src/provider-warning.ts","../../../packages/core/src/agent.ts","../../../packages/core/src/box-record.ts","../../../packages/core/src/sync/agent-spec.ts","../../../packages/core/src/persistent.ts","../../../packages/core/src/vnc.ts","../../../packages/core/src/replace.ts","../../../packages/core/src/errors.ts","../../../packages/core/src/identity.ts","../../../packages/core/src/prompt.ts","../../../packages/core/src/sync/agent-status.ts","../../../packages/core/src/sync/agent-kind.ts","../../../packages/core/src/sync/provider-sync.ts","../../../packages/core/src/sync/topology.ts","../../../packages/core/src/sync/files.ts","../../../packages/core/src/sync/containment.ts","../../../packages/core/src/sync/git-refs.ts"],"sourcesContent":["/**\n * Claude Code's registry row — the DATA half of this package.\n *\n * Imports only the two dependency-free leaves (`@agentbox/core` for the\n * contract, `@agentbox/config` for the host state dir) on purpose: this entry is read by\n * the agent registry, which `sandbox-core` depends on, which in turn everything\n * depends on. Anything heavier here is a dependency cycle. See this package's\n * `tsup.config.ts`.\n */\n\nimport { join } from 'node:path';\nimport { STATE_DIR } from '@agentbox/config';\nimport {\n BOX_USER,\n BOX_HOME,\n BOX_CREDS_DIR,\n SETUP_GUIDE_PATH,\n agentDirPrelude,\n} from '@agentbox/core';\nimport type { AgentSyncSpec } from '@agentbox/core';\n\nconst CLAUDE_BOX_DIR = `${BOX_HOME}/.claude`;\n\n/**\n * Copy the in-box-only `/agentbox-setup` skill the first-run wizard prompt\n * references into claude's config dir.\n *\n * Shared by BOTH of claude's recipes. It used to live only on the native one,\n * which silently cost `box.claudeInstall: npm` — the CDN-403 fallback — its\n * first-run wizard, because the providers' base scripts no longer copy it\n * either (it moved onto the agent, where it belongs).\n *\n * Guarded: the source is baked into every provider's base image, but a box\n * built from an older base may not have it, and a missing wizard skill must\n * never fail an agent install. On docker the config volume mounts over this dir,\n * so the `seeds` declaration below re-places the same content into the volume —\n * harmless, identical bytes.\n *\n * `skills` is created by its OWN `install -d`, not left to the nested path.\n * GNU `install -d -o u -g g a/b/c` applies the ownership to the FINAL component\n * only — intermediates are created root-owned. Since this runs as root, folding\n * `skills` into the nested call leaves it owned by root, and the later static\n * config stage (`sudo -u <box user> tar -C ~/.claude`) then cannot create\n * `skills/<name>` and dies with \"Permission denied\" — which aborts the whole\n * bake. Cost a live DigitalOcean derive to find.\n */\nconst SEED_SETUP_SKILL = `if [ -f ${SETUP_GUIDE_PATH} ]; then install -d -o ${BOX_USER} -g ${BOX_USER} ${CLAUDE_BOX_DIR}/skills && install -d -o ${BOX_USER} -g ${BOX_USER} ${CLAUDE_BOX_DIR}/skills/agentbox-setup && install -o ${BOX_USER} -g ${BOX_USER} -m 0644 ${SETUP_GUIDE_PATH} ${CLAUDE_BOX_DIR}/skills/agentbox-setup/SKILL.md; fi`;\n\nexport const claudeSpec: AgentSyncSpec = {\n id: 'claude',\n aliases: ['claude-code'],\n wireId: 'claude-code',\n sessionName: 'claude',\n binary: 'claude',\n // Anthropic's native installer is the canonical path (code.claude.com/docs/en/setup)\n // and drops the binary at ~/.local/bin/claude, which is what the host's\n // `.claude.json` (installMethod=native) expects. The CDN intermittently 403s\n // cloud egress IPs under load, hence the retries. The npm package is a\n // BAKE-TIME-only fallback selected by `claude.install`, not a second recipe.\n install: {\n recipe: { kind: 'script', url: 'https://claude.ai/install.sh', retries: 3 },\n runAs: 'box-user',\n alternatesFrom: 'install',\n // ~/.claude must exist and be box-user-owned BEFORE the named config\n // volume mounts over it: docker seeds an empty volume's permissions from\n // the mount point, so without this the volume comes up root-owned and\n // Claude Code can't write. The two symlinks are deliberately dangling at\n // build time — `_claude.json` materialises when the volume is seeded, and\n // `.credentials.json` resolves once the cloud credential volume mounts.\n postInstall: [\n ...agentDirPrelude([CLAUDE_BOX_DIR], 'claude'),\n `ln -sfn ${CLAUDE_BOX_DIR}/_claude.json ${BOX_HOME}/.claude.json`,\n `ln -sfn ${BOX_CREDS_DIR}/claude/.credentials.json ${CLAUDE_BOX_DIR}/.credentials.json`,\n `chown -h ${BOX_USER}:${BOX_USER} ${BOX_HOME}/.claude.json ${CLAUDE_BOX_DIR}/.credentials.json`,\n SEED_SETUP_SKILL,\n ].join(' && '),\n alternates: {\n // `claude.install: npm`. npm-global drops `claude` at Node's prefix\n // bin; symlink it into ~/.local/bin so the box is indistinguishable\n // from a native install (the host's .claude.json says installMethod\n // native, and the in-box integrity check compares against that).\n npm: {\n recipe: { kind: 'npm', package: '@anthropic-ai/claude-code' },\n runAs: 'root',\n postInstall: [\n ...agentDirPrelude([`${BOX_HOME}/.local/bin`, CLAUDE_BOX_DIR], 'claude'),\n `ln -sf \"$(command -v claude)\" ${BOX_HOME}/.local/bin/claude`,\n `ln -sfn ${CLAUDE_BOX_DIR}/_claude.json ${BOX_HOME}/.claude.json`,\n `ln -sfn ${BOX_CREDS_DIR}/claude/.credentials.json ${CLAUDE_BOX_DIR}/.credentials.json`,\n `chown -h ${BOX_USER}:${BOX_USER} ${BOX_HOME}/.local/bin/claude ${BOX_HOME}/.claude.json ${CLAUDE_BOX_DIR}/.credentials.json`,\n SEED_SETUP_SKILL,\n ].join(' && '),\n },\n },\n },\n dockerVolume: 'agentbox-claude-config',\n staticPaths: [\n {\n hostHomeRel: ['.claude'],\n boxDir: CLAUDE_BOX_DIR,\n // Push excludes (single source of truth; consumed by\n // `agentPushExcludes`). `node_modules` drops host-platform binaries; the\n // rest is per-machine runtime/history state the in-box claude regenerates\n // (`workflows` is seeded per-box at create time, not baked).\n //\n // The credential file is NOT listed: `agentPushExcludes` derives it from\n // `credential.boxRelPath`, because whether to exclude it differs by target\n // (out of a shared snapshot, into the box's own volume).\n exclude: [\n 'node_modules',\n 'projects',\n 'workflows',\n 'sessions',\n 'history.jsonl',\n 'file-history',\n 'shell-snapshots',\n 'backups',\n 'session-env',\n 'paste-cache',\n 'cache',\n 'telemetry',\n 'tasks',\n 'downloads',\n 'chrome',\n 'ide',\n 'debug',\n 'mcp-needs-auth-cache.json',\n 'stats-cache.json',\n ],\n },\n ],\n credential: {\n boxRelPath: '.credentials.json',\n boxAbsPath: `${CLAUDE_BOX_DIR}/.credentials.json`,\n hostBackup: join(STATE_DIR, 'claude-credentials.json'),\n cloudMountPath: '/home/vscode/.agentbox-creds/claude',\n cloudSubpath: 'claude/',\n realShape: 'claude-oauth',\n // `claudeAiOauth.expiresAt` strictly increases on every OAuth refresh\n // (verified live), and the refresh ROTATES the refresh token — so an older\n // blob is dead, not merely stale, and must never overwrite a newer one.\n freshness: { jsonPath: ['claudeAiOauth', 'expiresAt'] },\n },\n forwardedEnvKeys: [\n 'ANTHROPIC_API_KEY',\n 'CLAUDE_CODE_OAUTH_TOKEN',\n 'CLAUDE_EFFORT',\n 'ANTHROPIC_MODEL',\n ],\n boxRunEnv: {},\n // Claude Code's own renderer overrides. See `AgentSyncSpec.tuiEnv` for why\n // this is data: it replaced a `binary === 'claude'` branch at each cloud\n // launch site. `auto` is present and empty on purpose — \"no override, Claude\n // Code decides\" is a real mode, not a missing entry.\n tuiEnv: {\n default: { CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN: '1' },\n fullscreen: { CLAUDE_CODE_NO_FLICKER: '1' },\n auto: {},\n },\n tuiEnvFrom: 'tui',\n // Claude's own settings. These stay CLAUDE-named because they genuinely are:\n // one picks between Anthropic's installer and the npm package, the other\n // between Claude Code's two renderers. What is generic is the mechanism —\n // config generates `claude.install` / `claude.tui` from these rows, and the\n // values reach this spec's `alternates` / `tuiEnv` and the install shell's\n // `AGENTBOX_AGENT_SETTING_*` env without any shared code knowing what they\n // mean.\n settings: [\n {\n key: 'install',\n type: 'enum',\n enumValues: ['native', 'npm'],\n default: 'native',\n description:\n \"How Claude Code is installed into a box image: `native` runs Anthropic's installer (the recommended path), `npm` installs @anthropic-ai/claude-code. Use `npm` on hosts whose egress IP the native CDN 403s. Bake-time - changing it re-derives the agent layer.\",\n // Two values are two derived agent artifacts. The AGENTLESS base is\n // unaffected: it installs no agent, so it must not fork on this.\n affectsBake: true,\n },\n {\n key: 'tui',\n type: 'enum',\n enumValues: ['default', 'fullscreen', 'auto'],\n default: 'default',\n description:\n \"Terminal renderer Claude Code uses inside a box. Claude's `fullscreen` renderer repaints differentially and leaves stale characters in the blank areas of the screen over a network transport - visible while scrolling, cleared only by resizing the terminal. Boxes pin the classic renderer; set `fullscreen` to opt back in, or `auto` to let Claude decide. Rides the launch, so it takes effect on the agent's next start.\",\n // Deliberately NOT affectsBake: it is launch env, and folding it would\n // re-bake a whole base image for a renderer flip.\n },\n ],\n // The box-ONLY wizard skill: deliberately never written to the host's\n // ~/.claude. Claude also gets it at install time via SEED_SETUP_SKILL, but\n // the docker config volume mounts OVER ~/.claude, so it has to be re-placed\n // into the volume as well — same bytes, two placements.\n seeds: [\n {\n bakedPath: SETUP_GUIDE_PATH,\n destRel: 'skills/agentbox-setup/SKILL.md',\n sharedAsset: 'agentbox-setup-skill.md',\n label: 'the /agentbox-setup skill',\n },\n ],\n caps: { resume: true, teleport: 'full', activitySource: ['hooks', 'scraper'] },\n // Box->host. Claude's unit is a CHILD of a category dir, plus a 2-level\n // plugin cache, plus two registry JSONs merged additively with a\n // container->host path rewrite. See AgentPullSpec.\n pull: {\n categories: ['skills', 'agents', 'commands'],\n jsonMerges: [\n { rel: 'plugins/installed_plugins.json', projection: 'plugins' },\n { rel: 'plugins/known_marketplaces.json', projection: 'root' },\n ],\n },\n};\n","/**\n * Codex's registry row — the DATA half of this package.\n *\n * Imports only the two dependency-free leaves (`@agentbox/core` for the\n * contract, `@agentbox/config` for the host state dir) on purpose: this entry is read by\n * the agent registry, which `sandbox-core` depends on, which in turn everything\n * depends on. Anything heavier here is a dependency cycle. See this package's\n * `tsup.config.ts`.\n */\n\nimport { join } from 'node:path';\nimport { STATE_DIR } from '@agentbox/config';\nimport { BOX_USER, BOX_HOME, BOX_CREDS_DIR, agentDirPrelude } from '@agentbox/core';\nimport type { AgentSyncSpec } from '@agentbox/core';\n\nconst CODEX_BOX_DIR = `${BOX_HOME}/.codex`;\n/** Baked alongside the setup guide: codex's activity-reporting hooks. */\nconst CODEX_HOOKS_PATH = '/usr/local/share/agentbox/codex-hooks.json';\n\nexport const codexSpec: AgentSyncSpec = {\n id: 'codex',\n aliases: [],\n sessionName: 'codex',\n binary: 'codex',\n // `bubblewrap` is Codex's command-sandbox backend; without it on PATH Codex\n // falls back to a bundled copy and warns on every run.\n install: {\n recipe: { kind: 'npm', package: '@openai/codex' },\n runAs: 'root',\n // Optional: Codex ships a bundled bwrap and only warns without the system\n // one, so a missing or unavailable package must not fail a box create.\n // Amazon Linux 2023 (Vercel) may not carry it at all.\n packages: ['bubblewrap'],\n packagesOptional: true,\n postInstall: [\n ...agentDirPrelude([CODEX_BOX_DIR], 'codex'),\n `ln -sfn ${BOX_CREDS_DIR}/codex/auth.json ${CODEX_BOX_DIR}/auth.json`,\n `chown -h ${BOX_USER}:${BOX_USER} ${CODEX_BOX_DIR}/auth.json`,\n ].join(' && '),\n },\n dockerVolume: 'agentbox-codex-config',\n staticPaths: [\n {\n hostHomeRel: ['.codex'],\n boxDir: CODEX_BOX_DIR,\n // Push excludes (single source of truth; consumed by\n // `agentPushExcludes`, which also derives the credential file and applies\n // LIVE_DATABASE_EXCLUDES — so the `*.sqlite*` families no longer need\n // naming here, and cannot go stale again as codex adds databases).\n // `state_*.sqlite*` is the resume-cwd index (rebuilt in-box);\n // `packages`/`plugins/.plugin-appserver`/`computer-use` are heavy\n // macOS-only artifacts; the rest is host-only session/log/cache state.\n //\n // `.tmp` carve-in: the git-marketplace snapshots (`.tmp/marketplaces/`,\n // ~13 MB) must reach the box or in-box `codex plugin` breaks\n // (\"marketplace root does not contain a supported manifest\" — and the\n // box can't re-clone, the git shim blocks `clone`). The includes are\n // emitted BEFORE the excludes (first-match-wins): the root `.tmp/` dir\n // and the marketplaces subtree transfer, `/.tmp/*` drops its other\n // children (the ~200 MB desktop-app `bundled-marketplaces` + `plugins`\n // payloads), and the unanchored `.tmp` still blocks nested `.tmp` dirs\n // elsewhere in the tree.\n include: ['/.tmp/', '/.tmp/marketplaces/***'],\n exclude: [\n 'sessions',\n 'log',\n 'history.jsonl',\n 'hooks.json',\n 'external_agent_session_imports.json',\n // The DIRECTORY, not a database pattern: `LIVE_DATABASE_EXCLUDES`\n // matches file names, so dropping this would still ship the empty dir.\n 'sqlite',\n 'cache',\n 'vendor_imports',\n 'tmp',\n '/.tmp/*',\n '.tmp',\n '.codex-global-state.json',\n '.codex-global-state.json.bak',\n '.personality_migration',\n 'shell_snapshots',\n 'session_index.jsonl',\n 'models_cache.json',\n 'installation_id',\n 'version.json',\n 'packages',\n 'plugins/.plugin-appserver',\n 'computer-use',\n 'archived_sessions',\n ],\n },\n ],\n credential: {\n boxRelPath: 'auth.json',\n boxAbsPath: `${CODEX_BOX_DIR}/auth.json`,\n hostBackup: join(STATE_DIR, 'codex-credentials.json'),\n cloudMountPath: '/home/vscode/.agentbox-creds/codex',\n cloudSubpath: 'codex/',\n realShape: 'nonempty-json',\n },\n forwardedEnvKeys: ['OPENAI_API_KEY'],\n boxRunEnv: {},\n // Codex auto-discovers `~/.codex/hooks.json` and accumulates its hooks with\n // any the user defined, so seeding this never disables the user's own.\n seeds: [\n {\n bakedPath: CODEX_HOOKS_PATH,\n destRel: 'hooks.json',\n sharedAsset: 'agentbox-codex-hooks.json',\n label: 'Codex activity hooks',\n },\n ],\n // Codex will not load the seeded hooks without these:\n // - `--enable hooks` opts into lifecycle-hook loading (the feature was\n // renamed `codex_hooks` -> `hooks` in 0.134.0).\n // - `--dangerously-bypass-hook-trust` skips the in-TUI \"trust these hooks?\"\n // dialog that would otherwise block startup on every fresh box. The hooks\n // are AgentBox-managed and pre-vetted; the user never sees them.\n // The flag makes codex print a cosmetic \"…is enabled\" warning at startup and\n // there is NO option to silence just that one. Persisting trust hashes in\n // config.toml instead is worse: the hash is an opaque codex-internal digest\n // tied to both the file content and the codex version, and a mismatch turns\n // the cosmetic warning into a *blocking* \"Hooks need review\" dialog.\n launchFlags: ['--enable', 'hooks', '--dangerously-bypass-hook-trust'],\n caps: { resume: true, teleport: 'full', activitySource: ['hooks', 'scraper'] },\n // Box->host: a flat list under the single config root.\n pull: { items: [{ group: 'data', names: ['config.toml', 'auth.json', 'prompts'] }] },\n};\n","/**\n * The fourth agent.\n *\n * It exists to answer one question with a number instead of an opinion: what\n * does adding an agent to AgentBox actually cost? Every layer that still needs\n * hand-wiring fails loudly while this package is present, so the remaining cost\n * is a test result rather than a claim.\n *\n * `hidden: true` keeps it out of pickers, `--help` and the bake list — it is a\n * canary, not a supported agent. It is real everywhere else: the registry\n * resolves it, the machinery iterates it, and `agentbox example` builds a box\n * that works.\n *\n * Its \"agent\" is a login shell. That is deliberate: `bash` is in every base\n * image, so the package proves the whole seam — install probe, config volume,\n * tmux session, activity probe, attach — with no network, no npm package, and\n * nothing that can rot. Swap `binary`/`install` and it becomes a real agent\n * without touching anything else.\n *\n * Imports only the two dependency-free leaves; see `spec-purity.test.ts`.\n */\n\nimport { BOX_HOME, BOX_CREDS_DIR, agentDirPrelude } from '@agentbox/core';\nimport type { AgentSyncSpec } from '@agentbox/core';\nimport { join } from 'node:path';\nimport { STATE_DIR } from '@agentbox/config';\n\nconst EXAMPLE_BOX_DIR = `${BOX_HOME}/.agentbox-example`;\n\nexport const exampleSpec: AgentSyncSpec = {\n id: 'example',\n aliases: [],\n hidden: true,\n sessionName: 'example',\n // Always present in the base image, so `command -v` succeeds and the install\n // recipe never runs. A real agent names its own CLI here.\n binary: 'bash',\n install: {\n // Never reached (the probe finds bash), but a spec must declare how it would\n // install, and `true` is the honest no-op.\n recipe: { kind: 'exec', script: 'true' },\n runAs: 'root',\n postInstall: [...agentDirPrelude([EXAMPLE_BOX_DIR], 'example')].join(' && '),\n },\n dockerVolume: 'agentbox-example-config',\n staticPaths: [\n {\n hostHomeRel: ['.agentbox-example'],\n boxDir: EXAMPLE_BOX_DIR,\n },\n ],\n credential: {\n boxRelPath: 'auth.json',\n boxAbsPath: `${EXAMPLE_BOX_DIR}/auth.json`,\n hostBackup: join(STATE_DIR, 'example-credentials.json'),\n cloudMountPath: `${BOX_CREDS_DIR}/example`,\n cloudSubpath: 'example/',\n realShape: 'nonempty-json',\n },\n forwardedEnvKeys: [],\n boxRunEnv: {},\n caps: {\n resume: false,\n teleport: 'stub',\n teleportStubReason:\n 'The example agent is a seam canary with no conversation to teleport. Run `agentbox example` to start a fresh box.',\n // Reports nothing: no hooks, no plugin, and ctl ships no scraper for it. ctl\n // therefore skips probing it rather than reporting a permanent `unknown`.\n activitySource: [],\n },\n // Declared because `staticPaths` is: an agent that can be pushed into a box\n // must say how it comes back out, or `agentbox download example` silently\n // does nothing. Data, not code -- which is the point.\n pull: { items: [{ group: 'data', names: ['auth.json'] }] },\n};\n","/**\n * OpenClaw's registry row — the first `surface: 'service'` agent.\n *\n * Everything that makes it different from the four TUI rows is on `caps`,\n * `service` and `configRender`, which is the point of Phase 2/3: nothing\n * branches on the id. What the row says is \"this agent is a daemon the box\n * hosts\": ctl's supervisor runs it, its readiness is an HTTP probe rather than a\n * tmux session, and the box's web URL is its Control UI.\n *\n * Imports only the two dependency-free leaves, like every other spec (see\n * `spec-purity.test.ts`).\n *\n * The shape below is what the Phase 0 PoC measured, not what the plan assumed —\n * see `docs/plans/service-boxes-plan.md` §\"Established facts\". Three of its\n * findings are load-bearing here:\n *\n * - the gateway binds LOOPBACK and generates its own auth token, so there is no\n * `gateway.bind` override and no auto-secret. ctl's `WebProxy` forwards\n * `:80 -> 127.0.0.1:18789` inside the same container, which is both\n * sufficient and strictly safer than widening the bind.\n * - `openclaw config patch --stdin` is a validated recursive merge openclaw\n * performs on its own file, so `configRender` delegates to it rather than\n * hand-rolling a merge.\n * - `openclaw config get gateway.auth.token` answers `__OPENCLAW_REDACTED__`,\n * so `service.urlFields` reads the token out of the raw JSON instead.\n *\n * INSTALL IS ON DEMAND, NEVER BAKED. `npm i -g openclaw` lands ~893 MB — a ~29%\n * increase on the 3.1 GB base image. Baking it would also shift the build-context\n * fingerprint and stale every provider's base snapshot.\n */\n\nimport { BOX_HOME, BOX_USER, IDENTITY_RULES_SENTINEL, agentDirPrelude } from '@agentbox/core';\nimport type { AgentSyncSpec } from '@agentbox/core';\nimport { codexSpec } from './codex.js';\n\n/** OpenClaw's state root: config, sqlite state, per-agent dirs, migrations. */\nconst OPENCLAW_BOX_DIR = `${BOX_HOME}/.openclaw`;\n/**\n * Where openclaw keeps its auth-profile key: `~/.config/openclaw`, OUTSIDE the\n * state dir, and empty after a plain `onboard`.\n *\n * It is relocated into the state root as `xdg/` and symlinked back, the same\n * arrangement opencode uses for its config dir — one docker volume can only be\n * mounted once, and a second dir under `$HOME` would otherwise live in the\n * container's writable layer and be lost on re-create.\n */\nconst OPENCLAW_XDG_SUBPATH = 'xdg';\nconst OPENCLAW_XDG_BOX_DIR = `${OPENCLAW_BOX_DIR}/${OPENCLAW_XDG_SUBPATH}`;\nconst OPENCLAW_XDG_LINK = `${BOX_HOME}/.config/openclaw`;\n/** Loopback port the gateway binds. Named once — probe, expose and URL all read it. */\nconst GATEWAY_PORT = 18789;\n\n/**\n * Where AgentBox keeps the skills it owns, and the box \"system prompt\" it\n * derives. Both are AgentBox's, not the user's.\n *\n * The skill lives OUTSIDE the workspace on purpose: `skills.load.extraDirs` is\n * documented for exactly this (\"shared skill packs ... without copying them\n * into the OpenClaw workspace\"), at LOWEST precedence, so a user skill of the\n * same name wins. Nothing about it travels with `agentbox clone`.\n *\n * The prompt file cannot do the same. openclaw's `bootstrap-extra-files` hook\n * resolves every path from the workspace and REALPATH-CHECKS it, so a symlink\n * out is refused, and only the six canonical bootstrap basenames are accepted —\n * hence a real `AGENTS.md`, inside `/workspace`, under a namespaced dir.\n */\nconst AGENTBOX_SKILLS_DIR = '/opt/agentbox/skills';\n/** Baked into every provider's base image; see each `install-box.sh`. */\nconst BAKED_SETUP_SKILL = '/usr/local/share/agentbox/setup-guide.md';\n/** The identity wizard, baked the same way. Absent on a base baked before it. */\nconst BAKED_IDENTITY_SKILL = '/usr/local/share/agentbox/identity-skill.md';\n/**\n * What the identity wizard writes into `agentbox.yaml`, and therefore how we ask\n * \"has this bot done it yet?\". A comment rather than a key so the check is a\n * plain grep and needs no yaml parser inside a shell script — and so the user\n * can see, in their own file, what wrote it.\n */\nconst IDENTITY_SENTINEL = IDENTITY_RULES_SENTINEL;\n/** The workspace file the sentinel lives in. */\nconst WORKSPACE_YAML = '/workspace/agentbox.yaml';\n/** The per-provider box facts. Claude reads it directly; codex folds it in too. */\nconst BOX_FACTS = '/etc/claude-code/CLAUDE.md';\nconst AGENTBOX_CTX_DIR = '/workspace/.agentbox';\n/** First line of the generated file: makes a re-run idempotent, and says whose it is. */\nconst CTX_SENTINEL = '<!-- agentbox:box-facts (generated every boot; edit AGENTS.md instead) -->';\n\n/** Scratch path for the merge program; removed again as soon as it has run. */\nconst MERGE_PROGRAM_PATH = '/tmp/agentbox-openclaw-config-merge.cjs';\n\n/** Workspace-relative path of the generated prompt file, as the hook names it. */\nconst CTX_REL_PATH = '.agentbox/AGENTS.md';\n\n/**\n * Build the config patch AgentBox applies, as a MEMBERSHIP assertion on the two\n * arrays rather than a value for them.\n *\n * Both keys are arrays, and `openclaw config patch` replaces an array wholesale\n * rather than merging it — so sending a literal `[ourDir]` every boot would be a\n * silent data-loss bug, not merely rude. `openclaw-render` re-sends only the\n * overlay keys that CHANGED since its last render, so a user value that is\n * stable (in `agentbox.yaml`, or set in the box with `openclaw config set`)\n * would not be re-asserted afterwards: it would survive the first boot and\n * vanish on the second.\n *\n * Reading the current value and unioning ours in keeps AgentBox's claim to the\n * narrowest true one — \"our skills dir is on the list, our prompt file is in the\n * bootstrap set\" — and leaves every other entry, and every neighbouring key,\n * alone. An explicit `enabled: false` on the hook is preserved too: disabling\n * the box facts is a choice the user is allowed to make and have stick.\n *\n * Emitted as a program rather than a static JSON blob because the merge has to\n * happen IN the box, against that box's live config. node is guaranteed there —\n * openclaw is a node application.\n *\n * It is handed the current values rather than reading `openclaw.json` itself.\n * That file is JSON5 — openclaw reads a config with a `//` comment in it quite\n * happily, and `JSON.parse` throws on the same file (both verified in a box) —\n * so parsing it here would see `{}` for a commented config and clobber exactly\n * the arrays this program exists to preserve. `openclaw config get` is the\n * tool's own reader, and it also resolves defaults, profiles and env overrides.\n *\n * An unreadable value is treated as UNSET, which is only safe because the caller\n * gates the whole step on `openclaw config validate`: openclaw prints nothing\n * and exits 1 both for a path that is merely unset and for one it cannot read,\n * so the exit code alone cannot separate a fresh box from a broken config.\n */\nexport const OPENCLAW_CONFIG_MERGE_PROGRAM = `\nconst [skillDir, ctxPath, rawDirs, rawEntries, rawHooksEnabled] = process.argv.slice(2);\nconst read = (s) => {\n try {\n return JSON.parse(s);\n } catch {\n return undefined;\n }\n};\nconst withMember = (arr, v) =>\n Array.isArray(arr) ? (arr.includes(v) ? arr.slice() : [...arr, v]) : [v];\nconst entry = read(rawEntries)?.['bootstrap-extra-files'] ?? {};\nprocess.stdout.write(\n JSON.stringify({\n skills: { load: { extraDirs: withMember(read(rawDirs), skillDir) } },\n hooks: {\n internal: {\n enabled: read(rawHooksEnabled) === false ? false : true,\n entries: {\n 'bootstrap-extra-files': {\n ...entry,\n enabled: entry.enabled === false ? false : true,\n paths: withMember(entry.paths, ctxPath),\n },\n },\n },\n },\n }),\n);\n`;\n\n/** Single-quote a value for the POSIX shell. */\nfunction sq(v: string): string {\n return `'${v.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * Appended to the generated box facts while this workspace has no identity\n * rule-set. It is a prompt, so it says what is at stake rather than naming a\n * command: the agent decides when to act on it.\n */\nconst IDENTITY_NUDGE_TEXT = [\n '',\n '## Your identity is not portable yet',\n '',\n 'This workspace declares no `identity` replacement rules, so a bot spawned',\n 'from it with `agentbox clone` would introduce itself with YOUR name and',\n 'answer to YOUR handle. On your first turn, follow the `agentbox-identity`',\n 'skill once to write them, then carry on with whatever you were asked.',\n '',\n].join('\\n');\n\n/**\n * The model-auth task: turn a borrowed Codex login into OpenClaw's own OpenAI\n * OAuth profile. Reads the file the host seeded at codex's OWN credential path\n * (`AgentSyncSpec.modelAuth.borrows`), so nothing here knows how the host chose\n * or moved it.\n *\n * Every step below was measured on openclaw 2026.9.3, not read from the plan:\n *\n * - The auth store is SQLite (`agents/<id>/agent/openclaw-agent.sqlite`); the\n * retired `auth-profiles.json` / `credentials/oauth.json` are never read at\n * runtime, so writing one is not a seam.\n * - `openclaw migrate apply codex ... --item auth:openai` is the supported,\n * non-interactive import of a Codex CLI home. It lives in the official\n * `@openclaw/codex` plugin (ClawHub), which is also the harness the fresh\n * onboard's default model (`openai/gpt-5.6-sol`) runs on — so installing it\n * completes the default rather than changing it. The install is ~17s and\n * lands in the config volume, so it is paid once per box.\n * - A bare `~/.codex/auth.json` is enough for `models status` to SHOW a\n * bootstrapped `openai:default` — reported as `source: store`, status `ok`,\n * indistinguishable from a real row — but a turn on it fails with\n * `selected_auth_profile_unavailable`. So OpenClaw's own status is NOT the\n * gate for \"already imported\"; the import is what makes the profile real.\n * - The import applies on every run. After it OpenClaw owns the profile and\n * refreshes it in its own store, and OpenAI does not invalidate the prior\n * refresh token on rotation (two boxes seeded from one host file refreshed\n * independently and every chain, the host's included, stayed valid). So a\n * re-import is never needed for freshness, and would only replace the box's\n * own newer chain with the seed's.\n *\n * Hence the gate is the SEED itself: a hash of the file, recorded beside\n * `.agentbox-overlay.json` once an import succeeds. Unchanged file, no work;\n * a re-pushed login (the host logged in again) imports again. Idempotent and\n * exit 0 on every \"nothing to do\": no seeded file, a file that is not a Codex\n * login, or one already imported. The gateway is ordered after this task\n * (`needs`), so the plugin it installs is loaded on the gateway's first start\n * rather than needing a restart.\n */\nfunction buildModelAuthScript(): string {\n const auth = codexSpec.credential!.boxAbsPath;\n const home = auth.slice(0, auth.lastIndexOf('/'));\n return [\n 'set -u',\n `auth=${sq(auth)}`,\n `marker=${sq(MODEL_AUTH_MARKER)}`,\n 'if [ ! -s \"$auth\" ]; then echo \"openclaw-model-auth: no borrowed Codex login at $auth\"; exit 0; fi',\n // Shape gate, so a half-written or API-key-only file is \"nothing to\n // ingest\" rather than a failed import.\n `if ! node -e ${sq(MODEL_AUTH_IS_CODEX_LOGIN)} \"$auth\"; then echo \"openclaw-model-auth: $auth is not a Codex ChatGPT login\"; exit 0; fi`,\n 'seen=$(sha256sum \"$auth\" | cut -d\" \" -f1)',\n 'if [ -f \"$marker\" ] && [ \"$(cat \"$marker\")\" = \"$seen\" ]; then',\n ' echo \"openclaw-model-auth: this Codex login is already imported\"',\n ' exit 0',\n 'fi',\n // The plugin owns both the import command and the harness the default\n // model runs on.\n `if [ ! -d ${sq(`${OPENCLAW_BOX_DIR}/extensions/codex`)} ]; then`,\n ' echo \"openclaw-model-auth: installing the @openclaw/codex plugin\"',\n ' openclaw plugins install clawhub:@openclaw/codex || exit 0',\n 'fi',\n 'echo \"openclaw-model-auth: importing the Codex login into the OpenClaw auth store\"',\n // `--no-backup --force`: the pre-migration archive would snapshot a state\n // dir that is fresh on the boot this runs, and the migration report is\n // still written. `--item auth:openai` keeps skills/plugins/config out.\n `if openclaw migrate apply codex --from ${sq(home)} --include-secrets --item auth:openai --yes --no-backup --force; then`,\n ' printf %s \"$seen\" > \"$marker\" && chmod 600 \"$marker\"',\n 'fi',\n 'exit 0',\n ].join('\\n');\n}\n\n/** Hash of the last seed imported. Beside the overlay record: AgentBox-owned, per box. */\nconst MODEL_AUTH_MARKER = `${OPENCLAW_BOX_DIR}/.agentbox-model-auth.sha256`;\n\n/** argv[1] is the file. Exit 0 iff it is a Codex ChatGPT login with a refresh token. */\nconst MODEL_AUTH_IS_CODEX_LOGIN = `\nconst j = JSON.parse(require('fs').readFileSync(process.argv[1], 'utf8'));\nprocess.exit(typeof j?.tokens?.refresh_token === 'string' && j.tokens.refresh_token.length > 0 ? 0 : 1);\n`;\n\n/**\n * Teach the box's gateway where it is running.\n *\n * Runs on EVERY supervisor start, not once: the prompt file sits in the\n * workspace, so `agentbox clone` carries a copy of the SOURCE box's facts into\n * the new one. Regenerating overwrites it from this box's own `/etc/claude-code`\n * before the gateway ever reads it — which is what makes a clone, a re-provision\n * or a move to another provider self-correcting rather than quietly wrong.\n *\n * Best-effort throughout: none of this is worth failing a box over, so every\n * step is guarded and the task still exits 0 on a base too old to carry the\n * baked files.\n */\nfunction buildAgentboxContextScript(): string {\n return [\n 'set -u',\n // The skill. COPIED, not symlinked, and as `<name>/SKILL.md` rather than a\n // flat `.md` — both measured against openclaw 2026.9.2, which discovered\n // neither other shape: it takes skills as directories, and rejects a symlink\n // whose real target sits outside the source root unless that target is in\n // `skills.load.allowSymlinkTargets`. Re-copied every boot, so a re-baked\n // base image still propagates.\n ...[\n [BAKED_SETUP_SKILL, 'agentbox-setup'],\n [BAKED_IDENTITY_SKILL, 'agentbox-identity'],\n ].flatMap(([src, name]) => [\n `if [ -f ${src} ]; then`,\n ` D=${AGENTBOX_SKILLS_DIR}/${name}`,\n ' (sudo -n mkdir -p \"$D\" 2>/dev/null || mkdir -p \"$D\") || true',\n ` (sudo -n install -m 0644 ${src} \"$D/SKILL.md\" 2>/dev/null ||`,\n ` install -m 0644 ${src} \"$D/SKILL.md\") || true`,\n 'fi',\n ]),\n // The box facts, written atomically so a reader never sees a half file.\n // The nudge text, as a shell variable so the printf below stays a single\n // short line and the prose can carry the punctuation it needs.\n `IDENTITY_NUDGE=${sq(IDENTITY_NUDGE_TEXT)}`,\n `if [ -f ${BOX_FACTS} ]; then`,\n ` mkdir -p ${AGENTBOX_CTX_DIR} || true`,\n ` TMP=${AGENTBOX_CTX_DIR}/AGENTS.md.agentbox.tmp`,\n ' {',\n ` printf '%s\\\\n\\\\n' '${CTX_SENTINEL}'`,\n ` cat ${BOX_FACTS}`,\n // The identity nudge. Conditional on the workspace NOT already declaring the\n // rule-set, and regenerated every boot, so it disappears by itself once the\n // bot has written one -- the yaml is the only state, and there is no marker\n // to go stale. A supervisor task cannot do this job: writing these rules\n // means reading your own SOUL.md and deciding which words are you, which is\n // a judgement only the agent can make, on a turn only the agent can take.\n ` if [ -f ${BAKED_IDENTITY_SKILL} ] && ! grep -qs '${IDENTITY_SENTINEL}' ${WORKSPACE_YAML} 2>/dev/null; then`,\n ` printf '%s' \"$IDENTITY_NUDGE\"`,\n ' fi',\n ' } > \"$TMP\" && mv \"$TMP\" ' + `${AGENTBOX_CTX_DIR}/AGENTS.md || true`,\n 'fi',\n // One validated merge rather than several `config set` calls. The patch is\n // COMPUTED from the box's live config (see the program's own comment) so the\n // two arrays gain our entry instead of being replaced by it.\n //\n // Gated on openclaw's own validator. A `config get` prints nothing and exits\n // 1 both for a value that is merely unset and for one it cannot read, so\n // without this gate a broken config would look like a fresh box and be\n // overwritten with just our entry. With the config known good, an empty read\n // means genuinely unset, which is the one case where writing ours alone is\n // right.\n 'if openclaw config validate >/dev/null 2>&1; then',\n ` DIRS=$(openclaw config get 'skills.load.extraDirs' 2>/dev/null || true)`,\n // The whole `entries` object, by plain dot path, and the one key is picked out\n // in the program. Reading `entries['bootstrap-extra-files']` directly does\n // work on 2026.9.2, but it leans on the CLI's bracket-and-quote parsing for a\n // key with a hyphen in it — and a get that fails here is indistinguishable\n // from unset, which would silently replace the user's `paths`.\n ` ENTRIES=$(openclaw config get 'hooks.internal.entries' 2>/dev/null || true)`,\n ` HOOKS=$(openclaw config get 'hooks.internal.enabled' 2>/dev/null || true)`,\n // Written to a file first: a quoted heredoc keeps the program safe from the\n // shell, and it avoids process substitution, which some provider bases have\n // no `/dev/fd` for.\n ` PROG=${MERGE_PROGRAM_PATH}`,\n ' cat > \"$PROG\" <<\\'AGENTBOX_MERGE_EOF\\'',\n OPENCLAW_CONFIG_MERGE_PROGRAM.trim(),\n 'AGENTBOX_MERGE_EOF',\n ` node \"$PROG\" ${AGENTBOX_SKILLS_DIR} ${CTX_REL_PATH} \"$DIRS\" \"$ENTRIES\" \"$HOOKS\" |`,\n ' openclaw config patch --stdin >/dev/null || true',\n ' rm -f \"$PROG\" || true',\n 'fi',\n 'exit 0',\n ].join('\\n');\n}\n\nexport const openclawSpec: AgentSyncSpec = {\n id: 'openclaw',\n aliases: [],\n // The tmux session `service.repl` opens on demand. NOT an agent session: the\n // gateway runs under ctl whether or not anyone is attached, and\n // `activitySource: []` still tells ctl not to probe this name — see `caps`.\n // Nothing creates it until someone runs `agentbox attach`.\n sessionName: 'openclaw',\n binary: 'openclaw',\n install: {\n // `allowScripts` is load-bearing: npm >= 12 blocks lifecycle scripts by\n // default and openclaw's own do real setup work. It covers openclaw's\n // scripts ONLY -- four dependency scripts (koffi, tree-sitter-bash,\n // protobufjs, @google/genai) stay skipped. The PoC confirmed openclaw\n // installs, launches and serves without them; a feature routed through one\n // of those deps may be degraded.\n recipe: { kind: 'npm', package: 'openclaw', allowScripts: true },\n runAs: 'root',\n postInstall: [\n // EVERY dir, not just the leaf, for the reason pi's row documents: GNU\n // `install -d -o u -g g a/b` applies ownership to the FINAL component\n // only, so a nested path alone leaves the parent root-owned and the later\n // static-config stage (which runs as the box user) cannot write it.\n // No creds-subdir argument: with no `credential` declared there is no\n // subpath of the shared credentials volume to create a mount point for.\n ...agentDirPrelude([OPENCLAW_BOX_DIR, OPENCLAW_XDG_BOX_DIR, `${BOX_HOME}/.config`]),\n // Point `~/.config/openclaw` into the state root so it rides the one\n // config volume. `ln -sfn` onto an existing DIRECTORY would create the\n // link inside it, so the real dir goes first -- it is either absent or\n // the empty one openclaw/our own prelude made.\n `rm -rf ${OPENCLAW_XDG_LINK}`,\n `ln -sfn ${OPENCLAW_XDG_BOX_DIR} ${OPENCLAW_XDG_LINK}`,\n `chown -h ${BOX_USER}:${BOX_USER} ${OPENCLAW_XDG_LINK}`,\n ].join(' && '),\n },\n dockerVolume: 'agentbox-openclaw-config',\n staticPaths: [\n {\n hostHomeRel: ['.openclaw'],\n boxDir: OPENCLAW_BOX_DIR,\n // Push excludes. Everything here is IDENTITY, and openclaw does not\n // support two gateways sharing one: pushing the host's `openclaw.json`\n // into a box would hand the box the host gateway's token and channel\n // pairings, which is exactly the failure `clone`'s fresh-identity rule\n // exists to prevent. What DOES carry in is the user's content —\n // `agents/`, and anything else they keep beside it.\n //\n // `tmp` is excluded for a second reason: it holds lock sqlites under a\n // directory whose name is keyed by the box user's uid, which differs per\n // provider (docker 1000, vercel 1001, e2b 1002).\n exclude: [\n 'openclaw.json',\n 'openclaw.json.bak',\n 'config-journal-fingerprint.key',\n '.agentbox-overlay.json',\n '.agentbox-model-auth.sha256',\n // Per-gateway exec-approval state, plus the `.migrated.<hash>` archives\n // doctor leaves beside it. MEASURED: the host's copy from an older\n // openclaw rode the cloud static push into a 2026.9.3 box, and every\n // turn there failed with \"Legacy exec approvals exist ... run doctor\".\n 'exec-approvals.json*',\n 'state',\n 'migration',\n 'tmp',\n ],\n },\n // Relocated under the state root rather than given its own `boxDir`: one\n // docker volume, one mount, and the symlink above makes the box path work.\n // Same shape as opencode's config entry.\n {\n hostHomeRel: ['.config', 'openclaw'],\n boxDir: OPENCLAW_BOX_DIR,\n relocToSubpath: OPENCLAW_XDG_SUBPATH,\n },\n ],\n // NO `credential`: openclaw has no host-side credential to sync. Its gateway\n // token is generated per box by `openclaw onboard` and must never leave that\n // box, so there is no host backup to read, nothing to push at create, no\n // subpath of the shared credentials volume to reserve, and no credential watch.\n //\n // Pointing this at `openclaw.json` to fill the slot would be harmful, not\n // redundant: the credential watch is FANOUT by contract\n // (`buildAgentDescriptors` emits `sync: 'fanout'` for every credential it\n // sees), so every other openclaw box would receive box #1's gateway identity\n // and channel pairings — the multi-tenancy failure openclaw forbids, and the\n // one `clone`'s fresh-identity rule exists to prevent.\n //\n // Channel tokens are real secrets, but they ride a `carry:` entry into a 0600\n // env file and the overlay references them by name; AgentBox never holds them.\n //\n // A MODEL-PROVIDER login is the one host secret it does consume, and that is\n // `modelAuth`, not `credential`: the host seeds codex's file at codex's own\n // path and the `openclaw-model-auth` task below imports it. Absent\n // `credential` plus present `modelAuth.sources` is the shape for a consumer.\n modelAuth: {\n sources: [\n { kind: 'agent', agent: 'codex', label: 'Your Codex login (ChatGPT subscription OAuth)' },\n ],\n ingest: { kind: 'serviceTask', task: 'openclaw-model-auth' },\n // The one row that asks: a service agent has no TUI to sign in through, so\n // an unanswered create leaves a daemon with no model provider at all.\n promptOnCreate: true,\n },\n settings: [\n {\n key: 'modelAuth',\n type: 'enum-list',\n enumValues: ['none', 'codex'],\n default: 'none',\n description:\n 'Which host model-provider logins a new OpenClaw box is seeded with, comma-separated. `codex` copies your Codex (ChatGPT) OAuth login into the box, where OpenClaw imports it and refreshes it independently from then on. `none` leaves model auth for you to configure in the box, and is only valid on its own. `--model-auth` overrides per create.',\n // Seeded at create, never baked: the file rides the carry step.\n },\n ],\n forwardedEnvKeys: [],\n boxRunEnv: {\n // Honoured by `onboard`, which writes it to `agents.defaults.workspace`\n // (PoC #5). Set on the box env so a hand-run `openclaw` agrees with the\n // service unit.\n OPENCLAW_WORKSPACE_DIR: '/workspace',\n },\n service: {\n name: 'openclaw',\n command: 'openclaw gateway',\n restart: 'always',\n needs: ['openclaw-render'],\n // `/healthz` answers 200 and the gateway reaches ready in ~1s (PoC #8).\n readyWhen: { http: `http://127.0.0.1:${String(GATEWAY_PORT)}/healthz` },\n expose: { port: GATEWAY_PORT, as: 80 },\n // MEASURED on a live box, not assumed: the gateway answers 200 with the\n // Control UI on a direct connection and `403 proxy_attribution_required`\n // through Portless. Any ONE forwarded header does it -- `X-Forwarded-For`,\n // `X-Forwarded-Proto` and `Forwarded` each trigger it independently\n // (openclaw's `hasForwardedRequestHeaders` matches every `x-forwarded-*`).\n // `/healthz` is exempt, which is why every smoke test before this passed.\n //\n // `gateway.trustedProxies` does not rescue it. Configuring the proxy is\n // necessary but not sufficient: openclaw also requires the FORWARDED CLIENT\n // to be non-loopback (`ingress-attribution.ts`), and a browser on the same\n // machine as the proxy never is. That is deliberate -- it stops a remote\n // client claiming the loopback auth exemption by hopping through a proxy --\n // so there is no configuration that makes the proxied path work.\n rejectsProxyHeaders: true,\n // `tui` connects to the gateway this box is already running. `chat` and\n // `terminal` are aliases for `tui --local`, which start a SECOND embedded\n // runtime and ignore that gateway — measured, not assumed. No token or URL\n // argument: it defaults to the local gateway, and a loopback request with\n // no forwarded headers is `direct-local` to openclaw's own auth.\n repl: ['openclaw', 'tui'],\n tasks: [\n {\n name: 'openclaw-onboard',\n // `runOnce: 'marker'` keyed by the resolved command: a warm boot skips\n // it, so the box keeps the identity onboard generated the first time.\n runOnce: 'marker',\n command:\n 'openclaw onboard --non-interactive --accept-risk --mode local ' +\n '--skip-channels --skip-health --no-install-daemon',\n },\n {\n // The borrowed model login, if the host seeded one. After onboard so\n // the agent dir and default model exist; before the gateway so the\n // plugin it may install is loaded on the first start. No `runOnce`:\n // it decides for itself, and a re-run is a no-op once imported.\n name: 'openclaw-model-auth',\n command: buildModelAuthScript(),\n needs: ['openclaw-onboard'],\n },\n {\n // Everything AgentBox owns in this box: the skill root outside the\n // workspace, the derived box facts inside it, and the two config keys\n // that make openclaw read both. No `runOnce` — see the builder's doc.\n name: 'openclaw-agentbox-env',\n command: buildAgentboxContextScript(),\n needs: ['openclaw-model-auth'],\n },\n {\n name: 'openclaw-render',\n command: 'agentbox-ctl agent render openclaw',\n // After the AgentBox keys, so the user's overlay is the last word on any\n // key they and we both name.\n needs: ['openclaw-agentbox-env'],\n },\n ],\n // The Control UI asks for the gateway token on first load. `openclaw config\n // get gateway.auth.token` redacts it (PoC), so this used to read the raw\n // `openclaw.json` -- which meant depending on where openclaw keeps its\n // secrets. `dashboard --json` is the interface it offers for exactly this,\n // and it prints the whole sign-in URL:\n //\n // {\"ok\":true,\"url\":\"http://127.0.0.1:18789/#token=…\",\"httpUrl\":…}\n //\n // `--no-open` because the daemon would otherwise try to launch a browser\n // INSIDE the box; no `--yes`, because a read must never be the thing that\n // installs or starts the gateway. Only the fragment is kept: the rest of\n // that URL is the gateway's own loopback address, and the host reaches this\n // box on a different one.\n urlFields: [\n {\n label: 'token',\n command: ['openclaw', 'dashboard', '--json', '--no-open'],\n jsonPath: 'url',\n fromUrlFragment: 'token',\n fragmentKey: 'token',\n },\n ],\n },\n configRender: {\n file: `${OPENCLAW_BOX_DIR}/openclaw.json`,\n overlayKey: 'openclaw',\n applyCmd: 'openclaw config patch --stdin',\n dryRunFlag: '--dry-run',\n validate: 'openclaw config validate',\n },\n caps: {\n surface: 'service',\n resume: false,\n teleport: 'stub',\n teleportStubReason:\n 'OpenClaw is a gateway the box hosts, not a conversation you attach to. Open its Control UI with `agentbox openclaw url`.',\n // A daemon reports no agent activity, and ctl skips probing it rather than\n // reporting a permanently-`unknown` session.\n activitySource: [],\n },\n // Box->host. `agents/` only: per-agent definitions are independent items the\n // user authors in the box and may want on the host, and the pull is additive\n // and never overwrites. Everything else under the state root is identity\n // (`openclaw.json`, the journal key) or live state (`state/*.sqlite*`), and\n // pulling either onto the host would mix one gateway's identity into another.\n // `onboard --mode local` writes these into OPENCLAW_WORKSPACE_DIR, which is the\n // project workspace — verified live. It does NOT overwrite one seeded from the\n // host, so a file the user already had stays theirs.\n clone: {\n // `onboard` writes all four, so a clone would otherwise carry the SOURCE\n // bot's scaffolding. These two are regenerated for the new box as-is.\n drop: ['AGENTS.md', 'USER.md'],\n // These two ARE the bot's character, and the user wrote most of them. A\n // clone keeps the text and swaps the name through the `identity` rule-set.\n render: ['SOUL.md', 'IDENTITY.md'],\n // The channel tokens. Keyed by box name so two bots from one workspace\n // never share a Telegram/Discord identity -- which is the failure that\n // makes a spawned bot answer as the bot it was spawned from.\n perBoxCarry: [\n {\n src: '~/.agentbox/openclaw/{{AGENTBOX_BOX_NAME}}.env',\n dest: '~/.openclaw/.env',\n mode: 0o600,\n optional: true,\n },\n ],\n },\n pull: { categories: ['agents'] },\n // A backup KEEPS everything the push excludes -- `openclaw.json` IS the bot,\n // and a restore that mints a new gateway token has restored nothing. Only the\n // lock dir is dropped, because its name carries the box user's uid and that\n // differs per provider (docker 1000, vercel 1001, e2b 1002).\n stateBackup: { exclude: ['tmp'] },\n};\n","/**\n * OpenCode's registry row — the DATA half of this package.\n *\n * Imports only the two dependency-free leaves (`@agentbox/core` for the\n * contract, `@agentbox/config` for the host state dir) on purpose: this entry is read by\n * the agent registry, which `sandbox-core` depends on, which in turn everything\n * depends on. Anything heavier here is a dependency cycle. See this package's\n * `tsup.config.ts`.\n */\n\nimport { join } from 'node:path';\nimport { STATE_DIR } from '@agentbox/config';\nimport { BOX_USER, BOX_HOME, BOX_CREDS_DIR, agentDirPrelude } from '@agentbox/core';\nimport type { AgentSyncSpec } from '@agentbox/core';\n\nimport { buildCodexImportScript, codexImportMarker } from './_codex-import.js';\n\nconst OPENCODE_BOX_DIR = `${BOX_HOME}/.local/share/opencode`;\n/** Baked alongside the setup guide: opencode's activity-reporting plugin. */\nconst OPENCODE_PLUGIN_PATH = '/usr/local/share/agentbox/opencode-agentbox-plugin.js';\n\nexport const opencodeSpec: AgentSyncSpec = {\n id: 'opencode',\n aliases: [],\n sessionName: 'opencode',\n binary: 'opencode',\n install: {\n recipe: { kind: 'npm', package: 'opencode-ai' },\n runAs: 'root',\n postInstall: [\n ...agentDirPrelude([OPENCODE_BOX_DIR], 'opencode'),\n `ln -sfn ${BOX_CREDS_DIR}/opencode/auth.json ${OPENCODE_BOX_DIR}/auth.json`,\n `chown -R ${BOX_USER}:${BOX_USER} ${BOX_HOME}/.local`,\n `chown -h ${BOX_USER}:${BOX_USER} ${OPENCODE_BOX_DIR}/auth.json`,\n ].join(' && '),\n },\n dockerVolume: 'agentbox-opencode-config',\n // The three-XDG-dir layout as DATA: the generic seed loop reproduces\n // `ensureOpencodeVolume`'s three-source rsync (data + config→config +\n // state→.state/opencode newest-wins) with no tool-specific control flow.\n staticPaths: [\n {\n hostHomeRel: ['.local', 'share', 'opencode'],\n boxDir: OPENCODE_BOX_DIR,\n // Push excludes for the data tree (single source of truth; consumed by\n // `agentPushExcludes`, which also derives the credential file and the\n // live-database deny). The rest is host-only runtime state.\n exclude: ['storage', 'log', 'project', 'cache', 'bin', 'repos', 'snapshot', 'config'],\n },\n { hostHomeRel: ['.config', 'opencode'], boxDir: OPENCODE_BOX_DIR, relocToSubpath: 'config' },\n {\n hostHomeRel: ['.local', 'state', 'opencode'],\n boxDir: OPENCODE_BOX_DIR,\n relocToSubpath: '.state/opencode',\n update: true,\n exclude: ['locks'],\n // Two-way, per-box state (the selected model). It ships via its own\n // newest-wins stager, never baked into a shared snapshot.\n stagedAs: 'state',\n },\n ],\n credential: {\n boxRelPath: 'auth.json',\n boxAbsPath: `${OPENCODE_BOX_DIR}/auth.json`,\n hostBackup: join(STATE_DIR, 'opencode-credentials.json'),\n cloudMountPath: '/home/vscode/.agentbox-creds/opencode',\n cloudSubpath: 'opencode/',\n realShape: 'nonempty-json',\n },\n forwardedEnvKeys: [\n 'ANTHROPIC_API_KEY',\n 'OPENAI_API_KEY',\n 'OPENROUTER_API_KEY',\n 'GEMINI_API_KEY',\n 'GOOGLE_GENERATIVE_AI_API_KEY',\n 'GOOGLE_API_KEY',\n 'GROQ_API_KEY',\n ],\n boxRunEnv: {\n OPENCODE_CONFIG_DIR: `${OPENCODE_BOX_DIR}/config`,\n XDG_STATE_HOME: `${OPENCODE_BOX_DIR}/.state`,\n },\n // OpenCode auto-loads any JS/TS file under `$OPENCODE_CONFIG_DIR/plugins/`\n // at startup; this one subscribes to its event bus and shells\n // `agentbox-ctl opencode-state`. It is the ONLY source of opencode activity\n // (`activitySource: 'plugin'`), which is why its absence on the cloud\n // providers left every cloud opencode box reporting `unknown`.\n seeds: [\n {\n bakedPath: OPENCODE_PLUGIN_PATH,\n destRel: 'config/plugins/agentbox-state.js',\n sharedAsset: 'opencode-agentbox-plugin.js',\n label: 'the agentbox-state plugin',\n },\n ],\n caps: {\n resume: false,\n teleport: 'stub',\n // OpenCode stores sessions in a multi-tenant SQLite DB with sibling\n // storage/, snapshot/ and repos/ dirs. A naive teleport would copy the\n // whole DB (leaking every other project's sessions into the sandbox), and\n // row-level extraction is real work: foreign keys, FTS indices, and\n // snapshot artifacts that live on disk outside the DB.\n teleportStubReason:\n 'OpenCode session teleport is not yet supported in agentbox (sessions live in a multi-tenant SQLite DB at ~/.local/share/opencode/opencode.db; per-project extraction is tracked for a follow-up). Run `agentbox opencode` without -c / --resume to start a fresh session, or open an issue if you need this feature.',\n activitySource: ['plugin'],\n },\n // Box->host: two roots. `data` is staticPaths[0].boxDir; `config` is that\n // dir plus the config entry's relocToSubpath. The THIRD staticPaths entry\n // (~/.local/state/opencode, `update: true`) is deliberately absent: it is\n // newest-wins two-way state, and newest-wins is the opposite of pull's\n // additive never-overwrite rule.\n pull: {\n items: [\n { group: 'data', names: ['auth.json'] },\n {\n group: 'config',\n names: [\n 'opencode.json',\n 'opencode.jsonc',\n 'agents',\n 'commands',\n 'modes',\n 'plugins',\n 'skills',\n 'tools',\n 'themes',\n ],\n },\n ],\n },\n // Multi-provider, so it can run on a Codex (ChatGPT) subscription the host\n // already holds. The import is a field mapping into its own store — see\n // `buildCodexImportScript` for what was measured to make that safe.\n modelAuth: {\n sources: [\n { kind: 'agent', agent: 'codex', label: 'Your Codex login (ChatGPT subscription OAuth)' },\n ],\n ingest: {\n kind: 'command',\n name: 'opencode-model-auth',\n command: buildCodexImportScript({\n agentId: 'opencode',\n storePath: `${OPENCODE_BOX_DIR}/auth.json`,\n providerKey: 'openai',\n marker: codexImportMarker('opencode'),\n }),\n },\n },\n settings: [\n {\n key: 'modelAuth',\n type: 'enum-list',\n enumValues: ['none', 'codex'],\n default: 'none',\n description:\n 'Which host model-provider logins a new opencode box is seeded with, comma-separated. `codex` copies your Codex (ChatGPT) OAuth login into the box and imports it as `openai`. `none` leaves model auth to the box, and is only valid on its own. `--model-auth` overrides per create.',\n },\n ],\n};\n","/**\n * Turn a borrowed Codex login into a multi-provider agent's own OAuth profile.\n *\n * pi and opencode both store a ChatGPT-subscription profile in their own\n * provider-keyed `auth.json`, in the same five-field shape, under the same\n * OpenAI OAuth client as the Codex CLI itself. So the import is a field\n * mapping — no plugin to install, no CLI to drive — which is why this is a\n * `command` ingest the host runs rather than a service task.\n *\n * MEASURED on the host's real stores before this was written:\n *\n * - `~/.codex/auth.json` `.tokens` carries `access_token`, `refresh_token`,\n * `account_id`; the consumer wants `access`, `refresh`, `accountId`.\n * - All three stores share one OAuth `client_id`, which is what makes the\n * tokens interchangeable at all.\n * - `expires` MUST come from the access token's own `exp` claim. Writing 0 or\n * a past value looks harmless — \"it will just refresh\" — but the consumer's\n * refresh call REJECTS a codex-issued refresh token (`invalid_state`), so\n * the box would come up with auth that never worked. Verified back to back:\n * the agent's own refresh token at `expires:0` refreshed and rotated fine,\n * codex's did not.\n * - Because of that, a seeded box cannot renew itself. It works until the\n * borrowed access token expires, and is renewed by the credential fan-out\n * re-pushing the host's login and re-running this — which is exactly why the\n * gate below is a hash of the SEED, not \"is there a profile already\".\n *\n * The store is a map that may already hold other providers, so this MERGES one\n * key and never rewrites the file wholesale.\n */\n\nimport { codexSpec } from './codex.js';\n\n/** Single-quote a value for the POSIX shell. */\nfunction sq(v: string): string {\n return `'${v.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * argv: <seed> <store> <providerKey>. Exit 0 on success, non-zero on any\n * \"nothing to ingest\" so the shell can report it and still exit 0 itself.\n */\nconst IMPORT_JS = `\nconst fs = require('fs');\nconst path = require('path');\nconst [seedPath, storePath, key] = process.argv.slice(1);\nconst seed = JSON.parse(fs.readFileSync(seedPath, 'utf8'));\nconst t = seed && seed.tokens;\nif (!t || typeof t.refresh_token !== 'string' || t.refresh_token.length === 0) process.exit(3);\nif (typeof t.access_token !== 'string' || t.access_token.length === 0) process.exit(3);\n// The consumer's refresh cannot renew a codex-issued token, so a wrong expiry\n// is not self-healing: take the real one off the access token's exp claim.\nlet expires = 0;\ntry {\n const c = JSON.parse(\n Buffer.from(t.access_token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64')\n .toString('utf8'),\n );\n expires = typeof c.exp === 'number' ? c.exp * 1000 : 0;\n} catch (e) {\n expires = 0;\n}\nif (expires <= 0) process.exit(4);\nlet store = {};\ntry {\n const cur = JSON.parse(fs.readFileSync(storePath, 'utf8'));\n if (cur && typeof cur === 'object' && !Array.isArray(cur)) store = cur;\n} catch (e) {\n store = {};\n}\nstore[key] = {\n type: 'oauth',\n access: t.access_token,\n refresh: t.refresh_token,\n accountId: t.account_id,\n expires: expires,\n};\nfs.mkdirSync(path.dirname(storePath), { recursive: true });\nfs.writeFileSync(storePath, JSON.stringify(store, null, 2), { mode: 0o600 });\n`;\n\nexport interface CodexImportOptions {\n /** The consuming agent's id, for log lines. */\n agentId: string;\n /** The consumer's own auth store inside the box. */\n storePath: string;\n /** The provider key to write in that store — pi's `openai-codex`, opencode's `openai`. */\n providerKey: string;\n /** Where the hash of the last imported seed is kept. AgentBox-owned, per box. */\n marker: string;\n /** The seeded login's path. Defaults to codex's own; overridden only by tests. */\n seedPath?: string;\n}\n\n/** The ingest command for an agent that consumes a Codex login as OpenAI auth. */\nexport function buildCodexImportScript(o: CodexImportOptions): string {\n const seed = o.seedPath ?? codexSpec.credential!.boxAbsPath;\n const tag = `${o.agentId}-model-auth`;\n return [\n // `set -e` is deliberately absent: a box whose model auth cannot be seeded\n // must still come up.\n 'set -u',\n `seed=${sq(seed)}`,\n `store=${sq(o.storePath)}`,\n `marker=${sq(o.marker)}`,\n `if [ ! -s \"$seed\" ]; then echo ${sq(`${tag}: no borrowed Codex login at ${seed}`)}; exit 0; fi`,\n 'seen=$(sha256sum \"$seed\" | cut -d\" \" -f1)',\n 'if [ -f \"$marker\" ] && [ \"$(cat \"$marker\")\" = \"$seen\" ]; then',\n ` echo ${sq(`${tag}: this Codex login is already imported`)}`,\n ' exit 0',\n 'fi',\n `if node -e ${sq(IMPORT_JS)} \"$seed\" \"$store\" ${sq(o.providerKey)}; then`,\n ` echo ${sq(`${tag}: imported the Codex login as ${o.providerKey}`)}`,\n ' printf %s \"$seen\" > \"$marker\" && chmod 600 \"$marker\"',\n 'else',\n // Double-quoted so $seed expands; the tag is a plain agent id, no metachars.\n ` echo \"${tag}: $seed is not a usable Codex ChatGPT login\"`,\n 'fi',\n 'exit 0',\n ].join('\\n');\n}\n\n/**\n * Where a consumer keeps the hash of the seed it last imported.\n *\n * PER BOX (`/run/agentbox` is a bind to `~/.agentbox/boxes/<box>/run`), not in\n * the agent's own config dir. That dir is a SHARED docker volume —\n * `agentbox-pi-config` is mounted at `~/.pi/agent` in every pi box — so a marker\n * written there made the import run once per HOST: box #2 read box #1's hash,\n * logged \"already imported\", and came up with whatever credential the shared\n * volume happened to hold. Measured, not theorised.\n */\nexport function codexImportMarker(agentId: string): string {\n return `/run/agentbox/model-auth-${agentId}.sha256`;\n}\n","/**\n * Pi's registry row — the DATA half of this package.\n *\n * Imports only the two dependency-free leaves (`@agentbox/core` for the\n * contract, `@agentbox/config` for the host state dir) on purpose: this entry is read by\n * the agent registry, which `sandbox-core` depends on, which in turn everything\n * depends on. Anything heavier here is a dependency cycle. See this package's\n * `tsup.config.ts`.\n */\n\nimport { join } from 'node:path';\nimport { STATE_DIR } from '@agentbox/config';\nimport { BOX_USER, BOX_HOME, BOX_CREDS_DIR, agentDirPrelude } from '@agentbox/core';\nimport type { AgentSyncSpec } from '@agentbox/core';\n\n/** Pi keeps everything under one root; `PI_CODING_AGENT_DIR` would move it. */\nimport { buildCodexImportScript, codexImportMarker } from './_codex-import.js';\n\nconst PI_BOX_DIR = `${BOX_HOME}/.pi/agent`;\n/** Baked alongside the setup guide: Pi's activity-reporting extension. */\nconst PI_EXTENSION_PATH = '/usr/local/share/agentbox/pi-agentbox-extension.js';\n\nexport const piSpec: AgentSyncSpec = {\n id: 'pi',\n aliases: [],\n sessionName: 'pi',\n binary: 'pi',\n install: {\n // The `pi.dev/install.sh` script is only an npm wrapper (it shells\n // `npm i -g` with a spinner), so the npm recipe is the same install with\n // one less moving part — and no CDN to 403 us.\n recipe: { kind: 'npm', package: '@earendil-works/pi-coding-agent' },\n runAs: 'root',\n postInstall: [\n // Fail the INSTALL, not the launch, on too old a Node.\n //\n // Pi's package declares `engines: node >= 22.19.0` and uses `fs.globSync`\n // (node 22+), but `npm install -g` only WARNS on an engines mismatch. So\n // on a node-20 box the install \"succeeds\", `command -v pi` passes, the\n // box reports ready, and the tmux session dies instantly with\n // `SyntaxError: ... does not provide an export named 'globSync'` -- which\n // surfaces as \"agent exited immediately after launch\" with no cause.\n // Cost a full e2b create to diagnose; every provider's base is node 24\n // except E2B's, whose upstream `e2bdev/base` ships node 20.\n //\n // A community provider can hit this too and cannot patch our bake\n // scripts, so the check belongs on the agent that has the requirement.\n 'if [ \"$(node -p \\'process.versions.node.split(\".\")[0]\\' 2>/dev/null || echo 0)\" -lt 22 ]; then ' +\n 'echo \"agentbox: pi needs Node >= 22.19, but this box has $(node --version 2>/dev/null || echo none). ' +\n 'Re-bake this provider\\'s base (agentbox prepare --provider <name>) to get a newer Node.\" >&2; exit 65; fi',\n // BOTH dirs, not just the leaf: GNU `install -d -o u -g g a/b` applies the\n // ownership to the FINAL component only, so passing the nested path alone\n // leaves `~/.pi` root-owned and the later static-config stage (which runs\n // as the box user) cannot write into it.\n ...agentDirPrelude([`${BOX_HOME}/.pi`, PI_BOX_DIR], 'pi'),\n `ln -sfn ${BOX_CREDS_DIR}/pi/auth.json ${PI_BOX_DIR}/auth.json`,\n `chown -h ${BOX_USER}:${BOX_USER} ${PI_BOX_DIR}/auth.json`,\n ].join(' && '),\n },\n dockerVolume: 'agentbox-pi-config',\n staticPaths: [\n {\n hostHomeRel: ['.pi', 'agent'],\n boxDir: PI_BOX_DIR,\n // Push excludes (single source of truth; `agentPushExcludes` also derives\n // the credential file and applies LIVE_DATABASE_EXCLUDES).\n //\n // `bin` is the load-bearing one: Pi vendors `fd` and `rg` there as\n // HOST-NATIVE binaries. Shipping a macOS arm64 `rg` into a Linux box\n // leaves Pi's grep/find tools present-but-unexecutable, which fails as a\n // confusing tool error rather than as a missing binary.\n //\n // `trust.json` is keyed by canonical host directory, so none of its\n // decisions mean anything in a box (`launchFlags: ['-a']` covers trust\n // there instead). `sessions` is host transcripts — pull-direction only.\n // `models-store.json` is a provider-catalog cache the box refetches.\n exclude: ['sessions', 'bin', 'models-store.json', 'trust.json'],\n },\n ],\n credential: {\n boxRelPath: 'auth.json',\n boxAbsPath: `${PI_BOX_DIR}/auth.json`,\n hostBackup: join(STATE_DIR, 'pi-credentials.json'),\n cloudMountPath: `${BOX_CREDS_DIR}/pi`,\n cloudSubpath: 'pi/',\n realShape: 'nonempty-json',\n // No `freshness`: Pi's auth.json holds API keys and OAuth blobs that it\n // refreshes in place without ROTATING a refresh token, so there is no\n // ordering field to compare and last-writer-wins is correct.\n },\n // Pi resolves a key as: --api-key flag -> auth.json -> env -> models.json.\n // Forwarding these lets an env-authed host work in a box with no auth.json.\n forwardedEnvKeys: [\n 'ANTHROPIC_API_KEY',\n 'OPENAI_API_KEY',\n 'GEMINI_API_KEY',\n 'OPENROUTER_API_KEY',\n 'XAI_API_KEY',\n 'GROQ_API_KEY',\n 'AI_GATEWAY_API_KEY',\n 'HF_TOKEN',\n 'AWS_BEARER_TOKEN_BEDROCK',\n ],\n boxRunEnv: {\n // Suppress the startup update check only. Deliberately NOT `PI_OFFLINE=1`,\n // which also blocks the provider model-catalog fetch — a fresh box has no\n // `models-store.json` (we exclude the host's), so offline would leave it\n // with no model list at all.\n PI_SKIP_VERSION_CHECK: '1',\n },\n // Pi auto-loads every `.ts`/`.js` file under its `extensions/` dir\n // (`isExtensionFile` in its bundle accepts both), so a plain `.js` needs no\n // TypeScript toolchain in the box. This one subscribes to Pi's event bus and\n // shells `agentbox-ctl agent-state pi <state>` — the ONLY source of Pi\n // activity (`activitySource: ['plugin']`).\n seeds: [\n {\n bakedPath: PI_EXTENSION_PATH,\n destRel: 'extensions/agentbox-state.js',\n sharedAsset: 'pi-agentbox-extension.js',\n label: 'the agentbox-state extension',\n },\n ],\n // `-a` / `--approve` is Pi's PROJECT TRUST flag, not a permission bypass (Pi\n // has no tool-approval prompts at all — it is designed to run with full\n // permissions inside a container, which is what a box is). Without it, an\n // interactive launch into a repo carrying a `.pi/` dir blocks on a\n // \"trust project-local files?\" dialog that nothing on the host can answer.\n launchFlags: ['-a'],\n caps: {\n resume: true,\n teleport: 'full',\n activitySource: ['plugin'],\n },\n // Box->host: a flat list under the single config root. `sessions` is absent\n // on purpose — a box's transcripts are its own, and pulling them into the\n // host's per-cwd session tree would mix `/workspace` sessions into the\n // project's history.\n pull: {\n // Leaf FILES only. A directory whose children are the unit belongs in\n // `categories`, not here: the pull is additive and skips anything the host\n // already has, so listing `skills` flat would make every box-created skill\n // unpullable the moment the host had a `skills/` dir of its own.\n items: [\n {\n group: 'data',\n names: ['auth.json', 'settings.json', 'AGENTS.md', 'SYSTEM.md', 'APPEND_SYSTEM.md'],\n },\n ],\n // Directories of independent, individually-addable items — the same shape\n // as claude's skills/agents/commands.\n categories: ['extensions', 'skills', 'prompts', 'themes'],\n },\n // Multi-provider, so it can run on a Codex (ChatGPT) subscription the host\n // already holds. The import is a field mapping into its own store — see\n // `buildCodexImportScript` for what was measured to make that safe.\n modelAuth: {\n sources: [\n { kind: 'agent', agent: 'codex', label: 'Your Codex login (ChatGPT subscription OAuth)' },\n ],\n ingest: {\n kind: 'command',\n name: 'pi-model-auth',\n command: buildCodexImportScript({\n agentId: 'pi',\n storePath: `${PI_BOX_DIR}/auth.json`,\n providerKey: 'openai-codex',\n marker: codexImportMarker('pi'),\n }),\n },\n },\n settings: [\n {\n key: 'modelAuth',\n type: 'enum-list',\n enumValues: ['none', 'codex'],\n default: 'none',\n description:\n 'Which host model-provider logins a new pi box is seeded with, comma-separated. `codex` copies your Codex (ChatGPT) OAuth login into the box and imports it as `openai-codex`. `none` leaves model auth to the box, and is only valid on its own. `--model-auth` overrides per create.',\n },\n ],\n};\n","/**\n * Externally-installed agents — the dynamic half of the registry.\n *\n * The design is the provider one, deliberately: `agentbox agent add <package>`\n * loads the package once, validates the `AgentSyncSpec` it exports, and\n * SNAPSHOTS that spec into `~/.agentbox/agents.json`. Every consumer afterwards\n * reads the snapshot — synchronously, offline, without importing the package —\n * exactly as `resolveProviderDescriptor` reads `plugins.json`.\n *\n * Snapshotting costs nothing here because `AgentSyncSpec` is ALREADY pure JSON.\n * That was not an accident: the spec is shipped into a box whose `agentbox-ctl`\n * may predate the agent (over the `agents.list` RPC), so it has never been\n * allowed to hold a function. The same property that lets a spec cross into a\n * box lets it be written to a file and read back.\n *\n * This file is DATA only. Loading a plugin agent's behavior (its\n * `AgentSyncModule`) is a separate, lazy `import()` of `resolvedEntry` — and\n * that variable specifier is precisely why a plugin agent never enters the\n * workspace dependency graph, and so is structurally exempt from the package\n * cycle the built-in split exists to avoid.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { AGENTS_FILE } from '@agentbox/config';\nimport type { AgentSyncSpec } from '@agentbox/core';\n\n/**\n * Re-exported, not declared: the path also has to be reachable from\n * `@agentbox/config`, which generates a config key per declared agent setting\n * and cannot import this package (it is the leaf this one depends on). One\n * spelling, in the leaf.\n */\nexport { AGENTS_FILE };\n\n/** Agent-plugin API versions this build accepts. */\nexport const SUPPORTED_AGENT_API_VERSIONS: readonly number[] = [1];\n\nexport function isSupportedAgentApiVersion(v: number): boolean {\n return SUPPORTED_AGENT_API_VERSIONS.includes(v);\n}\n\nexport interface AgentPluginRecord {\n /** Package name as installed. */\n packageName: string;\n /** Absolute path to the package's resolved entry module, recorded at add time. */\n resolvedEntry: string;\n /** Package version at add time (informational). */\n version: string;\n /**\n * The spec rows this package contributes, keyed by agent id. This is the\n * snapshot — it is what every reader resolves against, so no consumer ever\n * has to `import()` the package just to learn that an agent exists.\n */\n specs: Record<string, AgentSyncSpec>;\n /** The agent API version the package declared (compat gate). */\n apiVersion: number;\n /** ISO timestamp the package was added. */\n addedAt: string;\n}\n\nexport interface AgentsFile {\n version: 1;\n agents: AgentPluginRecord[];\n}\n\nexport const AGENTS_FILE_VERSION = 1;\n\nconst EMPTY: AgentsFile = { version: AGENTS_FILE_VERSION, agents: [] };\n\n/**\n * Every field an `AgentSyncSpec` cannot work without. Checked at ADD time so a\n * malformed package is refused once, at the moment someone can fix it — rather\n * than at box-create time, which is both far away and much worse.\n */\nconst REQUIRED_SPEC_FIELDS = [\n 'id',\n 'aliases',\n 'sessionName',\n 'binary',\n 'install',\n 'dockerVolume',\n 'staticPaths',\n // NOT `credential`: an agent may declare it has none (openclaw generates its\n // gateway token inside the box and there is nothing on the host to sync). A\n // credential that IS present is still shape-checked — see `credentialProblem`.\n 'forwardedEnvKeys',\n 'boxRunEnv',\n 'caps',\n] as const;\n\nconst RECIPE_KINDS = ['npm', 'script', 'exec'] as const;\nconst RUN_AS = ['root', 'box-user'] as const;\n\n/**\n * The fields whose SHAPE — not just presence — is worth checking.\n *\n * Presence alone is not enough, and that is not hypothetical: an `install` of\n * `{ kind: 'none' }` passed a presence check and then threw at bake time, where\n * the author is long gone and the message is about `recipe.kind` being\n * undefined. The whole point of validating at `agent add` is to fail at the one\n * moment someone can still fix the package, so anything with a load-bearing\n * shape gets checked here.\n */\nfunction installProblem(raw: unknown): string | null {\n if (raw === null || typeof raw !== 'object') return '`install` must be an object';\n const install = raw as Record<string, unknown>;\n const recipe = install.recipe as Record<string, unknown> | undefined;\n if (recipe === undefined || typeof recipe !== 'object' || recipe === null) {\n return '`install.recipe` is required (`{ kind: \"npm\" | \"script\" | \"exec\", … }`)';\n }\n const kind = recipe.kind;\n if (typeof kind !== 'string' || !(RECIPE_KINDS as readonly string[]).includes(kind)) {\n return `\\`install.recipe.kind\\` must be one of ${RECIPE_KINDS.join(', ')}`;\n }\n if (kind === 'npm' && typeof recipe.package !== 'string') {\n return '`install.recipe.package` is required for the npm recipe';\n }\n if (kind === 'script' && typeof recipe.url !== 'string') {\n return '`install.recipe.url` is required for the script recipe';\n }\n if (kind === 'exec' && typeof recipe.script !== 'string') {\n return '`install.recipe.script` is required for the exec recipe';\n }\n // Not cosmetic: an installer that drops a binary in the INVOKING user's\n // ~/.local/bin puts it in /root when run as root, and the box user never\n // sees it.\n if (typeof install.runAs !== 'string' || !(RUN_AS as readonly string[]).includes(install.runAs)) {\n return `\\`install.runAs\\` must be one of ${RUN_AS.join(', ')}`;\n }\n return null;\n}\n\nfunction credentialProblem(raw: unknown): string | null {\n if (raw === null || typeof raw !== 'object') return '`credential` must be an object';\n const cred = raw as Record<string, unknown>;\n // Absolute, like `boxDir` and `hostBackup`. The credential push derives the\n // directory with `slice(0, lastIndexOf('/'))`, so a relative `auth.json`\n // yields an empty dir, `mkdir -p ''`, and a copy that never lands.\n if (typeof cred.boxAbsPath !== 'string' || !cred.boxAbsPath.startsWith('/')) {\n return '`credential.boxAbsPath` must be an absolute in-box path';\n }\n // The credential fan-out WRITES here when a box logs in. An empty or relative\n // path drops a temp file in whatever directory the CLI was run from and loses\n // the login silently.\n if (typeof cred.hostBackup !== 'string' || !cred.hostBackup.startsWith('/')) {\n return '`credential.hostBackup` must be an absolute host path (the fan-out writes to it)';\n }\n // A SUB-DIR of the shared cloud credentials volume, so it must end in `/`.\n // Every built-in uses `<id>/`; a filename here mounts the volume subpath at\n // the wrong depth, and nothing downstream notices.\n if (typeof cred.cloudSubpath !== 'string' || !cred.cloudSubpath.endsWith('/')) {\n return '`credential.cloudSubpath` must be a sub-directory, ending in `/` (e.g. `myagent/`)';\n }\n // A shape ctl does not recognise is DROPPED on arrival, and if that empties\n // the watch list ctl falls back to the list baked into its image — which a\n // plugin agent can never be in. The result is no credential watch at all, with\n // nothing logged about this agent. Refuse it here, where there is a person to\n // tell.\n if (cred.realShape !== 'claude-oauth' && cred.realShape !== 'nonempty-json') {\n return \"`credential.realShape` must be 'claude-oauth' or 'nonempty-json'\";\n }\n // Optional, but a malformed one silently disables newest-wins ordering, which\n // for a rotating token means an older blob can overwrite a newer one.\n const fresh = (cred as { freshness?: unknown }).freshness;\n if (fresh !== undefined) {\n const path = (fresh as { jsonPath?: unknown }).jsonPath;\n if (\n !Array.isArray(path) ||\n path.length === 0 ||\n path.some((k) => typeof k !== 'string' || k.length === 0)\n ) {\n return '`credential.freshness.jsonPath` must be a non-empty array of property names';\n }\n }\n return null;\n}\n\nfunction cloneProblem(raw: unknown): string | null {\n if (raw === null || typeof raw !== 'object') return '`clone` must be an object';\n const clone = raw as Record<string, unknown>;\n for (const key of ['drop', 'render'] as const) {\n const list = clone[key];\n if (list === undefined) continue;\n if (!Array.isArray(list) || list.some((v) => typeof v !== 'string' || v.length === 0)) {\n return `\\`clone.${key}\\` must be an array of non-empty workspace-relative paths`;\n }\n // Root-anchored and workspace-relative. An absolute path would be compared\n // against a relative listing and silently match nothing; a `..` would name\n // a file outside the workspace, which the clone has no business rewriting.\n for (const rel of list as string[]) {\n if (rel.startsWith('/') || rel.split('/').includes('..')) {\n return `\\`clone.${key}\\` entries must be workspace-relative, without '..' (got \"${rel}\")`;\n }\n }\n }\n const perBox = clone.perBoxCarry;\n if (perBox !== undefined) {\n if (!Array.isArray(perBox)) return '`clone.perBoxCarry` must be an array';\n for (const [i, entry] of perBox.entries()) {\n if (entry === null || typeof entry !== 'object') {\n return `\\`clone.perBoxCarry[${i}]\\` must be an object`;\n }\n const item = entry as Record<string, unknown>;\n // Absolute or `~/`: resolution happens with no project dir in scope, so a\n // relative source has nothing to resolve against and would be refused at\n // create time — after a box has been built. Catch it at `agent add`.\n if (\n typeof item.src !== 'string' ||\n !(item.src.startsWith('/') || item.src.startsWith('~/'))\n ) {\n return `\\`clone.perBoxCarry[${i}].src\\` must be an absolute host path or start with '~/'`;\n }\n if (\n typeof item.dest !== 'string' ||\n !(item.dest.startsWith('/') || item.dest.startsWith('~/'))\n ) {\n return `\\`clone.perBoxCarry[${i}].dest\\` must be an absolute in-box path or start with '~/'`;\n }\n if (item.mode !== undefined && typeof item.mode !== 'number') {\n return `\\`clone.perBoxCarry[${i}].mode\\` must be a number (e.g. 0o600)`;\n }\n }\n }\n return null;\n}\n\nfunction staticPathsProblem(raw: unknown): string | null {\n if (!Array.isArray(raw)) return '`staticPaths` must be an array';\n for (const [i, entry] of raw.entries()) {\n if (entry === null || typeof entry !== 'object')\n return `\\`staticPaths[${i}]\\` must be an object`;\n const path = entry as Record<string, unknown>;\n // NON-EMPTY, and every segment non-empty. Staging does\n // `join(homedir(), ...hostHomeRel)`, so `[]` and `['']` both resolve to the\n // user's HOME — and cloud staging would then rsync their entire home tree\n // into a snapshot that every box made from it shares.\n if (\n !Array.isArray(path.hostHomeRel) ||\n path.hostHomeRel.length === 0 ||\n path.hostHomeRel.some((seg) => typeof seg !== 'string' || seg.length === 0)\n ) {\n return `\\`staticPaths[${i}].hostHomeRel\\` must be a non-empty array of non-empty path segments`;\n }\n if (typeof path.boxDir !== 'string' || !path.boxDir.startsWith('/')) {\n return `\\`staticPaths[${i}].boxDir\\` must be an absolute in-box path`;\n }\n }\n return null;\n}\n\n/** Why a spec was rejected, or null when it is usable. */\nexport function agentSpecProblem(raw: unknown): string | null {\n if (raw === null || typeof raw !== 'object') return 'not an object';\n const spec = raw as Record<string, unknown>;\n const missing = REQUIRED_SPEC_FIELDS.filter((f) => spec[f] === undefined);\n if (missing.length > 0) return `missing required field(s): ${missing.join(', ')}`;\n if (typeof spec.id !== 'string' || spec.id.length === 0) return '`id` must be a non-empty string';\n if (!Array.isArray(spec.aliases)) return '`aliases` must be an array';\n const shape =\n installProblem(spec.install) ??\n // Optional field: absent is a legitimate declaration, malformed is not.\n (spec.credential === undefined ? null : credentialProblem(spec.credential)) ??\n (spec.clone === undefined ? null : cloneProblem(spec.clone)) ??\n staticPathsProblem(spec.staticPaths);\n if (shape !== null) return shape;\n // A spec that isn't JSON-round-trippable cannot reach a box: it travels to\n // `agentbox-ctl` over `agents.list` as JSON. Catching it here keeps that\n // guarantee true for plugin agents too.\n try {\n JSON.parse(JSON.stringify(raw));\n } catch {\n return 'not JSON-serializable';\n }\n return null;\n}\n\nfunction normalize(raw: unknown): AgentsFile {\n const parsed = raw as AgentsFile;\n if (!parsed || parsed.version !== AGENTS_FILE_VERSION || !Array.isArray(parsed.agents)) {\n // Unrecognized shape → treat as empty, never throw. A corrupt agents.json\n // must not brick every box command; the same rule `plugins.json` follows.\n return { ...EMPTY };\n }\n return parsed;\n}\n\n/**\n * Synchronous read. Missing or corrupt file → empty.\n *\n * Sync on purpose: this feeds the spec table, which the relay, the hub and\n * `sandbox-core` all read without awaiting. It is the same trade\n * `readPluginRegistrySync` makes for providers.\n */\nexport function readAgentRegistrySync(path: string = AGENTS_FILE): AgentsFile {\n try {\n if (!existsSync(path)) return { ...EMPTY };\n return normalize(JSON.parse(readFileSync(path, 'utf8')));\n } catch {\n return { ...EMPTY };\n }\n}\n\n/**\n * The spec rows contributed by installed agent packages, in registration order.\n *\n * A record whose API version this build does not support is skipped rather than\n * fatal: an agent added by a newer AgentBox must not break an older one, it\n * just isn't available. Same for an individual spec that fails validation — the\n * file may have been hand-edited since `agent add` checked it.\n */\nexport function pluginAgentSpecs(path: string = AGENTS_FILE): AgentSyncSpec[] {\n const out: AgentSyncSpec[] = [];\n for (const record of readAgentRegistrySync(path).agents) {\n if (!isSupportedAgentApiVersion(record.apiVersion)) continue;\n for (const spec of Object.values(record.specs ?? {})) {\n if (agentSpecProblem(spec) === null) out.push(spec);\n }\n }\n return out;\n}\n\n/** The package that contributed `agentId`, or undefined for a built-in. */\nexport function pluginForAgent(\n agentId: string,\n path: string = AGENTS_FILE,\n): AgentPluginRecord | undefined {\n return readAgentRegistrySync(path).agents.find((r) => agentId in (r.specs ?? {}));\n}\n\n/**\n * Read for a read-modify-WRITE. Unlike `readAgentRegistrySync` — which degrades\n * a corrupt file to empty so no command bricks — this REFUSES to proceed on an\n * unparseable file, because the alternative is overwriting a recoverable\n * `agents.json` and silently dropping every other registered agent. A genuinely\n * missing file is still an empty start.\n */\nasync function readForWrite(path: string): Promise<AgentsFile> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { ...EMPTY };\n throw err;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new Error(`${path} is not valid JSON — fix or remove it before adding an agent`);\n }\n const file = parsed as AgentsFile;\n if (!file || file.version !== AGENTS_FILE_VERSION || !Array.isArray(file.agents)) {\n throw new Error(`${path} is not a recognized agent registry — fix or remove it`);\n }\n return file;\n}\n\nasync function writeRegistry(path: string, file: AgentsFile): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, `${JSON.stringify(file, null, 2)}\\n`, 'utf8');\n}\n\n/** Register (or re-register) one package's agents. Replaces any prior record for it. */\nexport async function addAgentPluginRecord(\n record: AgentPluginRecord,\n path: string = AGENTS_FILE,\n): Promise<void> {\n const file = await readForWrite(path);\n file.agents = [...file.agents.filter((r) => r.packageName !== record.packageName), record];\n await writeRegistry(path, file);\n}\n\n/** Remove a package's registration. Returns false when it wasn't registered. */\nexport async function removeAgentPluginRecord(\n packageName: string,\n path: string = AGENTS_FILE,\n): Promise<boolean> {\n const file = await readForWrite(path);\n const before = file.agents.length;\n file.agents = file.agents.filter((r) => r.packageName !== packageName);\n if (file.agents.length === before) return false;\n await writeRegistry(path, file);\n return true;\n}\n","/**\n * The built-in agent specs.\n *\n * WHY A PACKAGE OF ITS OWN, BELOW `sandbox-core`. Every provider, the relay and\n * the hub depend on `sandbox-core`, and all three need agent DATA synchronously:\n * the relay answers `agents.list` from it, the hub reports what a host carries,\n * `sandbox-core` drives seeding and staging off it. So the data has to sit below\n * all of them.\n *\n * WHY THE DATA IS NOT IN THE AGENT PACKAGES. It was, briefly, behind a `./spec`\n * subpath with leaf-only dependencies — the theory being that entry points would\n * keep the graph acyclic. They do not: pnpm and turbo resolve per PACKAGE, so the\n * moment an agent package gains behavior (and therefore depends on\n * `sandbox-docker`) turbo refuses to build:\n *\n * Circular package dependency detected: @agentbox/agent-example,\n * @agentbox/agent-registry, @agentbox/sandbox-core, @agentbox/relay,\n * @agentbox/ctl, @agentbox/sandbox-docker\n *\n * Data and behavior therefore live in separate packages — exactly the provider\n * split, where `PROVIDERS` is a table in a leaf and `sandbox-<name>` is code\n * loaded from a literal-import map.\n *\n * THIS COSTS COMMUNITY AGENTS NOTHING. A plugin agent lives in the user's\n * `node_modules`, is loaded through a variable `import()`, and never enters the\n * workspace graph — structurally exempt from the cycle. It ships its descriptor\n * inside its own package and `agent add` snapshots it, the way `plugin add`\n * already does for providers. This table is only the shortcut for the agents\n * compiled into the CLI.\n */\n\nimport { claudeSpec } from './specs/claude.js';\nimport { codexSpec } from './specs/codex.js';\nimport { exampleSpec } from './specs/example.js';\nimport { openclawSpec } from './specs/openclaw.js';\nimport { opencodeSpec } from './specs/opencode.js';\nimport { piSpec } from './specs/pi.js';\nimport { pluginAgentSpecs } from './plugin-agents.js';\nimport type { AgentId, AgentSyncSpec } from '@agentbox/core';\n\n/**\n * Canonical order — claude first, matching the order these rows had when they\n * lived in one table. `list`, the dashboard and the pickers all present agents\n * in this order, so it is a user-visible fact, not an implementation detail.\n */\nexport const BUILTIN_AGENT_SPECS: readonly AgentSyncSpec[] = [\n claudeSpec,\n codexSpec,\n opencodeSpec,\n piSpec,\n openclawSpec,\n exampleSpec,\n];\n\n/**\n * Built-ins plus whatever `agentbox agent add` registered, resolved once at\n * import.\n *\n * A snapshot rather than a live read because ~50 call sites treat this as a\n * constant, and a plugin agent appearing halfway through a create would be far\n * worse than one that appears on the next command. Every CLI invocation is a\n * fresh process, so \"the next command\" is immediately; the long-lived host\n * processes (relay, hub) pick it up on restart, and {@link allAgentSpecs} is\n * there for a caller that must not wait for one.\n *\n * A built-in always wins: a plugin cannot shadow a shipped agent, the same rule\n * `plugin add` enforces for providers.\n */\nexport const AGENT_SPECS: readonly AgentSyncSpec[] = mergeAgentSpecs(\n BUILTIN_AGENT_SPECS,\n pluginAgentSpecs(),\n);\n\nfunction mergeAgentSpecs(\n builtins: readonly AgentSyncSpec[],\n plugins: readonly AgentSyncSpec[],\n): readonly AgentSyncSpec[] {\n // Aliases count as taken too, or a plugin claiming `claude-code` would\n // silently capture every `agentbox claude-code`.\n const taken = new Set(builtins.flatMap((s) => [s.id, ...s.aliases]));\n const extra = plugins.filter((s) => ![s.id, ...s.aliases].some((n) => taken.has(n)));\n return [...builtins, ...extra];\n}\n\n/**\n * Re-read the plugin registry and return the current set. For a long-lived\n * process that must see an agent added since it started — the relay answering\n * `agents.list` for a box created a moment ago.\n */\nexport function allAgentSpecs(): readonly AgentSyncSpec[] {\n return mergeAgentSpecs(BUILTIN_AGENT_SPECS, pluginAgentSpecs());\n}\n\n/**\n * The agents a user should be offered — pickers, `--help`, the install wizard,\n * the `--agents` bake list.\n *\n * Everything else iterates {@link AGENT_SPECS}: a hidden agent is fully real to\n * the machinery and merely unadvertised. Surfaces that ask a human to choose\n * should use this instead.\n */\nexport function visibleAgentSpecs(): AgentSyncSpec[] {\n return AGENT_SPECS.filter((s) => !s.hidden);\n}\n\n/** Ids of the agents a user should be offered. */\nexport function visibleAgentIds(): AgentId[] {\n return visibleAgentSpecs().map((s) => s.id);\n}\n\n/** Every built-in agent id, in canonical order. Excludes plugin agents. */\nexport function builtinAgentIds(): AgentId[] {\n return BUILTIN_AGENT_SPECS.map((s) => s.id);\n}\n\n/**\n * The spec for `id`, or undefined. Resolves aliases (`claude-code` -> claude),\n * because persisted queue jobs and box records still carry the wire spelling.\n */\nexport function findAgentSpec(id: string): AgentSyncSpec | undefined {\n return AGENT_SPECS.find((s) => s.id === id || s.aliases.includes(id));\n}\n\nexport {\n AGENTS_FILE,\n AGENTS_FILE_VERSION,\n SUPPORTED_AGENT_API_VERSIONS,\n isSupportedAgentApiVersion,\n agentSpecProblem,\n readAgentRegistrySync,\n pluginAgentSpecs,\n pluginForAgent,\n addAgentPluginRecord,\n removeAgentPluginRecord,\n type AgentPluginRecord,\n type AgentsFile,\n} from './plugin-agents.js';\n","/**\n * A provider log line that must SURVIVE the command it was emitted during.\n *\n * Provider progress reaches the user through `onLog`, which every consumer\n * renders as transient chrome — `prepare` truncates each line into an 80-column\n * spinner frame the next line overwrites a second later, `create` writes to the\n * command log file. That is right for build chatter and wrong for a decision\n * the user needs to know about afterwards: a daytona `linux-vm` bake that finds\n * no published box image silently produces a CONTAINER snapshot, and both the\n * fallback notice and the create-time class mismatch flashed past inside a\n * spinner. The user then had a box with a quarter of the RAM they asked for and\n * nothing on screen said so.\n *\n * So: same channel, marked. Wrap a line in `providerWarning()` and every\n * consumer that understands the marker re-emits it as a persisted warning when\n * the command finishes; one that doesn't still logs it verbatim minus a prefix.\n */\nconst PROVIDER_WARNING_PREFIX = 'agentbox-warning: ';\n\n/** Mark a line for re-emission after the command's transient output is gone. */\nexport function providerWarning(text: string): string {\n return `${PROVIDER_WARNING_PREFIX}${text}`;\n}\n\n/**\n * A leading ISO-8601 timestamp, which every log transport on the way to a\n * terminal prepends. A queued bake goes provider -> the worker's log file ->\n * the hub API -> the CLI, and the worker stamps each line, so by the time the\n * process that HAS a terminal sees the marker it is no longer at position 0.\n */\nconst LEADING_TIMESTAMP = /^\\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z\\s+/;\n\n/**\n * The warning text, or null when this is an ordinary progress line.\n *\n * Anchored (after any timestamp) so a build log that merely quotes the marker\n * mid-line stays what it is: build output.\n */\nexport function parseProviderWarning(line: string): string | null {\n const body = line.replace(LEADING_TIMESTAMP, '');\n return body.startsWith(PROVIDER_WARNING_PREFIX)\n ? body.slice(PROVIDER_WARNING_PREFIX.length)\n : null;\n}\n","import type { QueueAgentKind } from './sync/agent-kind.js';\n\nexport interface AgentLauncher {\n readonly kind: QueueAgentKind;\n buildArgs(initialMessage: string, userArgs: string[]): string[];\n}\n\n/**\n * Every agent we ship takes a leading positional as the seed user turn\n * (`claude \"<msg>\"`, `codex \"<msg>\"`, `opencode \"<msg>\"`), dropping the user into\n * the TUI with that turn pre-submitted — so one launcher serves all of them.\n *\n * The indirection stays because the shape is not guaranteed: an agent that wants\n * its seed prompt on stdin, or behind a flag, gets its own launcher here without\n * every call site learning about it.\n */\nfunction positionalSeedLauncher(kind: QueueAgentKind): AgentLauncher {\n return {\n kind,\n buildArgs(initialMessage, userArgs) {\n if (!initialMessage) return [...userArgs];\n return [initialMessage, ...userArgs];\n },\n };\n}\n\nexport function resolveAgentLauncher(kind: QueueAgentKind): AgentLauncher {\n return positionalSeedLauncher(kind);\n}\n","/**\n * The per-box state record persisted to `~/.agentbox/state.json`. Shared by\n * every provider: a box may be a local Docker container or a remote cloud\n * sandbox. The `provider` discriminator says which; provider-specific fields\n * live flat (Docker, for historical reasons) or under `cloud` (cloud backends).\n */\n\nimport type { InboundPolicy } from './cloud-backend.js';\nimport type { BoxRuntimeState } from './provider.js';\nimport type { SyncTopology } from './sync/types.js';\nimport type { AgentId } from './sync/agent-kind.js';\n\n/** Sandbox backend a box runs on. Open-ended so future providers need no core change. */\nexport type ProviderName = 'docker' | 'daytona' | 'hetzner' | (string & {});\n\n/**\n * Docker-backend-specific fields nested under `BoxRecord.docker` once 7.1\n * lands fully. Today every Docker box also keeps the flat copies of these\n * fields on `BoxRecord` directly for back-compat (state.json migration is\n * the rest of 7.1) — write sites populate both shapes; read sites still\n * use the flat fields. New code should target this interface so the\n * eventual flat-field removal is a search-and-replace, not a redesign.\n */\nexport interface DockerBoxFields {\n /** Docker container name (`agentbox-<id|name>`). */\n container: string;\n /** Base image / checkpoint image tag the container was started from. */\n image: string;\n /** Per-box scratch dir with the `cp -c` APFS clone (when --host-snapshot is on). */\n snapshotDir?: string | null;\n /** Host-side path to the agentbox-ctl unix socket bind-mounted into the container. */\n socketPath?: string;\n /** Docker volume mounted at /home/vscode/.claude inside the box. */\n claudeConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.codex inside the box. */\n codexConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.agents inside the box (Agent Skills). */\n agentsConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.local/share/opencode. */\n opencodeConfigVolume?: string;\n /**\n * Every agent's docker config volume, keyed by agent id.\n *\n * The three named fields above are a DERIVED mirror of this map, kept because\n * a box created by an older CLI has only them — read through\n * {@link agentConfigVolume}, never directly. The map is what makes a fourth or\n * plugin agent representable: `create` already resolves a volume for every\n * registered agent and used to discard all but three, which is why the\n * per-agent tables that consumed those fields answered opencode's volume for\n * anything they did not name.\n *\n * `agentsConfigVolume` is deliberately NOT in here: it is the shared\n * `~/.agents` skills volume, not an agent's.\n */\n agentConfigVolumes?: Record<string, string>;\n /** Per-box volume holding `.vscode-server`. */\n vscodeServerVolume?: string;\n /** Per-box volume holding `.cursor-server`. */\n cursorServerVolume?: string;\n /** Host port mapped to the noVNC web server. */\n vncHostPort?: number;\n /** Host port mapped to container :80. */\n webHostPort?: number;\n /** Portless route name registered for this box's web port. */\n portlessAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box. */\n portlessUrl?: string;\n /** Portless route name registered for this box's noVNC port (`vnc-<box-name>`). */\n portlessVncAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box's VNC. */\n portlessVncUrl?: string;\n /** Volume mounted at /var/lib/docker for the in-box dockerd. */\n dockerVolume?: string;\n /** True when this box's `dockerVolume` is the shared cache. */\n dockerCacheShared?: boolean;\n /** Checkpoint image tag this box was started from. */\n checkpointImage?: string;\n}\n\n/**\n * Cloud-backend-specific fields for a box. Populated only when\n * `BoxRecord.provider` is a cloud provider; `undefined` for Docker boxes.\n */\nexport interface CloudBoxFields {\n /** Cloud backend name, e.g. 'daytona'. Mirrors `BoxRecord.provider`. */\n backend: string;\n /** Provider-native sandbox id (the handle the backend SDK resolves). */\n sandboxId: string;\n /** Resolved base image / snapshot ref the sandbox was provisioned from. */\n image?: string;\n /**\n * In-box port the web service is exposed on (the supervisor's WebProxy\n * listen port). Cloud boxes bind a non-privileged port; Docker boxes use 80.\n */\n webPort?: number;\n /**\n * Token-authed preview URLs keyed by in-box port. Resolved at create and\n * refreshed on every start (preview tokens can rotate across stop/start).\n */\n previewUrls?: Record<number, string>;\n /**\n * Preview URL of the in-sandbox relay's `/bridge/*` surface — the channel the\n * host CloudBoxPoller drains. Refreshed on start alongside `previewUrls`.\n */\n relayPreviewUrl?: string;\n /**\n * Daytona-style preview-proxy token for `relayPreviewUrl` (sent as\n * `x-daytona-preview-token` header). Persisted so a relay restart can\n * rehydrate the poller without re-resolving from the SDK.\n */\n relayPreviewToken?: string;\n /**\n * Bearer secret authenticating the host poller to the in-sandbox relay's\n * `/bridge/*` routes. Distinct from `BoxRecord.relayToken` (the per-box token\n * the in-box agent sees) so a compromised agent cannot impersonate the host.\n */\n bridgeToken?: string;\n /**\n * User-facing checkpoint name this box was provisioned from (e.g. `setup`),\n * when `agentbox create --checkpoint <name>` resolved to a cloud snapshot.\n * Surfaces in `agentbox status --inspect` so the user can tell which\n * checkpoint a box is currently running.\n */\n snapshotRef?: string;\n /**\n * Last lifecycle state agentbox itself drove this box to (running on\n * create/start/resume, paused on pause/stop/vercel-checkpoint). `listBoxes`\n * shows this for cloud boxes so `agentbox list` stays instant — no SDK probe.\n * It reflects the last *host-initiated* op, not the authoritative live state\n * (a platform-side stop won't update it); `agentbox list --live` probes for\n * the real state. Absent on pre-feature records → treated as `running`.\n */\n lastState?: BoxRuntimeState;\n /**\n * Effective per-session timeout (ms) the sandbox was created with, when the\n * backend models one (vercel `Sandbox.create({ timeout })`). Recorded so the\n * host keepalive loop can seed its tracked death-time accurately (the\n * effective value can be project/workspace-overridden, not the global\n * default). Absent on backends without a session timeout / pre-feature records.\n */\n sessionTimeoutMs?: number;\n /**\n * Absolute death-time (epoch ms) last applied to the sandbox — written on\n * create and re-written on every start/resume, where the session window is\n * re-applied from scratch. The keepalive loop seeds its tracked deadline from\n * this in preference to `createdAt + sessionTimeoutMs`, which goes stale the\n * moment a box is paused and resumed (and after a relay restart mid-session).\n * Absent on backends without a session timeout / pre-feature records.\n */\n sessionDeadlineEpochMs?: number;\n /**\n * Actual resources the backend provisioned, read back from the create\n * response (Hetzner reports the real `server_type` cores/memory/disk). Shown\n * by `agentbox status --inspect`. Absent on backends that can't report it and\n * on pre-feature records → readers fall back to the provider's static defaults.\n */\n resources?: { cpu?: number; memory?: number; disk?: number };\n /**\n * Public IP/host of the box's VM (direct-SSH backends: hetzner /\n * digitalocean), read from the provision response. Persisted so the plane\n * re-registration on resume — and a PC adopting a hub-created box — can\n * rebuild the SSH target without a provider API call. Absent for SDK-reached\n * backends and pre-feature records.\n */\n publicHost?: string;\n /**\n * Inbound-access policy for VPS boxes (hetzner / digitalocean per-box\n * firewall). Persisted so a host-egress-IP drift re-sync (`repairReachability`\n * / `agentbox inbound`) recomputes `sources ∪ current-host-egress` without\n * losing the whitelist, and so `agentbox inbound --show` / `connect` can\n * report the box's current exposure. Absent on non-VPS backends / pre-feature\n * records → treated as `locked`.\n */\n inbound?: InboundPolicy;\n /**\n * Daytona sandbox class this box actually booted as (`linux-vm` | `container`).\n * Recorded from the class of the *snapshot* it booted from, not from config —\n * a user who flips `box.daytonaClass` while `box.imageDaytona` still points at\n * a snapshot of the other class must not have us lie about the running box.\n *\n * Threaded back into `CloudHandle.sandboxClass` so lifecycle ops can branch:\n * a VM pauses and cannot be archived, a container archives and cannot be\n * paused. Absent on non-Daytona backends and pre-feature records.\n */\n sandboxClass?: string;\n /**\n * True when this box's `/workspace` was seeded from the host checkout (the\n * laptop `create` path), i.e. it has a real fork base shared with the host.\n * Left unset for `inBoxClone` / plane boxes (they clone in-box from a leased\n * URL with no host fork base). Gates the session-start live-box resync — only\n * host-seeded boxes can merge the host's current state back in (Phase 7.5).\n */\n hostSeeded?: boolean;\n /**\n * The box's per-box branch (`agentbox/<name>`, or `--use-branch <b>`). The\n * merge target branch for the live-box resync; re-derived layout aside, this\n * is the one piece resync can't recover from the box alone.\n */\n workspaceBranch?: string;\n /**\n * Last branch the HOST sanctioned for this cloud box (defaults to\n * `workspaceBranch`, updated by host `agentbox git checkout`/`branch`/`pull\n * <branch>`). The cloud push gate auto-approves a push only to a scratch\n * branch OR this value — the cloud analogue of the docker registry's\n * `BoxWorktree.sanctionedBranch`. Absent → treated as `workspaceBranch`.\n */\n sanctionedBranch?: string;\n /**\n * The box's resolved sync federation shape (`resolveSyncTopology`). `'cloud'`\n * for a classic host-synced box, `'control-plane'` when its live relay is a\n * hosted control plane (the box forwards `/rpc` to the plane and leases push\n * tokens directly). Persisted so the value is stable across resumes.\n */\n topology?: SyncTopology;\n /**\n * The hosted control-plane base URL this box points at, when\n * `topology === 'control-plane'`. Persisted (not re-derived from config) so a\n * resume re-kick on a host whose config has changed/lacks the URL still\n * re-threads the box's forwarder upstream + `AGENTBOX_GIT_LEASE` correctly.\n */\n controlPlaneUrl?: string;\n /**\n * Git push routing (`git.pushMode`): `'auto' | 'relay' | 'lease' | 'direct'`.\n * Persisted (not re-derived from config) so a resume re-kick re-threads\n * `AGENTBOX_GIT_LEASE` / `AGENTBOX_GIT_DIRECT` correctly even if the host\n * config changed. Mirrors config's `GitPushMode`.\n */\n gitPushMode?: 'auto' | 'relay' | 'lease' | 'direct';\n /**\n * The hub's git-auth mode at create time (`hub.gitAuth`). Persisted for the\n * same reason as `gitPushMode`: a resume re-kick must re-derive the same\n * routing even if the host config has since changed. Mirrors config's\n * `HubGitAuthMode`.\n */\n hubGitAuth?: 'gh' | 'app';\n}\n\n/**\n * Last resolved SSH connection target for a box — host/user, the per-box\n * identity file (identity-authed providers: docker localhost sshd, Hetzner),\n * and an optional port (docker publishes its sshd on an ephemeral loopback\n * port; cloud providers use the default 22). Persisted on `BoxRecord.ssh`\n * whenever we're already online (create/start/code/open/shell) so\n * `~/.agentbox/ssh/config` can be regenerated purely from state — the\n * regenerate never hits a provider API or wakes a paused box. The host IP /\n * loopback port can change across stop/start, so it is refreshed on start/resume.\n * Absent for providers with no SSH.\n */\nexport interface SshTargetRecord {\n host: string;\n user: string;\n identityFile?: string;\n port?: number;\n /**\n * SSH jump host (`ProxyJump`), for a box that is not directly reachable but\n * sits behind a machine that is. remote-docker's box is a container on someone\n * else's engine: its sshd is published on THAT machine's loopback, so ssh\n * hops through the engine and dials `127.0.0.1:<port>` from there. Spelled as\n * an ssh destination (`[user@]host[:port]` or an `~/.ssh/config` alias).\n * Absent for providers whose box is directly reachable.\n */\n proxyJump?: string;\n}\n\nexport interface GitWorktreeRecord {\n kind: 'root' | 'nested';\n /** Host path to the main repo whose `.git/` is the source of the worktree. */\n hostMainRepo: string;\n /**\n * Agent-visible container path of the worktree (`/workspace` for root,\n * `/workspace/<sub>` for nested).\n */\n containerPath: string;\n /**\n * Per-box unique path where git registered the worktree. Docker boxes\n * register against the bind-mounted host `.git/`; cloud boxes clone into the\n * sandbox so this is a sandbox-local path. `destroyBox` uses it to deregister\n * a Docker worktree on the host.\n */\n gitWorktreePath: string;\n /** Branch the worktree was created on, e.g. `agentbox/<box-name>`. */\n branch: string;\n /**\n * The last branch the HOST put this box on — its create-time `branch`,\n * updated by host-driven `agentbox git checkout`/`branch`/`pull <branch>`.\n * Distinct from `branch` (which stays the immutable scratch identity used by\n * host-only land, checkout guards, and upstream-sync skip): the relay\n * auto-approves a push only to a scratch branch OR this sanctioned branch,\n * so an in-box agent self-switching to `main` and pushing still prompts.\n * Absent on records written before this field existed → treated as `branch`.\n */\n sanctionedBranch?: string;\n /** Workspace-relative path the repo was found at (empty string for root). */\n relPathFromWorkspace: string;\n}\n\nexport interface BoxRecord {\n id: string;\n name: string;\n /**\n * Cosmetic user-chosen label, set via `agentbox status <box> --set-name`.\n * Purely for display and lookup — unlike `name` it does NOT drive the\n * container, git branch, or Portless URL. Absent means \"fall back to name\".\n * See docs/architecture.md (\"Where state lives\").\n */\n displayName?: string;\n /**\n * Sandbox backend the box runs on. Absent on records written before the\n * multi-provider split — `readState` migrates those to `'docker'` on read.\n */\n provider?: ProviderName;\n /**\n * Unique runtime identifier. For docker records: the container name\n * (`agentbox-<id|name>`) — what `docker exec` resolves. For cloud\n * records: the backend sandbox id, prefixed with `cloud:` so a grep\n * for \"agentbox-cloud-*\" finds nothing (post 7.2) — the cloud\n * sandbox is not a docker container and shouldn't look like one.\n * Docker-internal code should only ever reach this via\n * `requireDockerProvider(box, ...)` first.\n */\n container: string;\n /**\n * The image the box was started from. Docker: base image or checkpoint\n * image tag. Cloud: the resolved sandbox image / snapshot ref (mirrors\n * `box.cloud.image`).\n */\n image: string;\n workspacePath: string;\n /**\n * Optional per-box scratch dir holding a `cp -c` APFS clone of the host\n * workspace, made at create time when `--host-snapshot` is on. Docker only.\n */\n snapshotDir?: string | null;\n /**\n * Host-side path to the agentbox-ctl unix socket bind-mounted into the\n * container at /run/agentbox/ctl.sock. Docker only.\n */\n socketPath?: string;\n /** Docker volume mounted at /home/vscode/.claude inside the box. Docker only. */\n claudeConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.codex inside the box. Docker only. */\n codexConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.agents inside the box (Agent Skills). Docker only. */\n agentsConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.local/share/opencode. Docker only. */\n opencodeConfigVolume?: string;\n /** Every agent's docker config volume, keyed by agent id. Docker only. */\n agentConfigVolumes?: Record<string, string>;\n /** Per-box volume holding `.vscode-server`. Docker only. */\n vscodeServerVolume?: string;\n /** Per-box volume holding `.cursor-server`. Docker only. */\n cursorServerVolume?: string;\n /**\n * Bearer token the in-box supervisor uses to authenticate with the relay.\n * Generated at create time and forwarded as AGENTBOX_RELAY_TOKEN.\n */\n relayToken?: string;\n /** Per-box git worktrees. Empty/absent when the host workspace is not a git checkout. */\n gitWorktrees?: GitWorktreeRecord[];\n /** True when the box was created with --with-playwright. */\n withPlaywright?: boolean;\n /** True when the box was created with --with-env. */\n withEnv?: boolean;\n /**\n * Resolved `box.autoApproveHostActions` at create time. Forwarded to the\n * host relay so host-action confirms (git push, cp, gh writes, checkpoint)\n * auto-resolve to `y` for this box — with an audit event per bypass.\n * Persisted so a `relay` rehydrate re-registers with the same policy.\n */\n autoApproveHostActions?: boolean;\n /**\n * Resolved `box.autoApproveSafeHostActions` at create time (default true).\n * Forwarded to the relay so the SAFE subset of host actions (open PR, PR\n * comments, sanctioned-branch push, contained non-secret file copy, CI\n * rerun, checkpoint, granted host-tool calls) auto-resolves without a prompt.\n * Absent is treated as enabled (default on) by the relay. Persisted so a\n * `relay` rehydrate re-registers with the same policy.\n */\n autoApproveSafeHostActions?: boolean;\n /**\n * Resolved `box.persistent` at create time (`--persistent`). A persistent box\n * is always-on: autopause never pauses it, the cloud keepalive never lets it\n * lapse, `prune` skips it, `destroy` asks even under `-y`, and the relay's\n * boot reconcile starts it again after a host reboot.\n *\n * Persisted on the RECORD rather than read from project config because the\n * relay reads records, not the project's `agentbox.yaml`/config layers — the\n * same reason `autoApproveHostActions` lives here. Absent → not persistent.\n */\n persistent?: boolean;\n /**\n * Carry summary recorded at create time: which host paths were copied into\n * the box from `agentbox.yaml`'s `carry:` block. Audit trail for inspect\n * (the actual file content is not retained — only the src/dest pairs and\n * sizes). Absent when no carry: block was applied.\n */\n carry?: {\n count: number;\n /**\n * `hash` is a content hash of the host source at copy time, used by the\n * on-start resync to re-copy only entries whose host source changed.\n * Absent on records written before resync existed (treated as \"changed\").\n */\n entries: Array<{ src: string; dest: string; bytes: number; hash?: string }>;\n };\n /** VNC stack (Xvnc + websockify + noVNC) is enabled for this box. */\n vncEnabled?: boolean;\n /** Container-side noVNC web port. */\n vncContainerPort?: number;\n /** Host port mapped to the noVNC web server (Docker), or preview port (cloud). */\n vncHostPort?: number;\n /** Per-box password baked into Xvnc's PasswordFile and the auto-connect URL. */\n vncPassword?: string;\n /** Container port reserved for the web service `expose:` forward. */\n webContainerPort?: number;\n /** Host port mapped to container :80 (Docker). */\n webHostPort?: number;\n /** In-box localhost sshd is enabled for this box (Docker). */\n sshEnabled?: boolean;\n /** Container-side sshd port (22). Docker. */\n sshContainerPort?: number;\n /** Ephemeral loopback host port mapped to the container's sshd (Docker). */\n sshHostPort?: number;\n /**\n * Last resolved SSH connection target. Regenerated into `~/.agentbox/ssh/config`\n * by `syncAgentboxSshConfig`. Docker: `127.0.0.1` + the per-box key + the\n * ephemeral `sshHostPort`; cloud (Hetzner): the VPS IP + per-box key.\n */\n ssh?: SshTargetRecord;\n /** Portless route name registered for this box's web port. Docker only. */\n portlessAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box. Docker only. */\n portlessUrl?: string;\n /** Portless route name registered for this box's noVNC port (`vnc-<box-name>`). */\n portlessVncAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box's VNC. */\n portlessVncUrl?: string;\n /** Volume mounted at /var/lib/docker for the in-box dockerd. Docker only. */\n dockerVolume?: string;\n /** True when this box's `dockerVolume` is the shared cache. Docker only. */\n dockerCacheShared?: boolean;\n /** Absolute host path of the project this box belongs to. */\n projectRoot?: string;\n /** Monotonic 1-based index within `projectRoot`. Never recycled. */\n projectIndex?: number;\n /** The checkpoint image tag this box was started from. Docker only. */\n checkpointImage?: string;\n /** Lineage of the checkpoint this box was started from. */\n checkpointSource?: {\n ref: string;\n type: 'layered' | 'flattened';\n /** Checkpoint refs composing the chain, base-most last. */\n chain: string[];\n };\n /** Resource ceilings actually applied at create. */\n resourceLimits?: {\n memoryBytes?: number;\n cpus?: number;\n pidsLimit?: number;\n disk?: string;\n };\n /**\n * Docker-backend-specific fields. Populated alongside the flat fields\n * during the 7.1 transition; once readers migrate, the flat fields go\n * away. New code SHOULD prefer `box.docker?.<field>` and fall back to\n * the flat field via the `dockerField()` helper in `@agentbox/core`.\n */\n docker?: DockerBoxFields;\n /** Cloud-backend-specific fields. Present only for cloud providers. */\n cloud?: CloudBoxFields;\n /**\n * The agent last launched in this box (`agentbox claude` / `codex` /\n * `opencode`). Recorded on every launch (foreground + queued). Durable, unlike\n * the in-box session pointers which are cleared on the running->stopped tmux\n * edge — so it's the signal `agentbox recover` uses to know which agent to\n * relaunch/attach, and the only such signal for an adopted box with no live\n * session.\n */\n lastAgent?: AgentId;\n /**\n * The agents this box was created FOR, as passed to `create`.\n *\n * Durable because the selection has to outlive the create: the resume path\n * re-reconciles agent credentials on every start, and without knowing the set\n * it would re-acquire every agent's tokens and undo the isolation. Absent on\n * boxes created before per-agent selection, which correctly means \"all\".\n */\n agents?: string[];\n /**\n * Other agents' logins seeded into this box as model-provider auth, as\n * passed to `create` (`borrowCredentials`). Durable so the credential\n * fan-out can reach a box that consumes a login it does not run, and so a\n * clone can borrow the same set. One-way: never a source for extraction.\n */\n borrowedCredentials?: string[];\n createdAt: string; // ISO-8601\n}\n\n/**\n * Read a Docker-specific field with fallback to the legacy flat slot.\n * Prefer this over `box.field` directly while the 7.1 migration is in\n * flight — once the flat fields are removed, this collapses to\n * `box.docker?.[key]` and the migration is mechanical.\n */\nexport function dockerField<K extends keyof DockerBoxFields>(\n box: BoxRecord,\n key: K,\n): DockerBoxFields[K] | undefined {\n if (box.docker && box.docker[key] !== undefined) return box.docker[key];\n // Fall back to the flat copy. Container / image are required at the\n // BoxRecord top level so they always exist as flat fields today.\n return (box as unknown as Record<string, unknown>)[key as string] as\n | DockerBoxFields[K]\n | undefined;\n}\n\n/**\n * One agent's docker config volume, or undefined when the box has none for it.\n *\n * Prefers the keyed map and falls back to the three legacy named fields, so a\n * box recorded before the map existed keeps answering. Every consumer goes\n * through here: the per-agent `switch` statements this replaced had a `default:`\n * arm returning opencode's volume, which silently handed a fourth agent\n * someone else's credentials store.\n */\nexport function agentConfigVolume(box: BoxRecord, agent: string): string | undefined {\n const map = dockerField(box, 'agentConfigVolumes');\n const fromMap = map?.[agent];\n if (fromMap !== undefined) return fromMap;\n if (agent === 'claude') return dockerField(box, 'claudeConfigVolume');\n if (agent === 'codex') return dockerField(box, 'codexConfigVolume');\n if (agent === 'opencode') return dockerField(box, 'opencodeConfigVolume');\n return undefined;\n}\n\nexport interface StateFile {\n version: 1;\n boxes: BoxRecord[];\n}\n\nexport type FindBoxResult =\n | { kind: 'ok'; box: BoxRecord }\n | { kind: 'none' }\n | { kind: 'ambiguous'; matches: BoxRecord[] };\n","/**\n * `AgentSyncSpec` — the single source of truth for every per-agent datum the\n * sync layer needs: paths, credential locations, forwarded env keys, install\n * recipes, capabilities.\n *\n * **DATA ONLY, and that is what makes an agent packageable.** Every field is a\n * string, array or plain object — nothing function-valued — so a spec can be\n * read synchronously and offline by code that must never `import()` the agent\n * it describes: the relay (whose bundle carries no workspace packages at all),\n * the hub, and `sandbox-core`, which everything depends on. Per-agent\n * *behavior* lives in that agent's own package.\n *\n * It lives in `@agentbox/core` — the zero-internal-dep leaf — rather than in\n * `sandbox-core`, so an agent package can declare its own row without importing\n * anything that would import it back. Moving it here is what lets the registry\n * be assembled FROM the agent packages instead of listing them.\n */\n\nimport type { AgentId } from './agent-kind.js';\n\n/**\n * Canonical agent id. Re-exported from `@agentbox/core` rather than redeclared:\n * one open string type, one home.\n */\nexport type { AgentId };\n\n/**\n * One host static-config source dir and where it lands inside the box. Most\n * tools have exactly one; OpenCode has three (data / config / state), which is\n * why this is a list — its layout becomes data instead of tool-specific control\n * flow.\n */\nexport interface AgentPathMap {\n /** Host source dir, as path segments relative to `os.homedir()` (e.g. `['.claude']`). */\n hostHomeRel: string[];\n /** Absolute box dir the source's static config is mounted/extracted at. */\n boxDir: string;\n /**\n * Sub-path under `boxDir` to land this source at (OpenCode: config →\n * `config`, state → `.state/opencode`). Absent ⇒ land at `boxDir` root.\n */\n relocToSubpath?: string;\n /** rsync `--update` (newest-wins) — OpenCode `model.json` is two-way state. */\n update?: boolean;\n /**\n * Which staging tarball carries this source.\n *\n * `'static'` (the default) is the one-way host config baked into a cloud\n * provider's snapshot. `'state'` marks two-way runtime state that ships on\n * its own newest-wins path and must NOT be baked — a snapshot is shared by\n * every box made from it, so a per-box state file in one would be handed to\n * all of them.\n */\n stagedAs?: 'static' | 'state';\n /**\n * rsync/tar `--exclude` patterns for this source. Populated per tool as the\n * static-config concern migrates (Phase 7); OpenCode's are already exact.\n */\n exclude?: string[];\n /**\n * rsync `--include` carve-ins for this source. Consumers MUST emit these\n * before the excludes (rsync filter rules are first-match-wins) — used to\n * re-include a subtree of an otherwise-excluded dir (codex:\n * `.tmp/marketplaces/` out of the excluded `.tmp`).\n */\n include?: string[];\n /**\n * Opt out of {@link LIVE_DATABASE_EXCLUDES} for this source.\n *\n * Only for a source whose databases are genuinely static content. Nothing\n * declares it today, and a new declarer should say why: copying a live SQLite\n * file is not a copy of the database (see the constant's note).\n */\n allowDatabases?: boolean;\n}\n\n/**\n * Files that are a live database's on-disk representation, never safe to copy.\n *\n * A running agent keeps its data in a write-ahead log, so the main file alone is\n * stale or empty and the triple copied together is a torn read. Measured on a\n * real box: codex's `state_5.sqlite` was 4 KB with a 1.79 MB `-wal`.\n *\n * Applied to EVERY agent's push rather than enumerated per agent, because that\n * enumeration is what went stale: codex's list named `state_*` and `logs_*`, and\n * three later databases (`goals_1`, `memories_1`, `queue_1` — plus their\n * `-wal`/`-shm`) shipped into every box, carrying cross-project thread goals and\n * extracted memories with them. Verified identical under `tar --exclude` and\n * `rsync --exclude`, matching at any depth and sparing names like `notes.dbg`.\n *\n * An agent that needs a database IN the box gets it from the agent itself, which\n * rebuilds these from real state — never from a byte-copy of the host's.\n */\nexport const LIVE_DATABASE_EXCLUDES: readonly string[] = ['*.sqlite*', '*.db', '*.db-*'];\n\n/**\n * Where a push is going. The difference is the CREDENTIAL file, and it is not a\n * per-agent quirk:\n *\n * - `'snapshot'` — a cloud provider's baked base, SHARED by every box made from\n * it. The credential must not be in there; it ships per-box afterwards.\n * - `'volume'` — the box's own docker config volume, which IS its credential\n * store. Excluding it there would leave the agent logged out.\n */\nexport type AgentPushTarget = 'snapshot' | 'volume';\n\n/**\n * Every `--exclude` pattern one static source contributes, for one target.\n *\n * One function so the two transports cannot drift — and they had: each agent's\n * excludes existed as spec data AND again as a hardcoded rsync string, with the\n * docker copy missing `snapshot` for opencode and five host-identity files\n * (`installation_id`, `version.json`, …) for codex.\n *\n * The credential file is DERIVED from `spec.credential.boxRelPath` rather than\n * listed, which is why the specs no longer name it: it is the one entry whose\n * correct value differs by target, and deriving it is what makes a single list\n * safe for both. An agent that declares no credential contributes no such entry.\n */\nexport function agentPushExcludes(\n spec: AgentSyncSpec,\n path: AgentPathMap,\n target: AgentPushTarget,\n): string[] {\n return [\n ...(path.allowDatabases ? [] : LIVE_DATABASE_EXCLUDES),\n ...(path.exclude ?? []),\n // An agent with no credential (`credential` absent) contributes nothing\n // here: there is no file to keep out of a shared snapshot.\n ...(target === 'snapshot' && spec.credential ? [spec.credential.boxRelPath] : []),\n ];\n}\n\n/** Where this tool's login credential lives on the box, on the host backup, and in the cloud volume. */\nexport interface AgentCredential {\n /** File the agent reads/writes, relative to its primary box dir. */\n boxRelPath: string;\n /** Canonical absolute in-box path (for the box→host `cat` extract). */\n boxAbsPath: string;\n /** Host backup under `~/.agentbox` that survives box destroys. */\n hostBackup: string;\n /** Cloud shared-credentials-volume mount for this agent. */\n cloudMountPath: string;\n /** Sub-dir of the shared cloud credentials volume for this agent. */\n cloudSubpath: string;\n /**\n * What a *real* (usable, non-placeholder) credential file must contain — the\n * box→host extract guard (`isRealAgentCredential`). `claude-oauth` requires a\n * non-empty `claudeAiOauth.refreshToken` (a setup-token blob has an\n * accessToken but no refreshToken and must not clobber a good backup);\n * `nonempty-json` (codex/opencode `auth.json`) just has to parse as a\n * non-empty JSON object. Encodes the per-agent switch that used to live inside\n * the docker credential helper.\n */\n realShape: 'claude-oauth' | 'nonempty-json';\n /**\n * How to tell which of two credential blobs is NEWER, when the agent's\n * credential carries an ordering field.\n *\n * `jsonPath` names a numeric JSON property (a ms-epoch expiry); the larger\n * value wins. Absent means the agent has no ordering information and the rule\n * falls back to last-writer-wins — correct for a static token, wrong for a\n * ROTATING one, which is why claude declares it: an OAuth refresh rotates the\n * refresh token, so accepting an older blob does not merely go stale, it kills\n * the login for every other box that holds the newer one.\n *\n * DATA rather than a module hook, deliberately. The fan-out that consumes it\n * runs in `agentbox-relay`, a separately spawned process bundled from\n * `@agentbox/relay` alone which never registers agent modules — a hook there\n * would silently degrade claude to last-writer-wins. The relay already reads\n * the registry synchronously, so data works everywhere the rule is needed.\n *\n * Kept off the `agents.list` descriptor on purpose: ctl never orders blobs (it\n * shape-validates and posts), so this is a host-side concern in the same\n * category as `hostBackup`, which the descriptor already strips.\n *\n * Deliberately NOT expressed by widening `realShape`: ctl drops a watch whose\n * shape it does not recognise, and an empty watch list makes it fall back to\n * the list baked into its image — which for a plugin agent, never bakeable,\n * means no credential watch at all.\n */\n freshness?: { jsonPath: readonly string[] };\n}\n\n/**\n * This agent's credential, for a call site that only works with one.\n *\n * `credential` is optional, but some code exists only to move a credential —\n * claude's host-backup guards, pi's volume extract, the custody upload set.\n * Those callers already know their agent has one, and a `?? ''` fallback at\n * each site would turn a spec change into a silent write to the wrong path.\n * A throw here means a spec changed under a mechanism that requires the field.\n */\nexport function requireAgentCredential(spec: AgentSyncSpec): AgentCredential {\n if (!spec.credential) {\n throw new Error(\n `agent '${spec.id}' declares no credential — this code path requires one; ` +\n `gate on \\`spec.credential\\` before calling it`,\n );\n }\n return spec.credential;\n}\n\n/**\n * One agentbox-OWNED file that has to be placed where the agent will load it.\n *\n * These are not user config and never touch the host: an activity hook, a\n * plugin, a skill. They are baked into every provider's base image at\n * `bakedPath` and copied into the agent's config root on every create/start, so\n * an image upgrade propagates instead of a stale copy pinning an old version in\n * a long-lived shared volume.\n *\n * Data rather than three near-identical `seed*` functions: the copy step was\n * the only per-agent part, and having it live in `@agentbox/sandbox-docker`\n * meant the cloud providers silently did not do it at all (a cloud OpenCode box\n * never got its state plugin, so it reported `unknown` activity forever).\n */\nexport interface AgentSeedSpec {\n /** Absolute in-image source. Baked into every provider base. */\n bakedPath: string;\n /**\n * Destination, RELATIVE to `staticPaths[0].boxDir` — which is both the docker\n * config volume's root and the in-box config dir, so one string serves the\n * volume copy and the in-box copy.\n */\n destRel: string;\n /**\n * Basename under the CLI's staged `runtime/_shared/`, used as the host-side\n * source when `bakedPath` is absent. That happens for real: a base snapshot\n * baked before the asset existed never carries it, and the VPS providers\n * never shipped the OpenCode plugin at all. Uploading from the host is what\n * lets the fix land without re-baking every provider's snapshot.\n */\n sharedAsset: string;\n /** Short human label for log lines (\"Codex activity hooks\"). */\n label: string;\n}\n\n/**\n * How ctl should run a `surface: 'service'` agent, as ctl's own unit shapes.\n *\n * FIELD-FOR-FIELD WITH `ServiceSpec`/`TaskSpec` in `packages/ctl/src/config.ts`,\n * on purpose. The synthesizer that turns this into supervisor units is then a\n * field copy rather than a translation layer, and a field ctl grows later is one\n * line here instead of a new mapping decision. What it is NOT is a second\n * `agentbox.yaml` parser: the yaml's snake_case keys stay in ctl's parser; this\n * is the already-parsed shape.\n *\n * Data, like the rest of the spec — it rides `agents.list` into a box whose\n * `agentbox-ctl` was baked before this agent existed.\n */\nexport interface AgentServiceSpec {\n /** ctl unit name. A unit of the same name in `/workspace/agentbox.yaml` WINS. */\n name: string;\n command: string | string[];\n /** Working dir for the process. Absent ⇒ the supervisor's workspace. */\n cwd?: string;\n env?: Record<string, string>;\n /** Exactly one of the three is used, in the order `http`, `port`, `logMatch`. */\n readyWhen?: AgentServiceReadyWhen;\n /**\n * Publish this service on the box's web URL. `as` must be the reserved web\n * port (80) — it is the only port a box publishes.\n */\n expose?: AgentServiceExpose;\n /**\n * The daemon refuses any request carrying forwarded headers, so its URL must\n * reach it with no reverse proxy in the path.\n *\n * A box normally publishes its web service behind Portless, which gives it a\n * stable `https://<box>.localhost` that resolves the same on the host and\n * inside the box. Portless always adds `X-Forwarded-*`. A daemon that treats\n * those headers as a security signal then refuses to serve — OpenClaw answers\n * `403 proxy_attribution_required`, and no amount of its own configuration\n * helps, because it additionally requires the FORWARDED CLIENT to be\n * non-loopback and a browser on the same machine never is.\n *\n * Setting this makes AgentBox skip the Portless WEB alias for the box, which\n * is the whole mechanism: every URL producer already falls back to the\n * directly published port when no alias is registered, and the in-box browser\n * falls back to the service's own loopback port. The VNC alias is unaffected.\n *\n * The cost is real — the box has no friendly name, its URL carries a host\n * port that changes on every restart, and host and in-box URLs stop matching\n * — so set it only for a daemon that has actually been observed rejecting a\n * proxied request.\n */\n rejectsProxyHeaders?: boolean;\n /**\n * Argv for an interactive CLIENT of this daemon — what `agentbox attach` and\n * `agentbox open --in <app>` should open. NOT a shell line: it is passed as\n * argv, so nothing here is word-split or glob-expanded.\n *\n * This is not an \"attach to the agent\" in the TUI sense and does not make the\n * agent a TUI one — there is still no agent session. The daemon runs under\n * ctl either way; this is a terminal talking to it, and it is data precisely\n * so the attach path can implement it once for every service agent rather\n * than per agent.\n *\n * Point it at a client that talks to the ALREADY-RUNNING daemon. OpenClaw's\n * `tui` connects to the gateway; its `chat`/`terminal` aliases are\n * `tui --local`, which start a second, embedded runtime and ignore the\n * gateway the box exists to host — the wrong thing here.\n *\n * Absent means there is no such client, and attach says so rather than\n * opening a bare shell.\n */\n repl?: readonly string[];\n restart?: 'always' | 'on-failure' | 'never';\n /** Other unit names this service waits for. */\n needs?: readonly string[];\n /** One-shot units run before the service — onboard, render. */\n tasks?: readonly AgentServiceTask[];\n /**\n * Extra values `agentbox <agent> url` prints beside the URL, read out of the\n * daemon's own config file in the box.\n *\n * For the thing a hosted UI asks for that its URL alone does not carry — a\n * gateway token pasted into a Control UI on first load. Declared as data\n * (file + dotted path) rather than an agent-specific `url` implementation,\n * because the only per-agent parts are where to read and what to call it.\n *\n * WHY NOT THE TOOL'S OWN `config get`: openclaw's answers\n * `__OPENCLAW_REDACTED__` for exactly this key, which is the correct default\n * for a CLI and useless here. Reading the raw JSON is the way round it.\n *\n * These are SECRETS. A value is fetched only when the user asks for it, and\n * never persisted on the box record or logged.\n */\n urlFields?: readonly AgentServiceUrlField[];\n}\n\n/**\n * One value `<agent> url` reads out of the running box — typically the auth\n * token a daemon generated for itself, which the host cannot know any other way.\n *\n * Two sources, and `command` is the one to reach for. A daemon that can print\n * its own connection details (`openclaw dashboard --json`) is offering a\n * SUPPORTED interface; reading its config file instead means depending on a\n * private layout that can move under us, and the failure when it does is a link\n * that silently opens to a login prompt. `file` stays for a daemon that offers\n * no such command.\n */\nexport interface AgentServiceUrlField {\n /** Printed before the value (`token`). */\n label: string;\n /** Absolute in-box path of a JSON file to read. Mutually exclusive with `command`. */\n file?: string;\n /**\n * A command run IN THE BOX whose stdout is JSON. Preferred over `file`.\n * Must not need a TTY, must not open anything (pass the daemon's own\n * `--no-open`-style flag), and must not be the one that starts the service.\n */\n command?: readonly string[];\n /** Dotted path into that JSON — `gateway.auth.token`, or `url`. */\n jsonPath: string;\n /**\n * When the value at `jsonPath` is itself a URL carrying the token in its\n * FRAGMENT (openclaw's `dashboard` prints `http://127.0.0.1:18789/#token=…`),\n * this names the fragment parameter to lift out of it.\n *\n * The rest of that URL is deliberately discarded: it is the daemon's own\n * loopback address inside the box, and the host reaches the box on a\n * different one.\n */\n fromUrlFragment?: string;\n /**\n * When set, this value also belongs in the URL's FRAGMENT under this key, and\n * `<agent> url` prints a ready-to-open link alongside the bare URL —\n * `<url>/#token=<value>`.\n *\n * A fragment rather than a query string because that is where these daemons\n * put it (openclaw's Control UI reads `#token=`), and it is the half of a URL\n * a browser never sends to the server, so the secret stays out of access logs\n * and `Referer` headers.\n */\n fragmentKey?: string;\n}\n\n/** A ready probe, one of three kinds. Mirrors ctl's `ReadyProbe` inputs. */\nexport interface AgentServiceReadyWhen {\n /** URL ctl polls until it answers 2xx. */\n http?: string;\n /** TCP port on 127.0.0.1 ctl polls until it accepts. */\n port?: number;\n /** Regex source matched against the service's own log lines. */\n logMatch?: string;\n}\n\n/** `expose:` — container port `as` forwards to `127.0.0.1:port`. */\nexport interface AgentServiceExpose {\n port: number;\n as: number;\n}\n\n/** A one-shot unit that runs before the service. Mirrors ctl's `TaskSpec`. */\nexport interface AgentServiceTask {\n name: string;\n command: string | string[];\n cwd?: string;\n env?: Record<string, string>;\n needs?: readonly string[];\n /**\n * `'marker'` — ctl stores a marker keyed by the resolved command, so a warm\n * boot skips it and editing the command re-runs it. `{ check }` — run the\n * probe first; exit 0 means already satisfied.\n */\n runOnce?: 'marker' | { check: string };\n}\n\n/**\n * Layered config for an agent whose own config file AgentBox owns a LAYER of.\n *\n * The problem it solves: the tool underneath gets updated, its factory defaults\n * gain keys, and the user has hand-edited the file in the box. A plain\n * regenerate loses their edits; never regenerating means they never get the new\n * defaults.\n *\n * THE MERGE IS THE TOOL'S JOB, NOT OURS. `applyCmd` is a command the tool\n * already ships that takes a config patch on stdin and merges it into its own\n * file, validating as it goes. Delegating buys three things a hand-rolled merge\n * cannot: no format parser (the tool owns its own syntax), no shadow copy of the\n * file, and a render that keeps working across the tool's own config\n * migrations — which is the entire point of the mechanism. An agent whose tool\n * has no such command simply does not declare `configRender`.\n *\n * What AgentBox keeps for itself is the small half: which keys it is asserting\n * this time. `agentbox-ctl agent render <id>` diffs the `agentbox.yaml` overlay\n * against the overlay it applied last time and sends only what changed, so a key\n * the user edited in-box is never re-asserted unless they edited the overlay\n * too.\n *\n * Secrets NEVER belong in the overlay: real values ride a `carry:` entry into a\n * 0600 env file and the overlay references them by name. `agent render` lints\n * for a secret-shaped literal under the overlay key and warns.\n */\nexport interface AgentConfigRenderSpec {\n /**\n * Absolute in-box path of the tool's config file.\n *\n * The render itself never writes it — `applyCmd` does. It is here for the\n * reads AgentBox must do on its own (a token the tool's `config get`\n * redacts) and to anchor the overlay record that sits beside it.\n */\n file: string;\n /** Top-level `agentbox.yaml` key holding the user's overlay for this agent. */\n overlayKey: string;\n /**\n * The tool's own patch command. It receives the changed overlay keys as JSON\n * on stdin and is expected to merge them into {@link file} recursively.\n */\n applyCmd: string;\n /**\n * Flag that turns {@link applyCmd} into a no-write check, run first so a bad\n * overlay fails before anything is written. Absent means the tool has none and\n * the apply is the only gate.\n */\n dryRunFlag?: string;\n /** Command run after the apply; a non-zero exit fails the render loudly. */\n validate?: string;\n}\n\n/** Capabilities that genuinely differ per tool (drive resume/teleport/activity wiring). */\nexport interface AgentCapabilities {\n /**\n * What an agent IS, from the product's point of view.\n *\n * - `tui` (the default when absent) — an interactive tool the user attaches\n * to: a tmux session, a wrapped pty, `attach`/`start`/`login`.\n * - `service` — a long-running daemon the box HOSTS. It has no session to\n * attach to; its unit is run by ctl's supervisor, its state is read from\n * the supervisor rather than from a tmux probe, and its CLI command ends at\n * \"service ready + URL printed\".\n *\n * DECLARED, never derived from the id. Everything that behaves differently for\n * a daemon reads this field, so a second service agent needs no new branch\n * anywhere — the same rule `caps.resume` and `caps.teleport` already follow.\n */\n surface?: 'tui' | 'service';\n /** Session resume supported (`--resume`). OpenCode: false. */\n resume: boolean;\n /** Session-teleport support. OpenCode: a stub that throws. */\n teleport: 'full' | 'stub';\n /**\n * Why teleport is a stub, in the user's words. Required in spirit whenever\n * `teleport: 'stub'` — it is what the refusal actually prints.\n *\n * Data, not a thrown-from-a-module string, so declaring `teleport: 'stub'` is\n * all an agent has to do to get a good refusal: no per-agent `case` in\n * `prepareTeleport`, no module of its own. Falls back to a generic message.\n */\n teleportStubReason?: string;\n /**\n * Every mechanism that reports this agent's in-box activity. A LIST because\n * the real answer is plural and a single value described it wrongly: Claude is\n * hooks-primary with a promote-only scraper backstop, Codex declares hooks but\n * is scraper-primary in practice (its own hooks file calls itself\n * defense-in-depth), and OpenCode is plugin-only.\n *\n * - `hooks` — the agent invokes `agentbox-ctl agent-state` from its own\n * lifecycle hooks.\n * - `plugin` — an agentbox-seeded plugin reports on the agent's event bus.\n * Implies `seeds` (asserted by `agent-seed.test.ts`) — the plugin has to\n * reach the box for this to be true.\n * - `scraper` — ctl watches the agent's tmux pane. Only meaningful for an\n * agent ctl actually ships a scraper for; declaring it does not create one.\n *\n * EMPTY means the agent reports nothing, and ctl will not probe its session at\n * all — a permanently-`unknown` entry in every snapshot is worse than absence.\n */\n activitySource: readonly ('hooks' | 'plugin' | 'scraper')[];\n}\n\n/**\n * How to put this agent's binary into a box that doesn't have it.\n *\n * One recipe, two execution sites: the Dockerfile/provider install scripts read\n * it at BAKE time (`AGENTBOX_AGENTS`), and `ensureAgentInstalled` runs it at\n * RUN time against a live box. Keeping it as data is what lets a box carry only\n * the agent it was launched for and still gain another on demand.\n */\nexport type AgentInstallRecipe =\n /** `npm install -g <package>`. `allowScripts` for packages with lifecycle scripts (npm 12+ blocks them by default). */\n | { kind: 'npm'; package: string; allowScripts?: boolean }\n /** Fetch an installer to a file and run it. NOT `curl | bash` — a blocked download must fail the chain, not exit 0. */\n | { kind: 'script'; url: string; retries?: number }\n /** Anything else: a shell snippet run as-is. */\n | { kind: 'exec'; script: string };\n\nexport interface AgentInstall {\n recipe: AgentInstallRecipe;\n /**\n * Who runs the recipe. Not a detail — Claude's native installer drops the\n * binary in the INVOKING user's `~/.local/bin`, so running it as root puts\n * `claude` in /root and the box user never sees it. `npm install -g` is the\n * opposite and needs root. `apt` is always root regardless.\n */\n runAs: 'root' | 'box-user';\n /**\n * OS packages the agent needs alongside its own installer (codex: bubblewrap).\n * Installed with whichever package manager the box has -- see\n * `renderPackageInstall`; boxes are Debian/Ubuntu except Vercel (AL2023/dnf).\n */\n packages?: string[];\n /**\n * True when the agent still works without those packages, just degraded.\n * An optional prerequisite that fails logs and continues; a required one\n * aborts the install. Default (undefined) is REQUIRED, so a new prerequisite\n * has to opt into being skippable rather than silently becoming so.\n */\n packagesOptional?: boolean;\n /** Shell run after the recipe succeeds (dirs, symlinks, ownership). Runs as root. */\n postInstall?: string;\n /**\n * Alternate ways to install the same agent, keyed by the value of the setting\n * named in {@link alternatesFrom}.\n *\n * Claude is the only declarer: `claude.install: npm` is the documented escape\n * hatch for hosts whose egress IP the Claude CDN 403s. Without this the\n * setting would silently do nothing now that the install lives here rather\n * than in a Dockerfile branch.\n */\n alternates?: Record<string, Omit<AgentInstall, 'alternates' | 'alternatesFrom'>>;\n /**\n * Which of the agent's declared {@link AgentSyncSpec.settings} selects\n * {@link alternates}. Present iff `alternates` is.\n *\n * Named explicitly rather than by a reserved key so a drift test can assert\n * the setting exists and is an enum whose values cover the map's keys — a\n * naming convention cannot be checked.\n */\n alternatesFrom?: string;\n}\n\n/**\n * Pick the install for this agent's resolved settings, falling back to the\n * default recipe.\n *\n * Generic on purpose: which setting selects an alternate is the AGENT's\n * declaration (`alternatesFrom`), so nothing here knows what `install` means.\n */\nexport function resolveAgentInstall(\n install: AgentInstall,\n settings?: AgentSettings,\n): Omit<AgentInstall, 'alternates' | 'alternatesFrom'> {\n const key = install.alternatesFrom;\n const chosen = key ? settings?.[key] : undefined;\n const alt = typeof chosen === 'string' ? install.alternates?.[chosen] : undefined;\n return alt ?? install;\n}\n\n/**\n * One agent's resolved settings — its own config block with the declared\n * defaults applied. Opaque to everything but the agent that declared them.\n */\nexport type AgentSettings = Readonly<Record<string, string | boolean>>;\n\n/**\n * A setting an agent declares for itself.\n *\n * WHY THIS IS NOT A ROLE-NAMED FIELD. `claude.install` and `claude.tui` really\n * are Claude-specific — one picks between Anthropic's installer and the npm\n * package, the other picks between Claude Code's two renderers. Generalising\n * their NAMES would be a lie; what generalises is the MECHANISM: an agent\n * declares its settings, config generates the keys, every call site carries an\n * opaque bag, and the agent's own recipe / `postInstall` / launch env is the\n * only thing that knows what they mean.\n *\n * Pure JSON like the rest of the spec, so a setting survives `agentbox agent\n * add`'s snapshot into `~/.agentbox/agents.json` and a community agent gets\n * real `agentbox config set` keys with no change to this repo.\n */\nexport interface AgentSettingSpec {\n /** Leaf key under the agent's own config block: `claude.install`. */\n key: string;\n type: 'string' | 'bool' | 'enum' | 'enum-list';\n /**\n * Required when `type` is `enum` or `enum-list`; the accepted values.\n *\n * `enum-list` holds a comma-separated SUBSET of these in one string, so the\n * value stays scalar everywhere it is carried — config, the JSON schema, and\n * the `AGENTBOX_AGENT_SETTING_*` export are all string-shaped by contract.\n * A sentinel meaning \"none of them\" is only legal on its own.\n */\n enumValues?: readonly string[];\n /** Applied when the user set nothing. Also what the fingerprint fold treats as absent. */\n default: string | boolean;\n /** Shown by `agentbox config list` and the docs table. */\n description: string;\n /** Hide from the default `config list` view, like the per-provider keys. */\n advanced?: boolean;\n /**\n * This setting changes what a BAKE produces, so it folds into\n * `variantFingerprint` and two values are two artifacts.\n *\n * Runtime-only settings must NOT set it — claude's `tui` rides the launch\n * env, and folding it would re-bake a whole base image for a renderer flip.\n */\n affectsBake?: boolean;\n}\n\n/**\n * One host-held model-provider credential a box may be seeded with.\n *\n * Two kinds, because the host holds these two ways and a picker that offered\n * only the first could never express a provider with no agent behind it (xAI):\n *\n * - `agent` — another agent's login FILE. The host lands it at that agent's\n * own `credential.boxAbsPath`, 0600, exactly where a runtime install would\n * put it, and the consumer's `ingest` turns it into its own store.\n * - `env` — a provider API key held in the host's environment, forwarded into\n * the box. There is nothing to import: the key IS the auth.\n */\nexport type AgentModelAuthSource =\n | {\n kind: 'agent';\n /** The agent whose `credential` is borrowed. Must declare one. */\n agent: AgentId;\n /** Shown by the picker and by `--model-auth`'s help. */\n label: string;\n /** Shown beside the choice when consuming this login carries a caveat. */\n caveat?: string;\n }\n | {\n kind: 'env';\n /** Host env var holding the key; the same name it is set under in the box. */\n envKey: string;\n label: string;\n /** Who it authenticates to, when `label` does not say it: 'xAI (Grok)'. */\n provider?: string;\n caveat?: string;\n };\n\n/**\n * How a box turns a seeded `agent` source into this agent's own auth state.\n *\n * AgentBox never learns the consuming agent's auth format; the row owns that.\n * Two shapes because the two agent surfaces have different places to run one:\n *\n * - `serviceTask` names an entry in the agent's OWN `service.tasks`, ordered\n * in its DAG (openclaw's import runs after onboard, before the gateway).\n * - `command` is for an agent with no service DAG. The HOST runs it in the box\n * at the launch seam — after the binary is installed, before the session\n * starts — because a TUI agent has no supervisor unit to hang it on and\n * ctl's wire cannot express a task without a service.\n *\n * Absent means nothing needs importing, which is the correct answer for a row\n * whose only sources are `env`.\n */\nexport type AgentModelAuthIngest =\n | { kind: 'serviceTask'; task: string }\n | {\n kind: 'command';\n /** Unique across the registry; used in logs and as the marker basename. */\n name: string;\n /** Shell script. Must be idempotent and exit 0 on nothing-to-do. */\n command: string;\n };\n\n/**\n * Which host model-provider credentials this agent may be seeded with.\n *\n * Seeding is ONE-WAY. The box is a consumer of that credential, never a source:\n * `box.agents` still gates box->host extraction, the resume reconcile and the\n * credential watch, so a copy the box has since rewritten in its own store is\n * never read back over the host's.\n *\n * MEASURED, and it shapes the refresh story: a borrowed Codex login works in a\n * pi/opencode box until its access token expires, but the box cannot renew it —\n * the consumer's refresh call rejects a codex-issued refresh token\n * (`invalid_state`). Renewal therefore rides the existing credential fan-out,\n * which re-pushes the host's refreshed login and re-runs `ingest`. That is why\n * an ingest must gate on a hash of the SEED, so a re-pushed login re-imports.\n */\nexport interface AgentModelAuthSpec {\n sources: readonly AgentModelAuthSource[];\n ingest?: AgentModelAuthIngest;\n /**\n * Ask at create time when nothing else decided.\n *\n * Opt-IN, and absent means the row is only ever driven by `--model-auth` or\n * its `<agent>.modelAuth` key. A coding agent already has its own sign-in and\n * usually its own login, so a question on every create would be noise for a\n * capability most boxes do not want; a service agent has no TUI to log in\n * through, which is why openclaw asks.\n */\n promptOnCreate?: boolean;\n}\n\n/**\n * The stable id `--model-auth`, `<agent>.modelAuth` and `BoxRecord` use.\n *\n * An agent id stays BARE (`codex`) and an env key is prefixed\n * (`env:XAI_API_KEY`). Agent ids never contain `:`, so this is unambiguous, and\n * every `--model-auth codex` invocation and stored config value keeps working\n * verbatim.\n */\nexport function modelAuthSourceId(s: AgentModelAuthSource): string {\n return s.kind === 'agent' ? s.agent : `env:${s.envKey}`;\n}\n\n/**\n * Split an `enum-list` setting value into its members.\n *\n * Trims, drops empties, dedupes, preserves order. `''` is `[]` — an empty list\n * is a legal value, not an error.\n *\n * Membership is validated by the config layer against `enumValues`. Whether a\n * particular sentinel (`none`) may be combined with real members is the OWNING\n * feature's rule, not a property of the type, so it is enforced where that\n * meaning lives.\n */\nexport function enumListMembers(raw: string): string[] {\n const seen = new Set<string>();\n for (const part of raw.split(',')) {\n const v = part.trim();\n if (v.length > 0) seen.add(v);\n }\n return [...seen];\n}\n\n/** The env key an `env:`-prefixed source id names, or undefined for an agent id. */\nexport function modelAuthEnvKey(id: string): string | undefined {\n return id.startsWith('env:') ? id.slice(4) : undefined;\n}\n\nexport interface AgentSyncSpec {\n id: AgentId;\n /** Alternate spellings that resolve to this spec (reconciles the wire `'claude-code'`). */\n aliases: string[];\n /**\n * The FROZEN wire/queue spelling, when it differs from `id` (claude only).\n * Carried here so a caller that needs the queue name doesn't re-derive it —\n * `buildPromptArgs` / `assertAgentCredsAvailable` want `'claude-code'` while\n * everything else wants `'claude'`.\n */\n wireId?: string;\n /**\n * Keep this agent out of user-facing listings — pickers, `--help`, the install\n * wizard, the `--agents` bake list. It stays fully real everywhere else: the\n * registry resolves it, the machinery iterates it, its box works.\n *\n * For an agent that exists to exercise the seam rather than to be used. The\n * repo's fourth agent is a deliberate canary: every layer that still needs\n * hand-wiring to support a new agent fails loudly while it is present, which\n * is a running count of how far \"an agent is a package\" actually goes.\n */\n hidden?: boolean;\n /** Default tmux session name. */\n sessionName: string;\n /** Command name to probe with `command -v` — how we tell \"already installed\". */\n binary: string;\n /** How to install the binary into a box that lacks it. */\n install: AgentInstall;\n /** Shared docker config volume for this tool's static config. */\n dockerVolume: string;\n /** Host→box static-config source map (1 entry for claude/codex, 3 for opencode). */\n staticPaths: AgentPathMap[];\n /**\n * What a CLONE of a box running this agent has to do differently — the files\n * it must not copy, the ones it must rewrite for the new box, and the\n * per-box secrets it needs before it can be a separate instance at all.\n *\n * Data, not a hook: the hub runs the clone, and a package-provided agent\n * reaches it as JSON in `~/.agentbox/agents.json` — neither can call a\n * function (`spec-purity.test.ts` forbids one).\n */\n clone?: AgentCloneSpec;\n /**\n * Where this agent's login credential lives, when it HAS one.\n *\n * ABSENT MEANS \"this agent has no host-side credential to sync\". That is a\n * declaration, not a shortcut for \"not wired up yet\". An agent that\n * authenticates inside the box — openclaw generates its gateway token during\n * `openclaw onboard` — has nothing on the host to back up, push, watch or fan\n * out, and every mechanism skips it: no credentials-volume mount, no\n * `agents.list` credential watch, no relay fan-out entry, no host backup probe.\n *\n * Omitting is the only correct way to say that. Naming a path nothing writes\n * buys a no-op at the cost of a fictional file every consumer has to know\n * about. Pointing it at the agent's real config is worse: the credential watch\n * is FANOUT by contract (`buildAgentDescriptors` emits `sync: 'fanout'` for\n * every credential it sees), so one box's identity would be copied into every\n * other box.\n */\n credential?: AgentCredential;\n /** Host env keys forwarded into the box so an env-authed agent finds its creds. */\n forwardedEnvKeys: readonly string[];\n /**\n * Extra box run-env (OpenCode: `OPENCODE_CONFIG_DIR`, `XDG_STATE_HOME`).\n *\n * Plain data, not a function: the whole spec has to stay JSON-serializable so\n * it can be shipped into a box whose `agentbox-ctl` was baked before the agent\n * existed. A closure here would foreclose that.\n */\n boxRunEnv: Record<string, string>;\n /**\n * Agentbox-owned files seeded into this agent's config root on create/start.\n * See {@link AgentSeedSpec}. Absent means the agent needs no seeding.\n */\n seeds?: readonly AgentSeedSpec[];\n /**\n * Extra argv prepended to every launch of this agent's binary, for flags it\n * needs in order to LOAD what `seeds` placed (codex will not read a\n * `hooks.json` without `--enable hooks --dangerously-bypass-hook-trust`).\n *\n * Prepended, never appended: codex's `resume` is a SUBCOMMAND and global\n * flags have to precede it.\n */\n launchFlags?: readonly string[];\n /**\n * Environment that pins the agent's in-box terminal renderer, keyed by mode.\n *\n * Data rather than code because the alternative was a `binary === 'claude'`\n * branch at each launch site — and claude is only the agent this happens to\n * matter for TODAY, not the only one it could ever matter for. An agent with\n * no renderer to pin omits the field and gets an empty env.\n *\n * Claude's entry exists because its `fullscreen` renderer repaints\n * differentially: it skips cells it believes are already blank, which over a\n * network transport leaves stale characters behind in the GAPS of the text.\n * The variables are Claude Code's own overrides (verified against v2.1.250)\n * and beat the `tui` key in `~/.claude/settings.json`, so the pin holds\n * whatever a box's settings volume carries. Reported upstream behaviour, not\n * an AgentBox bug — `agentbox shell` is clean, and so is `/tui default`.\n *\n * Forwarded on the launch itself (`docker exec -e`, the cloud inner command),\n * NOT written to `/etc/agentbox/box.env`: tmux runs the binary directly rather\n * than through a login shell, so it would never source that file, and a\n * container's `docker run` env is immutable — a box created before the setting\n * existed would keep the old renderer forever.\n */\n tuiEnv?: Readonly<Record<string, Readonly<Record<string, string>>>>;\n /**\n * Which of {@link settings} selects {@link tuiEnv}'s mode. Present iff\n * `tuiEnv` is — see {@link AgentInstall.alternatesFrom} for why the binding is\n * explicit rather than a reserved key name.\n */\n tuiEnvFrom?: string;\n /**\n * Settings this agent declares for itself. `@agentbox/config` generates a\n * `<id>.<key>` config key from each one, for a built-in and for an\n * `agentbox agent add`-installed package alike.\n *\n * The resolved values reach the agent three ways, all of them opaque to\n * shared code: `alternatesFrom` picks an install recipe, `tuiEnvFrom` picks a\n * launch env, and every value is exported as\n * `AGENTBOX_AGENT_SETTING_<UPPER_SNAKE_KEY>` before the agent's own `recipe`\n * and `postInstall` run — which is the escape hatch for a setting nothing in\n * this repo was written to understand.\n */\n settings?: readonly AgentSettingSpec[];\n caps: AgentCapabilities;\n /**\n * The ctl unit that RUNS this agent. Present iff `caps.surface === 'service'`\n * (asserted by `agent-service-spec.test.ts`); a TUI agent is launched into a\n * tmux session instead and declares nothing here.\n */\n service?: AgentServiceSpec;\n /**\n * Layered rendering of this agent's own config file. Independent of `service`\n * — a TUI agent could want it too — which is why it is its own field rather\n * than a member of {@link AgentServiceSpec}.\n */\n configRender?: AgentConfigRenderSpec;\n /**\n * Box->host (`agentbox download <agent>`) descriptor.\n *\n * Separate from `staticPaths` on purpose: that field's `exclude`/`include` are\n * PUSH-direction hygiene (claude drops `projects`/`sessions` on the way in),\n * while the pull's real filters are different ones. Reusing it verbatim would\n * be wrong in both directions. The ROOTS do map one-to-one, which is why\n * `agentBoxDir` derives them from `staticPaths[0].boxDir` instead of\n * restating them.\n *\n * Absent means the agent has no box->host sync — which is the silent gap that\n * made `download` easy to forget when adding an agent.\n */\n pull?: AgentPullSpec;\n /**\n * What a FULL state capture (`agentbox download --backup`) must leave behind.\n *\n * A backup is the one direction that deliberately keeps the agent's IDENTITY\n * — for openclaw the gateway token, the config journal key and the live\n * session state — because a restore that produces a different bot has not\n * restored anything. So it cannot reuse `staticPaths[].exclude`, which is\n * push-direction hygiene and is precisely that identity.\n *\n * What must still be dropped is anything keyed to the box it came from. The\n * motivating case is openclaw's `tmp/openclaw-<uid>/` lock databases: the box\n * user's uid differs per provider (docker 1000, vercel 1001, e2b 1002), so\n * carrying them across a provider switch restores garbage.\n *\n * Live databases are excluded from the tree copy for every agent regardless\n * ({@link LIVE_DATABASE_EXCLUDES}) and captured separately through SQLite's\n * online-backup API — a byte copy of a live WAL triple is a torn read.\n */\n stateBackup?: AgentStateBackupSpec;\n /**\n * Host-held model-provider credentials this agent may be seeded with — another\n * agent's login file, a provider API key from the host env — and how it\n * ingests them. See {@link AgentModelAuthSpec}.\n *\n * Absent means the agent authenticates to its model providers by itself and\n * the picker offers it nothing.\n */\n modelAuth?: AgentModelAuthSpec;\n /**\n * Extra in-box files ctl should watch, beyond `credential` (which is always\n * watched). This is the hook a custom agent uses to say \"sync these back\".\n *\n * The credential watch is implicit and always `fanout`; anything declared here\n * defaults to `backup` — see `AgentWatchSpec.sync`.\n */\n watch?: readonly AgentWatchSpec[];\n}\n\n/**\n * One host file a clone needs a PER-BOX copy of. The point is that two bots\n * cloned from one workspace must not share a channel token: the source path is\n * keyed by box name, so each instance reads its own file.\n *\n * `optional` is honoured on an ordinary create (a first box has nobody to\n * collide with, and refusing would make the agent's own example unrunnable) and\n * NEVER on a clone, where a missing file is the whole failure being prevented.\n */\nexport interface AgentPerBoxCarry {\n /** Host path. `~/` and `{{AGENTBOX_BOX_NAME}}` are expanded. */\n src: string;\n /** In-box destination; `~/` is the box user's home. */\n dest: string;\n /** Octal mode for the copy in the box, e.g. `0o600`. */\n mode?: number;\n /** Skip silently when `src` is missing. Ignored on a clone. */\n optional?: boolean;\n}\n\n/** How a clone of a box running this agent differs. See `AgentSyncSpec.clone`. */\nexport interface AgentCloneSpec {\n /**\n * Workspace-relative files a clone does NOT copy, because the agent\n * regenerates them for the new box (openclaw's `AGENTS.md`, `USER.md`).\n * Matched at the workspace ROOT only, so a user's `docs/AGENTS.md` survives.\n */\n drop?: readonly string[];\n /**\n * Workspace-relative files a clone copies and then RENDERS with the\n * workspace's `identity` replacements rule-set, so the new bot's own name\n * replaces the source bot's (openclaw's `SOUL.md`, `IDENTITY.md`).\n *\n * Rendered once, at clone time, on the host: the file is a normal workspace\n * file afterwards and a bot that edits its own `SOUL.md` is never reset.\n */\n render?: readonly string[];\n /** Host files this agent needs a per-box copy of. */\n perBoxCarry?: readonly AgentPerBoxCarry[];\n}\n\n/** What a full state capture must leave behind. See `AgentSyncSpec.stateBackup`. */\nexport interface AgentStateBackupSpec {\n /**\n * Paths under the agent's state root, relative, dropped from the capture.\n * Read as tar `--exclude` patterns, so a bare name matches at any depth.\n */\n exclude?: readonly string[];\n}\n\n/** One extra file an agent asks ctl to watch. */\nexport interface AgentWatchSpec {\n /** Absolute in-box path. */\n path: string;\n /**\n * `backup` (default) lands the file on the host and stops. `fanout` also\n * re-distributes it to every other box, which is correct ONLY for a rotating\n * secret — an agent's own logs or transcripts must never fan out.\n */\n sync?: 'fanout' | 'backup';\n /** Host destination, relative to the box's host workspace. */\n hostDest?: string;\n}\n\n/**\n * How `download <agent>` enumerates what a box has that the host doesn't.\n *\n * Two strategies because the agents genuinely differ in SHAPE, not just data:\n * codex/opencode are flat item lists, while claude's unit is \"child of a\n * category dir\" plus a 2-level plugin cache and a JSON registry merge. A single\n * strategy would have to model claude's case for everyone.\n */\nexport interface AgentPullSpec {\n /**\n * Flat items (files or dirs) directly under a root — codex, opencode.\n * `group` selects which root: `data` is `staticPaths[0].boxDir`, any other\n * value is that dir plus the matching entry's `relocToSubpath`.\n */\n items?: readonly { group: string; names: readonly string[] }[];\n /**\n * Roots that exist ONLY in the pull direction, named directly rather than\n * resolved through `staticPaths`.\n *\n * Session logs are the motivating case and are genuinely pull-only: you would\n * never PUSH transcripts into a box, and every agent's `staticPaths.exclude`\n * already drops them on the way in (claude: `projects`/`sessions`/\n * `history.jsonl`; codex: `sessions`/`archived_sessions`/`log`; opencode:\n * `storage`/`log`/`snapshot`). With groups resolving only through\n * `staticPaths`, such a location had nowhere to be declared.\n *\n * Roots that exist in BOTH directions keep deriving from `staticPaths` — this\n * is an alternative, not a replacement.\n */\n roots?: readonly {\n /** Group name referenced by `items[].group`. */\n group: string;\n /** Absolute in-box directory. */\n boxDir: string;\n /** Host destination, as path segments under `os.homedir()`. */\n hostHomeRel: readonly string[];\n }[];\n /**\n * Directories whose CHILDREN are the unit — claude's `skills`/`agents`/\n * `commands`. Each child dir is one item.\n */\n categories?: readonly string[];\n /**\n * JSON files merged additively rather than copied — claude's plugin\n * registries. `projection` names the sub-object holding the entries (`root`\n * for a flat map). Never overwrites an existing host key.\n */\n jsonMerges?: readonly { rel: string; projection: 'root' | 'plugins' }[];\n}\n\n/**\n * The box user's NAME, not uid: the vscode uid differs per provider\n * (docker/hetzner 1000, vercel 1001, e2b 1002) but the name is stable.\n */\nexport const BOX_USER = 'vscode';\nexport const BOX_HOME = '/home/vscode';\n/** Where a cloud credential volume mounts, pivoted into each agent's real path. */\nexport const BOX_CREDS_DIR = `${BOX_HOME}/.agentbox-creds`;\n\n/**\n * The `postInstall` prelude every agent needs: its own config dir owned by the\n * box user, and its subdir of the credentials mount.\n *\n * `BOX_CREDS_DIR` IS NOT A NORMAL DIRECTORY AT RUNTIME. On the cloud providers\n * it is where the shared credentials volume mounts, and on Daytona that mount\n * is virtiofs: it presents `drwxrwxrwx root root` and rejects `chown`/`chmod`\n * with EPERM *even for root*. So the ownership of anything under it is\n * best-effort — the box user can already write it, and the mount ignores the\n * bits either way.\n *\n * Recipes used to fold both dirs into one `install -d -o vscode -g vscode`,\n * which chmods and chowns what it creates. That worked at BAKE time (no volume\n * mounted yet) and failed every runtime install on Daytona with\n * `cannot change owner and permissions of '…/.agentbox-creds/<agent>'`, so an\n * agent missing from a snapshot could never be installed into a live box.\n */\nexport function agentDirPrelude(agentDirs: readonly string[], credsSubdir?: string): string[] {\n return [\n `install -d -o ${BOX_USER} -g ${BOX_USER} ${agentDirs.join(' ')}`,\n // Omitted for an agent that declares no `credential`: it gets no subpath of\n // the shared credentials volume, so creating a dir there would reserve a\n // mount point nothing will ever mount.\n ...(credsSubdir === undefined\n ? []\n : [\n `mkdir -p ${BOX_CREDS_DIR}/${credsSubdir}`,\n `chown -R ${BOX_USER}:${BOX_USER} ${BOX_CREDS_DIR} 2>/dev/null || true`,\n ]),\n ];\n}\n/**\n * Where a provider's base image bakes AgentBox's own shared assets.\n *\n * Named once rather than spelled out at each use: the staging that puts a file\n * there runs on the host, while the code that reads it runs inside the box, and\n * the two packages have to agree on the path.\n */\nexport const BOX_ASSET_DIR = '/usr/local/share/agentbox';\n\n/** Baked into every provider's base image; the source for the wizard skill. */\nexport const SETUP_GUIDE_PATH = `${BOX_ASSET_DIR}/setup-guide.md`;\n/**\n * The `replacements:` rule-set a clone renders an agent's identity files with,\n * and the comment that marks it as written by the identity wizard.\n *\n * One definition because three places have to agree: the wizard skill writes\n * them, the box facts stop nudging once the sentinel is present, and a CLONE\n * strips both — the rules describe the SOURCE bot's name, so leaving them in\n * the copy makes the NEXT clone rewrite a name that is no longer there.\n */\nexport const IDENTITY_RULE_SET = 'identity';\nexport const IDENTITY_RULES_SENTINEL = 'agentbox:identity-rules';\n\n/**\n * Does this agent run as a ctl service rather than a tmux TUI?\n *\n * One reader of `caps.surface` instead of `spec.caps.surface === 'service'`\n * repeated at every call site, so the default (\"absent means tui\") is stated\n * once and cannot drift.\n */\nexport function isServiceAgent(spec: { caps: AgentCapabilities }): boolean {\n return spec.caps.surface === 'service';\n}\n","/**\n * Persistent (always-on) boxes: who defaults to one, which providers can host\n * one, and the refusal text for the ones that can't.\n *\n * e2b and vercel run their boxes as Firecracker microVMs with a HARD per-session\n * cap (E2B Hobby 1h, Vercel Hobby ~45m). The host keepalive can push the\n * death-time out within that cap but cannot remove it, so a box created there\n * lapses whatever `persistent` says — hence a refusal by name rather than a\n * warning.\n */\n\nimport { isServiceAgent } from './sync/agent-spec.js';\nimport type { AgentCapabilities } from './sync/agent-spec.js';\n\n/** Providers whose session cap makes an always-on box impossible. */\nexport const PERSISTENT_UNSUPPORTED: Readonly<Record<string, string>> = {\n e2b: 'E2B sandboxes carry a platform session cap (1h on Hobby, 24h on Pro) that the host keepalive can extend within, never remove — the box would lapse on its own',\n vercel:\n 'Vercel Sandboxes carry a platform session cap (~45m on Hobby, ~5h on Pro+) that the host keepalive can extend within, never remove — the box would lapse on its own',\n};\n\n/**\n * The refusal message for `--persistent` / `box.persistent` on `provider`, or\n * `null` when the provider can host an always-on box.\n */\nexport function persistentRefusal(provider: string): string | null {\n const why = PERSISTENT_UNSUPPORTED[provider];\n if (!why) return null;\n return (\n `--persistent is not supported on ${provider}: ${why}. ` +\n 'Use a provider with no session cap: docker, hetzner, digitalocean, remote-docker, or daytona.'\n );\n}\n\n/**\n * The `persistent` a create should carry, or `undefined` to leave the decision\n * to the config layers (`box.persistent`).\n *\n * The rule lives here, beside the refusal, so the whole always-on policy is one\n * file: who defaults to an always-on box, and which providers cannot host one.\n *\n * A **service agent** defaults to one. Its box hosts a daemon — a gateway that\n * is only useful while it is reachable — so an autopause or an idle lapse is an\n * outage, not a saving. That is derived from `caps.surface`, never from an agent\n * id: a new service agent gets the right default from its registry row alone.\n *\n * Returning `undefined` rather than `false` for the ordinary case is\n * load-bearing: `false` would OVERRIDE a user's `box.persistent = true`, turning\n * \"no opinion\" into an opt-out. Only an explicit `--no-persistent` says false.\n */\nexport function resolveCreatePersistent(input: {\n /** Registry row of the agent the box is FOR, if any. */\n spec?: { caps: AgentCapabilities } | undefined;\n /** `--persistent` / `--no-persistent`; `undefined` when neither was passed. */\n flag?: boolean | undefined;\n}): boolean | undefined {\n if (input.flag !== undefined) return input.flag;\n if (input.spec && isServiceAgent(input.spec)) return true;\n return undefined;\n}\n","/**\n * In-box port websockify serves the noVNC client on. Fixed by Dockerfile.box and\n * mirrored by `CLOUD_VNC_PORT` in @agentbox/sandbox-cloud.\n */\nexport const NOVNC_PORT = 6080;\n\n/**\n * The complete noVNC viewer URL for a box: `<base>/vnc.html?autoconnect=1&password=…`.\n *\n * `base` is a scheme+host(+port) origin — a Portless alias, an OrbStack name, a\n * loopback host port, or a cloud provider's signed preview URL. Trailing slashes\n * are stripped so the concat stays canonical, and the password is URL-encoded\n * (generateVncPassword's alphabet is already safe, a hand-set one may not be).\n */\nexport function buildNoVncUrl(base: string, password: string): string {\n return `${base.replace(/\\/+$/, '')}/vnc.html?autoconnect=1&password=${encodeURIComponent(password)}`;\n}\n","/**\n * Provider-neutral text-replacement engine. Pure (no fs / no yaml) so it can be\n * shared by the host carry path (`renderCarryEntries`) and the in-box\n * `agentbox-ctl render` CLI without a dependency cycle. The yaml/fs loaders that\n * read a `replacements:` block live in `@agentbox/ctl` (which has those deps).\n */\n\n/**\n * The fixed set of `{{NAME}}` placeholders that `replaceEnvs` / `--env`\n * substitution recognizes. Deliberately a whitelist (not \"any env var\") so a\n * rendered file is predictable: a stray `{{FOO}}` is left untouched rather than\n * silently clobbered, and secrets/tokens are never substitutable.\n */\nexport const PLACEHOLDER_KEYS = [\n 'AGENTBOX_BOX_NAME',\n 'AGENTBOX_BOX_ID',\n 'AGENTBOX_BOX_KIND',\n 'AGENTBOX_HOST_WORKSPACE',\n 'AGENTBOX_PROJECT_ROOT',\n // Convenience: the host this box is reachable at. Derived from\n // AGENTBOX_BOX_NAME as `<box-name>.localhost` when not set explicitly (the\n // portless host for docker/hetzner). Public-URL cloud providers\n // (vercel/daytona/e2b) set it explicitly at boot to the real preview host\n // (e.g. `<sub>.vercel.run`), which then wins over the derived fallback.\n 'AGENTBOX_BOX_HOST',\n] as const;\n\nexport type PlaceholderKey = (typeof PLACEHOLDER_KEYS)[number];\n\nconst PLACEHOLDER_SET = new Set<string>(PLACEHOLDER_KEYS);\n\n/** A single regex/literal substitution. `to` may itself contain placeholders. */\nexport interface ReplaceRule {\n from: string;\n to: string;\n /** Treat `from` as a JS regex (with `flags`); otherwise a literal string. */\n regex?: boolean;\n /** Regex flags (default `g`). Ignored unless `regex` is true. */\n flags?: string;\n}\n\nexport class ReplaceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ReplaceError';\n }\n}\n\nconst PLACEHOLDER_RE = /\\{\\{\\s*([A-Z0-9_]+)\\s*\\}\\}/g;\n\n/**\n * Replace `{{NAME}}` placeholders whose NAME is in {@link PLACEHOLDER_KEYS}\n * with the matching value from `context`. Unknown names (not whitelisted) are\n * left as-is. Whitelisted names with no value in `context` are also left as-is\n * (and reported via `onWarn`).\n */\nexport function substitutePlaceholders(\n text: string,\n context: Record<string, string>,\n onWarn?: (msg: string) => void,\n): string {\n return text.replace(PLACEHOLDER_RE, (match, name: string) => {\n if (!PLACEHOLDER_SET.has(name)) return match;\n const value = context[name];\n if (value === undefined) {\n onWarn?.(`placeholder {{${name}}} has no value in this context — left untouched`);\n return match;\n }\n return value;\n });\n}\n\nexport interface ApplyReplacementsOptions {\n /** When true, substitute `{{NAME}}` whitelist placeholders across the file. */\n env?: boolean;\n /** Ordered custom rules applied after (or instead of) placeholder env subst. */\n rules?: ReplaceRule[];\n /** Placeholder values (used by both `env` subst and rule `to` strings). */\n context: Record<string, string>;\n onWarn?: (msg: string) => void;\n}\n\n/**\n * Apply env-placeholder substitution and/or custom rules to file content.\n * Rules run in declaration order; each rule's `to` string is itself run through\n * placeholder substitution so `to: '.{{AGENTBOX_BOX_NAME}}.localhost'` works\n * regardless of `env`.\n */\nexport function applyReplacements(content: string, opts: ApplyReplacementsOptions): string {\n let out = content;\n if (opts.env) {\n out = substitutePlaceholders(out, opts.context, opts.onWarn);\n }\n for (const rule of opts.rules ?? []) {\n const to = substitutePlaceholders(rule.to, opts.context, opts.onWarn);\n if (rule.regex) {\n let re: RegExp;\n try {\n re = new RegExp(rule.from, rule.flags ?? 'g');\n } catch (err) {\n throw new ReplaceError(\n `invalid regex \"${rule.from}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n out = out.replace(re, to);\n } else {\n // Literal: split/join so `$`/special chars in either side stay literal.\n out = out.split(rule.from).join(to);\n }\n }\n return out;\n}\n\n/**\n * Fill in `AGENTBOX_BOX_HOST` (the published portless host, `<box-name>.localhost`)\n * from `AGENTBOX_BOX_NAME` when it isn't already set. Single source of truth for\n * the host-derivation rule, shared by every placeholder-context builder. Mutates\n * and returns `ctx`.\n */\nexport function deriveBoxHost(ctx: Record<string, string>): Record<string, string> {\n if (ctx.AGENTBOX_BOX_HOST === undefined && ctx.AGENTBOX_BOX_NAME !== undefined) {\n ctx.AGENTBOX_BOX_HOST = `${ctx.AGENTBOX_BOX_NAME}.localhost`;\n }\n return ctx;\n}\n\n/** Build the whitelist placeholder context from a process environment. */\nexport function placeholderContextFromEnv(\n env: NodeJS.ProcessEnv = process.env,\n): Record<string, string> {\n const ctx: Record<string, string> = {};\n for (const key of PLACEHOLDER_KEYS) {\n const v = env[key];\n if (typeof v === 'string' && v.length > 0) ctx[key] = v;\n }\n return deriveBoxHost(ctx);\n}\n\n// --- rule parsing (shared by config top-level `replacements:` and the CLI) ---\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nconst RULE_KEYS = new Set(['from', 'to', 'regex', 'flags']);\n\n/** Parse one rule mapping (from `replacements:` blocks or carry `replace:`). */\nexport function parseReplaceRule(raw: unknown, where: string): ReplaceRule {\n if (!isPlainObject(raw)) {\n throw new ReplaceError(`${where} must be a mapping with at least { from, to }`);\n }\n for (const key of Object.keys(raw)) {\n if (!RULE_KEYS.has(key)) throw new ReplaceError(`${where} has unknown key \"${key}\"`);\n }\n if (typeof raw.from !== 'string' || raw.from.length === 0) {\n throw new ReplaceError(`${where}.from must be a non-empty string`);\n }\n if (typeof raw.to !== 'string') {\n throw new ReplaceError(`${where}.to must be a string`);\n }\n const rule: ReplaceRule = { from: raw.from, to: raw.to };\n if (raw.regex !== undefined && raw.regex !== null) {\n if (typeof raw.regex !== 'boolean') throw new ReplaceError(`${where}.regex must be a boolean`);\n rule.regex = raw.regex;\n }\n if (raw.flags !== undefined && raw.flags !== null) {\n if (typeof raw.flags !== 'string') throw new ReplaceError(`${where}.flags must be a string`);\n rule.flags = raw.flags;\n }\n if (rule.regex) {\n try {\n new RegExp(rule.from, rule.flags ?? 'g');\n } catch (err) {\n throw new ReplaceError(\n `${where}.from is not a valid regex: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n return rule;\n}\n\n/** Parse a list of rules (carry `replace:` or a `replacements:` named set). */\nexport function parseReplaceRules(raw: unknown, where: string): ReplaceRule[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) throw new ReplaceError(`${where} must be a list of rules`);\n return raw.map((r, i) => parseReplaceRule(r, `${where}[${String(i)}]`));\n}\n\n/** Parse the top-level `replacements:` block: name → rule list. */\nexport function parseReplacements(raw: unknown): Record<string, ReplaceRule[]> {\n if (raw === undefined || raw === null) return {};\n if (!isPlainObject(raw)) {\n throw new ReplaceError('replacements must be a mapping of name → rule list');\n }\n const out: Record<string, ReplaceRule[]> = {};\n for (const [name, rules] of Object.entries(raw)) {\n if (!/^[A-Za-z0-9_-]+$/.test(name)) {\n throw new ReplaceError(`replacements.${name}: name must match [A-Za-z0-9_-]+`);\n }\n out[name] = parseReplaceRules(rules, `replacements.${name}`);\n }\n return out;\n}\n\n/**\n * Resolve a list of named rule-set references against a `replacements:` map,\n * concatenating their rules in reference order. Throws on an unknown name.\n */\nexport function resolveRuleRefs(\n refs: string[],\n replacements: Record<string, ReplaceRule[]>,\n where: string,\n): ReplaceRule[] {\n const out: ReplaceRule[] = [];\n for (const name of refs) {\n const set = replacements[name];\n if (set === undefined) {\n const known = Object.keys(replacements);\n throw new ReplaceError(\n `${where}: unknown replacements rule-set \"${name}\"` +\n (known.length > 0 ? ` (known: ${known.join(', ')})` : ' (none declared)'),\n );\n }\n out.push(...set);\n }\n return out;\n}\n\n/** Parse a CLI `--rule 'from=>to'` argument into a rule. `regex` opt-in. */\nexport function parseRuleArg(arg: string, regex: boolean): ReplaceRule {\n const idx = arg.indexOf('=>');\n if (idx === -1) {\n throw new ReplaceError(`--rule \"${arg}\" must be of the form 'from=>to'`);\n }\n const from = arg.slice(0, idx);\n const to = arg.slice(idx + 2);\n if (from.length === 0) throw new ReplaceError(`--rule \"${arg}\" has an empty 'from'`);\n return parseReplaceRule({ from, to, ...(regex ? { regex: true } : {}) }, `--rule \"${arg}\"`);\n}\n","/**\n * Provider-neutral box-resolution errors. Thrown by the box-ref resolver and\n * caught by the CLI's lifecycle error handler. They carry the query (and, for\n * the ambiguous case, the candidate records) so the CLI can render a useful\n * hint.\n */\n\nimport type { BoxRecord } from './box-record.js';\n\n/**\n * Marker class for expected, actionable failures that the CLI should render\n * to the user as a clean message (no stack trace) — e.g. \"you skipped a\n * required `agentbox prepare` step\". The top-level CLI catch in\n * `apps/cli/src/index.ts` detects this via `instanceof` and falls back to the\n * `name` field so bundling / dual-publish boundaries can't lose the marker.\n */\nexport class UserFacingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'UserFacingError';\n }\n}\n\nexport class BoxNotFoundError extends Error {\n constructor(public readonly query: string) {\n super(`no agentbox matches \"${query}\"`);\n this.name = 'BoxNotFoundError';\n }\n}\n\nexport class AmbiguousBoxError extends Error {\n constructor(\n public readonly query: string,\n public readonly matches: BoxRecord[],\n ) {\n const ids = matches.map((m) => m.id).join(', ');\n super(`\"${query}\" matches multiple boxes: ${ids}`);\n this.name = 'AmbiguousBoxError';\n }\n}\n","import { randomBytes } from 'node:crypto';\n\n/**\n * Stable identity helpers shared across providers. Currently just the per-box\n * id mint; checkpoint ids etc. can join later under their own prefix.\n */\n\n/**\n * Type tag prefixed to every minted box id so the kind is readable at a glance\n * and id namespaces can grow without colliding (reserve `c` for checkpoints,\n * etc.). The leading non-digit is load-bearing: it guarantees a box id is never\n * an all-decimal string, which would otherwise collide with the per-project\n * numeric index in `resolveBoxRef` (`agentbox open 4`) and make all-digit ids\n * unresolvable.\n */\nexport const BOX_ID_PREFIX = 'b';\n\nexport function generateBoxId(): string {\n return `${BOX_ID_PREFIX}${randomBytes(4).toString('hex')}`;\n}\n","/**\n * The wire schema for a question AgentBox asks a human before it does something\n * at the host boundary — copying `carry:` files into a box, seeding a box with\n * another agent's login, granting a host CLI.\n *\n * One shape, four front-ends. The CLI renders it with clack, the hub web and the\n * macOS tray render it as a panel, and a future client renders it without either\n * of them changing: a client that understands only {@link PromptRequest} can\n * always ask the question and post a valid answer. {@link PromptDetail} is the\n * opt-in half — a client that recognises a variant draws it properly (a file\n * table, a credential card) and one that does not falls back to its `summary`.\n *\n * The gates that ask are asker-agnostic: they take a {@link PromptAsker} rather\n * than calling a prompt library, so the same gate serves a TTY, an HTTP\n * preflight, and a recorded answer map.\n */\n\nimport { createHash } from 'node:crypto';\n\n/**\n * Which widget a client must render. `open-link` is the odd one out: it is not a\n * question but a link the box wants opened on the human's own machine, so a\n * client answers it by opening the URL itself and reporting `openedByClient`.\n * A client that doesn't know the kind falls back to a confirm, and a plain `y`\n * makes the host open it — the pre-`open-link` behavior.\n */\nexport type PromptKind = 'confirm' | 'select' | 'text' | 'open-link';\n\n/** One option of a `select`. */\nexport interface PromptChoice {\n value: string;\n label: string;\n /** Second line, when the option carries a caveat worth reading before picking. */\n hint?: string;\n /** Risky/destructive — a client may style it apart. */\n danger?: boolean;\n /**\n * In a `multiple` select this option means \"none of the others\" — a\n * multi-aware client draws it apart from the checkboxes. Meaningless without\n * {@link PromptRequest.multiple}, where every option is already exclusive,\n * which is exactly what lets an older client render it as an ordinary choice\n * and still produce a valid answer.\n */\n exclusive?: boolean;\n}\n\n/** One row of a {@link PromptFileTableDetail}. */\nexport interface PromptFileRow {\n /** Source as the user wrote it, not the realpath. */\n src: string;\n dest: string;\n /** Absent for `missing`. */\n bytes?: number;\n kind: 'file' | 'dir' | 'missing';\n /** Already formatted octal, e.g. `0600`. */\n mode?: string;\n /** Numeric uid, when the entry pins one. */\n user?: number;\n /** Free-form tags: `optional`, `dir`, `symlink-outside-home`. */\n flags: string[];\n /** The row deserves visual weight — it is why the question is being asked. */\n warn?: boolean;\n}\n\n/** Files about to be copied somewhere. */\nexport interface PromptFileTableDetail {\n type: 'file-table';\n summary: string;\n rows: PromptFileRow[];\n totalBytes: number;\n}\n\n/** One host login about to be handed to a box. */\nexport interface PromptCredentialDetail {\n type: 'credential';\n summary: string;\n /** The agent whose login this is (`codex`), not the one consuming it. */\n agent: string;\n label: string;\n caveat?: string;\n hostPath: string;\n boxPath: string;\n bytes?: number;\n}\n\n/**\n * One row of a {@link PromptCredentialListDetail}.\n *\n * Every field past `value`/`source`/`label` is optional because the two source\n * kinds populate different ones, and because a client decoding this strictly\n * must not fail on a row shaped for the other kind.\n */\nexport interface PromptCredentialRow {\n /**\n * The {@link PromptChoice.value} this row describes. The join between the\n * detail and the choices, so a multi-select client can draw the row AS the\n * checkbox rather than pairing two unrelated lists by index.\n */\n value: string;\n /** How the host holds it: a login file to copy, or an env var to forward. */\n source: 'file' | 'env';\n label: string;\n /** Who it authenticates to, when `label` does not say it. */\n provider?: string;\n caveat?: string;\n /** `source: 'file'` only. */\n hostPath?: string;\n boxPath?: string;\n bytes?: number;\n /** `source: 'env'` only: the variable NAME. The VALUE never goes on this wire. */\n envVar?: string;\n /** Deserves visual weight — mirrors {@link PromptFileRow.warn}. */\n warn?: boolean;\n}\n\n/**\n * Several host logins offered together.\n *\n * A separate `type` from {@link PromptCredentialDetail} rather than a widening\n * of it, because that variant's `hostPath`/`boxPath` are load-bearing in shipped\n * clients: the macOS tray decodes them as non-optional, so a `credential` detail\n * describing an env-backed source would fail its whole preflight decode and the\n * user would be shown no prompts at all. A new type degrades to `summary`\n * instead, which is what every variant carries it for.\n */\nexport interface PromptCredentialListDetail {\n type: 'credential-list';\n /** Must be a real, readable list — a shipped client renders ONLY this. */\n summary: string;\n rows: PromptCredentialRow[];\n}\n\n/** Nothing structured to say — `summary` is the whole detail. */\nexport interface PromptTextDetail {\n type: 'text';\n summary: string;\n}\n\n/**\n * Typed extra content a client MAY render richly.\n *\n * Every variant carries `summary`, plain text, so a client that does not know\n * the variant still renders something correct rather than nothing. New variants\n * are therefore additive: an older client degrades, it does not break.\n */\nexport type PromptDetail =\n | PromptFileTableDetail\n | PromptCredentialDetail\n | PromptCredentialListDetail\n | PromptTextDetail;\n\n/** What an asker does when it cannot reach a human. */\nexport interface PromptFallback {\n value: string;\n /** Said out loud when the fallback is taken, so it is never a silent default. */\n reason: string;\n}\n\nexport interface PromptRequest {\n /**\n * `<topic>:<digest>` — content-addressed over the question itself (see\n * {@link promptId}). An answer therefore cannot be replayed onto a question\n * that has since changed: the id no longer matches and the caller refuses.\n */\n id: string;\n /** Machine-stable reason this prompt exists: `carry`, `model-auth`, `tools`. */\n topic: string;\n kind: PromptKind;\n /**\n * Two or three words for a card header (\"Copy credentials\"), with {@link title}\n * as the line under it. Optional: a client without a header slot — the CLI —\n * shows only `title`, which is always the actual question.\n */\n heading?: string;\n /** The question itself. Always present, and always answerable on its own. */\n title: string;\n body?: string;\n /** Required for `select`; ignored otherwise. */\n choices?: PromptChoice[];\n /**\n * `select` only: several choices may be picked at once, and the answer is\n * their values joined by {@link PROMPT_MULTI_SEPARATOR}.\n *\n * Deliberately a flag rather than a fourth {@link PromptKind}. A client that\n * has never heard of it still sees a `kind` it is obliged to render, draws a\n * plain single select, and posts ONE value — which is the n=1 encoding of the\n * same answer. It degrades to a strictly valid subset instead of guessing at\n * an unknown widget. No choice `value` in such a request may contain the\n * separator.\n */\n multiple?: boolean;\n /** Pre-selected choice / prefilled text. For `confirm`, `'y'` or `'n'`. */\n defaultValue?: string;\n detail?: PromptDetail;\n fallback: PromptFallback;\n /**\n * There is no safe fallback: an asker that cannot reach a human must refuse\n * rather than take `fallback`. Set by prompts whose silent answer would move\n * secrets (`carry:`).\n */\n required?: boolean;\n /**\n * The exact sentence to print when there is no way to ask — the flags or env\n * vars that decide the question up front. Owned by the gate, because only the\n * gate knows its own escape hatches.\n */\n nonInteractiveHint?: string;\n}\n\nexport interface PromptAnswer {\n id: string;\n value: string;\n /** The user dismissed rather than chose (Esc / closing the panel). */\n cancelled?: boolean;\n}\n\n/**\n * The one seam every gate takes instead of calling a prompt library.\n *\n * Implementations: a clack-backed asker in the CLI, a collecting asker that\n * turns a gate into an HTTP preflight, and a map-backed asker that replays the\n * answers a client posted back.\n */\nexport type PromptAsker = (req: PromptRequest) => Promise<PromptAnswer>;\n\n/**\n * Content-address a question: `<topic>:<12 hex of sha256(topic + payload)>`.\n *\n * `payload` must be canonical — the same question must serialize identically on\n * every run, or a preflight answer would never match the create that replays it.\n * Callers pass a stable projection of what they are asking about (the resolved\n * carry table, the borrow list), never a timestamp or an absolute temp path.\n */\nexport function promptId(topic: string, payload: unknown): string {\n const digest = createHash('sha256')\n .update(topic)\n .update(' ')\n .update(JSON.stringify(payload) ?? 'null')\n .digest('hex')\n .slice(0, 12);\n return `${topic}:${digest}`;\n}\n\n/**\n * Separator for the answer to a `multiple` select.\n *\n * A comma is safe for every value space that uses one today — agent ids are\n * lowercase slugs, env var names are `[A-Z0-9_]` — and that is a RULE, not an\n * accident: a gate must not offer a choice whose `value` contains it.\n */\nexport const PROMPT_MULTI_SEPARATOR = ',';\n\n/** Join chosen values. One value encodes to itself — see {@link decodeMultiAnswer}. */\nexport function encodeMultiAnswer(values: readonly string[]): string {\n return values.join(PROMPT_MULTI_SEPARATOR);\n}\n\n/**\n * Split a multi answer.\n *\n * `'codex'` -> `['codex']` is the whole point: a client that rendered a\n * `multiple` select as a plain single select posts one bare value, and that is\n * already a valid answer rather than a case to detect. `''` -> `[]`.\n */\nexport function decodeMultiAnswer(value: string): string[] {\n const seen = new Set<string>();\n for (const part of value.split(PROMPT_MULTI_SEPARATOR)) {\n const v = part.trim();\n if (v.length > 0) seen.add(v);\n }\n return [...seen];\n}\n\n/** True when `id` names this topic — the cheap half of answer validation. */\nexport function promptTopicOf(id: string): string {\n const i = id.indexOf(':');\n return i === -1 ? id : id.slice(0, i);\n}\n","/**\n * The per-agent activity/status contract, shared by every hop between the in-box\n * ctl daemon and the hub's `/api/v1` payload.\n *\n * WHY IT LIVES IN `@agentbox/core`: `ctl` depends on `relay`, never the reverse,\n * and `core` is the zero-internal-dep leaf both can reach. `ctl` owns the\n * `BoxStatus` envelope (it is the producer); the per-agent *entry* has to be\n * readable by the relay's queue gate and by the hub without either importing the\n * box daemon.\n *\n * WHY A KEYED MAP AND NOT NAMED FIELDS: `BoxStatus` used to carry a required\n * `claude` plus optional `codex`/`opencode`, and every consumer re-spelled those\n * three names. A fourth agent could not report activity at all — not \"was not\n * wired up\", but had nowhere to put the value. Keyed by {@link AgentId}, a new\n * agent reports activity the moment it has a registry row.\n *\n * BACK-COMPAT IS READ-TIME, exactly as {@link normalizeLastAgent} does it for\n * persisted agent names, and for the same reason: the producer is BAKED INTO THE\n * BOX IMAGE. A box created from an older snapshot keeps posting the old shape\n * for as long as it lives, and no host-side release can change that. So the old\n * shape is normalized on the way in ({@link normalizeAgentStatus}) rather than\n * migrated, and the current producer keeps WRITING the legacy blocks too, since\n * the skew runs both ways (a laptop CLI can be newer than a control box's hub).\n *\n * THE SCHEMA VERSION DOES NOT MOVE. `BoxStatus.schema` is `1`, and both\n * `isValidBoxStatus` (relay) and `readBoxStatus` (host) reject anything else\n * outright — a bump would silently blank every field on every existing host\n * rather than degrade. `agents` is therefore an ADDITIVE field, the same\n * discipline `probed`, `expose` and `sessionTitle` already follow on this type.\n */\n\nimport type { AgentId } from './agent-kind.js';\n\n/**\n * Coarse activity state of an in-box agent session. `unknown` is the initial\n * value, before any hook/plugin/scraper has reported (or for a box whose image\n * predates the reporting).\n *\n * `end-plan` and `question` are the fine-grained, payload-bearing states: the\n * agent is awaiting human approval of a plan, or showing an interactive\n * question. `compacting` means the conversation is being summarized; `error`\n * that a turn ended in an unrecoverable failure.\n */\nexport type AgentActivityState =\n | 'working'\n | 'idle'\n | 'waiting'\n | 'end-plan'\n | 'question'\n | 'compacting'\n | 'error'\n | 'unknown';\n\nexport const AGENT_ACTIVITY_STATES: readonly AgentActivityState[] = [\n 'working',\n 'idle',\n 'waiting',\n 'end-plan',\n 'question',\n 'compacting',\n 'error',\n 'unknown',\n];\n\nexport function isAgentActivityState(v: unknown): v is AgentActivityState {\n return typeof v === 'string' && (AGENT_ACTIVITY_STATES as readonly string[]).includes(v);\n}\n\n/** Body captured from a plan-approval hook payload. */\nexport interface AgentPlanPayload {\n /** Markdown plan body. */\n plan: string;\n /** ISO-8601 timestamp the hook fired. */\n capturedAt: string;\n}\n\n/** Body captured from an interactive-question hook payload. */\nexport interface AgentQuestionPayload {\n /** Each entry is one question the agent is asking; usually length 1. */\n questions: Array<{\n question: string;\n header?: string;\n multiSelect?: boolean;\n options: Array<{ label: string; description?: string }>;\n }>;\n capturedAt: string;\n}\n\n/**\n * One agent's status inside a box.\n *\n * Uniform across agents on purpose. `plan`/`question` are not Claude-specific —\n * only Claude *produces* them today, because only its hooks carry the payload —\n * so an agent that grows the same hooks needs no new field and no new reader.\n */\nexport interface AgentStatusEntry {\n state: AgentActivityState;\n /** ISO-8601 time the last state report arrived, or null if none yet. */\n updatedAt: string | null;\n /** Whether the agent's tmux session was present at snapshot time. */\n sessionRunning: boolean;\n /** Sanitized in-box tmux pane title the agent's TUI set. Additive. */\n sessionTitle?: string;\n /** Populated while `state === 'end-plan'`; cleared by the matching post-hook. */\n plan?: AgentPlanPayload;\n /** Populated while `state === 'question'`; cleared by the matching post-hook. */\n question?: AgentQuestionPayload;\n}\n\n/** Every reporting agent in one box, keyed by {@link AgentId}. */\nexport type AgentStatusMap = Record<AgentId, AgentStatusEntry>;\n\n/**\n * The legacy per-agent field names on `BoxStatus`, in the order a reader should\n * prefer them. Frozen: this is the set of names old producers actually wrote, so\n * it never grows — a fourth agent lives only in `agents`.\n */\nexport const LEGACY_AGENT_STATUS_KEYS: readonly AgentId[] = ['claude', 'codex', 'opencode'];\n\n/**\n * Narrow one agent's body from an untrusted payload, or null if it isn't one.\n *\n * Deliberately lenient about everything except `state`: an entry whose `state`\n * is unrecognizable is not an entry, but a missing `updatedAt` or a garbage\n * `sessionTitle` is dropped field-by-field rather than failing the whole box.\n * A newer producer's extra fields are ignored, never rejected.\n */\nexport function parseAgentStatusEntry(raw: unknown): AgentStatusEntry | null {\n if (raw === null || typeof raw !== 'object') return null;\n const o = raw as Record<string, unknown>;\n if (!isAgentActivityState(o.state)) return null;\n const entry: AgentStatusEntry = {\n state: o.state,\n updatedAt: typeof o.updatedAt === 'string' ? o.updatedAt : null,\n sessionRunning: o.sessionRunning === true,\n };\n if (typeof o.sessionTitle === 'string' && o.sessionTitle.length > 0) {\n entry.sessionTitle = o.sessionTitle;\n }\n const plan = o.plan as Record<string, unknown> | undefined;\n if (plan && typeof plan === 'object' && typeof plan.plan === 'string') {\n entry.plan = {\n plan: plan.plan,\n capturedAt: typeof plan.capturedAt === 'string' ? plan.capturedAt : '',\n };\n }\n const question = o.question as Record<string, unknown> | undefined;\n if (question && typeof question === 'object' && Array.isArray(question.questions)) {\n entry.question = {\n questions: question.questions as AgentQuestionPayload['questions'],\n capturedAt: typeof question.capturedAt === 'string' ? question.capturedAt : '',\n };\n }\n return entry;\n}\n\n/**\n * Read the agent status map out of a box-status payload of ANY vintage.\n *\n * Accepts both shapes and always answers the map:\n * - a current producer's `agents: { … }`, and\n * - an older producer's `claude` / `codex` / `opencode` blocks.\n *\n * `agents` WINS where both are present, because the current producer writes the\n * legacy blocks as a derived mirror — so on a mixed payload the map is the\n * source and the mirror is the copy. Unknown agent ids inside `agents` are kept:\n * a newer box may report an agent this host has never heard of, and dropping it\n * would make `list` claim the box is idle.\n *\n * Never throws — a malformed payload yields `{}`, never a crash in `list`.\n */\nexport function normalizeAgentStatus(raw: unknown): AgentStatusMap {\n if (raw === null || typeof raw !== 'object') return {};\n const o = raw as Record<string, unknown>;\n const out: AgentStatusMap = {};\n\n // Legacy blocks first, so `agents` overwrites them on a dual-shape payload.\n for (const key of LEGACY_AGENT_STATUS_KEYS) {\n const entry = parseAgentStatusEntry(o[key]);\n if (entry) out[key] = entry;\n }\n\n const agents = o.agents;\n if (agents !== null && typeof agents === 'object') {\n for (const [id, body] of Object.entries(agents as Record<string, unknown>)) {\n if (id.length === 0) continue;\n const entry = parseAgentStatusEntry(body);\n if (entry) out[id] = entry;\n }\n }\n return out;\n}\n\n/**\n * The legacy mirror a current producer writes beside `agents`, so a host or hub\n * older than this build keeps reading activity. DERIVED, never hand-maintained —\n * a test asserts it moves with the map.\n *\n * Only the frozen legacy names are mirrored: an old reader has no field for a\n * fourth agent, and inventing one would not help it.\n */\nexport function legacyAgentStatusFields(map: AgentStatusMap): Record<string, AgentStatusEntry> {\n const out: Record<string, AgentStatusEntry> = {};\n for (const key of LEGACY_AGENT_STATUS_KEYS) {\n const entry = map[key];\n if (entry) out[key] = entry;\n }\n return out;\n}\n\n/**\n * The agent a box should be judged by when a caller wants exactly one: whichever\n * reports a quota-consuming state, else the most recently updated.\n *\n * Shared so the queue's working-gate, `list`'s AGENT column and the dashboard\n * cannot disagree about which agent a box \"is\" — they each used to re-implement\n * this over the same three hardcoded names.\n */\nexport function pickPrimaryAgent(\n map: AgentStatusMap,\n): { agent: AgentId; entry: AgentStatusEntry } | null {\n const entries = Object.entries(map).map(([agent, entry]) => ({ agent, entry }));\n if (entries.length === 0) return null;\n const busy = entries.find((e) => e.entry.state === 'working' || e.entry.state === 'compacting');\n if (busy) return busy;\n entries.sort((a, b) => parseTime(b.entry.updatedAt) - parseTime(a.entry.updatedAt));\n return entries[0] ?? null;\n}\n\nfunction parseTime(iso: string | null): number {\n if (!iso) return 0;\n const t = Date.parse(iso);\n return Number.isNaN(t) ? 0 : t;\n}\n","/**\n * The one agent-id type, and the adapter reconciling the two spellings of the\n * Claude agent across the codebase:\n * - `'claude'` — canonical INTERNAL name (sync layer, docker volumes,\n * `BoxRecord.lastAgent`, the CLI `claude` subcommand).\n * - `'claude-code'` — the FROZEN wire/registry name (persisted queue jobs, the\n * `AgentLauncher` registry).\n *\n * Everything downstream of a boundary uses `AgentId`; `toQueueKind` /\n * `toSyncKind` translate only at the boundary. We NEVER rewrite persisted\n * wire/record values — back-compat is read-time normalization\n * (`normalizeLastAgent`), so existing box records and in-flight queue jobs keep\n * working untouched.\n *\n * WHY THIS LIVES IN `@agentbox/core`: it is the only package with no internal\n * dependencies, so it is the one place `sandbox-*`, `relay`, `ctl`, the hub and\n * the CLI can all reach. The agent REGISTRY (`AGENT_SYNC_SPECS`) deliberately\n * stays in `@agentbox/sandbox-core` — it carries host paths and install recipes\n * that have no business in a type contract, and `ctl` (baked into the box image)\n * must never import it.\n *\n * WHY `AgentId` IS `string` AND NOT A UNION: an agent is data — a registry row —\n * so the set of valid ids is a runtime fact, not a compile-time one. The cost is\n * that the compiler no longer enumerates the sites a newly-added agent misses,\n * which is why that job is done by tests instead: `no-inline-agent-union.test.ts`\n * fails if a hardcoded union of the shipped agent names reappears anywhere in\n * src, and the per-surface tables assert their keys against `agentIds()`.\n * Removing either guard silently re-closes the type.\n */\n\n/**\n * Canonical internal agent id. Open by design (see the file doc); validate with\n * {@link isAgentKind} for the built-ins or `isRuntimeAgent` from\n * `@agentbox/sandbox-core` for anything the registry knows about.\n */\nexport type AgentId = string;\n\n/** The frozen wire/queue spelling (persisted jobs, `AgentLauncher.kind`). */\nexport type QueueAgentKind = string;\n\n/**\n * An agent id, or the plain shell — what a box's terminal is currently showing.\n * Distinct from {@link AgentId} because `'shell'` is a UI mode, not an agent: it\n * has no registry row, no credentials and no install recipe.\n */\nexport type AgentMode = AgentId | 'shell';\n\n/**\n * The agents compiled into this build. NOT the authority on what exists — the\n * registry is (`agentIds()` / `isRuntimeAgent` in `@agentbox/sandbox-core`).\n * This list exists only for the two things a dependency-free leaf can still do\n * honestly: normalize a persisted record and translate a wire spelling.\n */\nexport const BUILTIN_AGENT_KINDS: readonly AgentId[] = ['claude', 'codex', 'opencode', 'pi'];\n\n/** Wire spellings that map onto a different canonical id. */\nconst WIRE_ALIASES: Readonly<Record<string, AgentId>> = { 'claude-code': 'claude' };\n\n/** Canonical ids whose wire spelling differs, keyed the other way. */\nconst WIRE_SPELLINGS: Readonly<Record<AgentId, QueueAgentKind>> = { claude: 'claude-code' };\n\n/** True for an agent built into this release. */\nexport function isAgentKind(v: unknown): v is AgentId {\n return typeof v === 'string' && BUILTIN_AGENT_KINDS.includes(v);\n}\n\n/**\n * Boundary → internal. Maps the wire spelling `'claude-code'` to `'claude'`;\n * every other known id passes through. Throws on anything else so a typo can't\n * silently seed the wrong agent — with `AgentId` open this is the only\n * validation left at this boundary, so it stays fail-closed.\n */\nexport function toSyncKind(k: string): AgentId {\n const canonical = WIRE_ALIASES[k] ?? k;\n if (!isAgentKind(canonical)) throw new Error(`unknown agent kind: ${k}`);\n return canonical;\n}\n\n/** Internal → boundary. Maps `'claude'` to the wire spelling `'claude-code'`. */\nexport function toQueueKind(k: AgentId): QueueAgentKind {\n return WIRE_SPELLINGS[k] ?? k;\n}\n\n/**\n * Read-time back-compat for persisted `BoxRecord.lastAgent`. A record written by\n * any past/forked build that stored `'claude-code'` still resolves to\n * `'claude'`; unknown/absent values return undefined rather than throwing (a\n * stale record must never crash `list`/`recover`).\n */\nexport function normalizeLastAgent(raw: string | undefined | null): AgentId | undefined {\n if (!raw) return undefined;\n const canonical = WIRE_ALIASES[raw] ?? raw;\n return isAgentKind(canonical) ? canonical : undefined;\n}\n","/**\n * `ProviderSync` — the co-located, auditable surface of every shared sync\n * activity a provider performs. One implementation per provider\n * (`makeDockerSync` / `makeCloudSync`), each method a thin delegation to the\n * provider-neutral concern in `@agentbox/sandbox-core`. The two goals this\n * serves — see `docs/sync-architecture.md` §\"Co-location: the ProviderSync\n * facade\":\n *\n * - **Per-provider audit** — one file (`docker-sync.ts` / `cloud-sync.ts`) is\n * the complete list of a provider's sync ops.\n * - **Per-concern cross-provider audit** — `dockerSync.resyncWorkspace` vs\n * `cloudSync.resyncWorkspace` are peer methods under one interface.\n *\n * The handle (docker container / cloud backend+handle) is closed at construction\n * time; every method takes the `SyncContext` plus its own operation args.\n *\n * Granularity is GROUPED: per-tool agent config (static config, skills, dynamic,\n * box-facts) bundles into `seedAgentConfig`; resync / credentials / extract /\n * git-identity / env / carry stay separate peer methods. Workspace *seed* (git\n * worktree create + docker `mount --bind`) is deliberately NOT here — it has no\n * cloud analog (cloud clones), so it stays a provider-specific step called\n * directly by each `create()`. Each facade file's header names that carve-out so\n * the file remains the full picture.\n */\n\nimport type { GitWorktreeRecord } from '../box-record.js';\nimport type { ResolvedCarryEntry, ResyncResult } from '../provider.js';\nimport type { SyncContext } from './context.js';\n\n/** Env var that flips every `ProviderSync` op into a print-only no-op. */\nexport const SYNC_DRYRUN_ENV = 'AGENTBOX_SYNC_DRYRUN';\n\n/**\n * Outcome of applying the approved `carry:` entries into a box. Mirrors the\n * docker `CopyCarryResult` shape (kept identical so `applyCarry` returns it\n * verbatim): the count copied, per-entry errors, and an audit summary for\n * `BoxRecord.carry` (`hash` is the host source content hash at copy time).\n */\nexport interface CarryApplyResult {\n copied: number;\n errors: string[];\n applied: Array<{ src: string; dest: string; bytes: number; hash?: string }>;\n}\n\nexport interface ProviderSync {\n /**\n * Merge the host's checked-out branch into each box worktree's per-box branch\n * and overlay the host's uncommitted/untracked changes, box-wins on conflict.\n * `worktrees` are the box's recorded worktrees (root + nested).\n */\n resyncWorkspace(ctx: SyncContext, worktrees: GitWorktreeRecord[]): Promise<ResyncResult>;\n /**\n * Seed the per-tool agent config (claude/codex/opencode): static config +\n * skills + dynamic (workflows/memory) + box-facts. The method body lists the\n * sub-steps in order so the facade file stays the auditable full picture.\n */\n seedAgentConfig(ctx: SyncContext): Promise<void>;\n /** Seed the host's agent logins (claude/codex/opencode) into the box. */\n seedCredentials(ctx: SyncContext): Promise<void>;\n /** Capture the box's agent logins back to the host backups. Returns updated agents. */\n extractCredentials(ctx: SyncContext): Promise<string[]>;\n /** Seed the host git identity (`~/.gitconfig`) into the box. Docker no-op (bind-mounted). */\n seedGitIdentity(ctx: SyncContext): Promise<void>;\n /** Copy gitignore-bypassing host env files matching `patterns` into /workspace. */\n seedEnvFiles(ctx: SyncContext, patterns: string[]): Promise<{ copied: number }>;\n /** Apply the approved `carry:` entries (host→box file copies) into the box. */\n applyCarry(ctx: SyncContext, entries: ResolvedCarryEntry[]): Promise<CarryApplyResult>;\n}\n\n/**\n * Wrap a `ProviderSync` so each op prints `[sync dry-run] <label>.<op>(…)` via\n * `ctx.onLog` and returns a benign default WITHOUT executing — the readable\n * audit of \"what the facade would do.\" `makeDockerSync`/`makeCloudSync` apply\n * this when {@link SYNC_DRYRUN_ENV} is set. The inner facade is never invoked, so\n * a dry run makes no host/box changes.\n */\nexport function dryRunProviderSync(label: string): ProviderSync {\n const note = (ctx: SyncContext, op: string, detail = ''): void =>\n ctx.onLog(`[sync dry-run] ${label}.${op}(${detail})`);\n return {\n resyncWorkspace(ctx, worktrees) {\n note(ctx, 'resyncWorkspace', `${String(worktrees.length)} worktree(s)`);\n return Promise.resolve({ repos: [], hadConflicts: false });\n },\n seedAgentConfig(ctx) {\n note(ctx, 'seedAgentConfig');\n return Promise.resolve();\n },\n seedCredentials(ctx) {\n note(ctx, 'seedCredentials');\n return Promise.resolve();\n },\n extractCredentials(ctx) {\n note(ctx, 'extractCredentials');\n return Promise.resolve([]);\n },\n seedGitIdentity(ctx) {\n note(ctx, 'seedGitIdentity');\n return Promise.resolve();\n },\n seedEnvFiles(ctx, patterns) {\n note(ctx, 'seedEnvFiles', `${String(patterns.length)} pattern(s)`);\n return Promise.resolve({ copied: 0 });\n },\n applyCarry(ctx, entries) {\n note(ctx, 'applyCarry', `${String(entries.length)} entry/entries`);\n return Promise.resolve({ copied: 0, errors: [], applied: [] });\n },\n };\n}\n","/**\n * Pure resolver for a box's {@link SyncTopology} — the \"resolved ONCE per box\n * (from the provider name + whether a control-plane URL is configured)\" step the\n * `SyncTopology` doc describes. No fs/exec — string logic only — so it's shared\n * by the provider (persists it on the record) and any host/box consumer.\n */\nimport type { SyncTopology } from './types.js';\n\n/**\n * Resolve a box's federation topology from its provider name and whether a\n * hosted control-plane URL is configured for it.\n *\n * - docker → always `'docker'` (bind-mounted `.git`, host relay loopback; never\n * a control-plane target).\n * - any cloud provider + a non-empty control-plane URL → `'control-plane'`\n * (the box's live relay is the plane; git push-back leases a token directly).\n * - any cloud provider without one → `'cloud'` (host-side sync via the backend).\n */\nexport function resolveSyncTopology(providerName: string, controlPlaneUrl?: string): SyncTopology {\n if (providerName === 'docker') return 'docker';\n return controlPlaneUrl && controlPlaneUrl.length > 0 ? 'control-plane' : 'cloud';\n}\n","/**\n * Pure download / file-transfer decisions, co-located here so *all* sync\n * decision logic is discoverable under `core/src/sync/` — even though the two\n * download handlers keep genuinely divergent transports (docker re-shells the\n * host CLI; cloud calls `pullCloudDirContents`, workspace-only). We do NOT\n * force-unify the transport; only these shared, pure decisions live here.\n *\n * No fs/exec beyond `node:path`/`node:os` string helpers.\n */\n\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, resolve } from 'node:path';\n\n/** The `download.<kind>` variants an in-box agent can request. */\nexport type DownloadKind = 'workspace' | 'env' | 'config' | 'claude';\n\n/**\n * Parse the `download.<kind>` RPC method into its kind, defaulting a missing\n * suffix to 'workspace'. Duplicated inline at the docker (`server.ts`) and\n * cloud (`host-actions.ts`) download entry points.\n */\nexport function parseDownloadKind(method: string): DownloadKind {\n return (method.split('.')[1] ?? 'workspace') as DownloadKind;\n}\n\n/**\n * Resolve a host path supplied by an in-box agent to an absolute host path.\n * Absolute paths pass through; a leading `~`/`~/` expands against the host\n * home; anything else is relative to the box's host `workspacePath` (NOT the\n * relay daemon's CWD). When `workspacePath` is unknown, relative paths fall\n * back to `path.resolve` (process CWD) — same as the old behaviour.\n */\nexport function resolveHostPath(workspacePath: string | undefined, hostPath: string): string {\n if (isAbsolute(hostPath)) return hostPath;\n if (hostPath === '~') return homedir();\n if (hostPath.startsWith('~/')) return join(homedir(), hostPath.slice(2));\n return workspacePath ? resolve(workspacePath, hostPath) : resolve(hostPath);\n}\n","/**\n * Host-side path-containment + secret-file guards for the relay's auto-approve\n * decisions. Unlike its pure sibling `files.ts`, this module DOES touch the\n * filesystem (`realpath`) — that's the whole point: following symlinks is what\n * catches an in-project symlink that actually points outside the box's project\n * folder. Lives in `@agentbox/core` so the relay (`@agentbox/relay`) and the\n * host CLI's carry resolver (`apps/cli`) share one containment definition.\n *\n * These are advisory *safety* checks for relaxing approval prompts, never the\n * only boundary: a not-contained / secret path just falls back to prompting.\n */\n\nimport { realpath } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, normalize, resolve, sep } from 'node:path';\n\n/** realpath `p`, falling back to a lexical resolve when it can't be canonicalized. */\nexport async function realpathSafe(p: string): Promise<string> {\n try {\n return await realpath(p);\n } catch {\n return resolve(p);\n }\n}\n\n/**\n * True when canonicalized `child` is `parent` or lives under it. Both are\n * resolved so the comparison happens in the same (already realpath'd) space —\n * callers pass values that have been through `realpathSafe`.\n */\nexport function isInside(child: string, parent: string): boolean {\n const c = resolve(child);\n const p = resolve(parent);\n if (c === p) return true;\n return c.startsWith(p + sep);\n}\n\n/**\n * realpath the deepest *existing* prefix of `p`, then re-append the\n * not-yet-existing tail. Lets a download/cp destination that doesn't exist yet\n * still be containment-checked (its existing parent is canonicalized, so a\n * symlinked parent pointing outside is caught), while a fully-existing source\n * is realpath'd end-to-end.\n */\nasync function realpathDeepestExisting(p: string): Promise<string> {\n let cur = resolve(p);\n const tail: string[] = [];\n // Bounded by the path depth; dirname() reaches the root fixpoint.\n for (;;) {\n try {\n const real = await realpath(cur);\n return tail.length > 0 ? resolve(real, ...tail.reverse()) : real;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return resolve(p);\n const parent = dirname(cur);\n if (parent === cur) return resolve(p); // nothing along the path exists\n tail.push(basename(cur));\n cur = parent;\n }\n }\n}\n\n/**\n * True when `hostPath` (an absolute host path) resolves to a location inside\n * the box's `workspacePath` (the host dir mirroring `/workspace`). Symlinks are\n * followed via realpath so an in-project link escaping the folder fails the\n * check. A literal `..` that survives normalization is rejected outright.\n * Returns `false` (→ caller prompts) when the workspace is unknown.\n */\nexport async function isContainedInWorkspace(\n hostPath: string,\n workspacePath: string | undefined,\n): Promise<boolean> {\n if (!workspacePath) return false;\n if (!isAbsolute(hostPath)) return false;\n // A surviving `..` segment means the literal path escapes upward.\n if (normalize(hostPath).split(sep).includes('..')) return false;\n const wsReal = await realpathSafe(workspacePath);\n const real = await realpathDeepestExisting(hostPath);\n return isInside(real, wsReal);\n}\n\n/** Sensitive directory names: any path segment equal to one of these is secret. */\nconst SECRET_DIR_SEGMENTS = new Set(['.ssh', '.aws', '.gnupg']);\n\n/** Exact basenames that are always secrets. */\nconst SECRET_BASENAMES = new Set(['credentials', '.npmrc', '.netrc', '.pgpass', '.htpasswd']);\n\n/** Basename patterns that mark a likely secret / private key. */\nconst SECRET_BASENAME_PATTERNS: readonly RegExp[] = [\n /^\\.env(\\..+)?$/, // .env, .env.local, .env.production\n /\\.(pem|key|pfx|p12|keystore|jks)$/i,\n /^id_(rsa|dsa|ecdsa|ed25519)$/, // private SSH keys (not the .pub)\n];\n\n/**\n * True when `hostPath` looks like a secret/credential file — used to keep a\n * host->box copy of such a file behind the approval prompt even when the path\n * is contained. Deliberately conservative (a false positive just re-adds a\n * prompt the user can approve): matches secret dirs, `.config/gh`, exact\n * credential basenames, and private-key patterns.\n */\nexport function looksLikeSecret(hostPath: string): boolean {\n const segs = normalize(hostPath).split(sep).filter(Boolean);\n for (const seg of segs) {\n if (SECRET_DIR_SEGMENTS.has(seg)) return true;\n }\n // `.config/gh` (gh CLI auth) — two adjacent segments.\n for (let i = 0; i + 1 < segs.length; i++) {\n if (segs[i] === '.config' && segs[i + 1] === 'gh') return true;\n }\n const base = basename(hostPath);\n if (SECRET_BASENAMES.has(base)) return true;\n return SECRET_BASENAME_PATTERNS.some((re) => re.test(base));\n}\n","/**\n * Pure git ref/branch decisions, shared by the relay host paths and the in-box\n * ctl. Lives in `@agentbox/core` (not `sandbox-core`) because `@agentbox/ctl`\n * depends only on core — same pattern as the pure engine in `../replace.ts`.\n *\n * No fs/exec: only string logic. The three git push-back paths (docker relay,\n * cloud relay, in-box lease push) keep their divergent *mechanisms* but read\n * these *decisions* from here so the branch/refspec/remote/upstream spellings\n * can't drift apart.\n */\n\n/** Prefix of the per-box scratch branch (`agentbox/<name>`). */\nexport const SCRATCH_BRANCH_PREFIX = 'agentbox/';\n\n/**\n * True for a per-box `agentbox/<name>` scratch branch. Undefined-safe so it\n * reproduces the existing `worktree?.branch.startsWith(...) ?? false` sites\n * exactly (`isScratchBranch(undefined) === false`).\n */\nexport function isScratchBranch(branch: string | undefined): boolean {\n return !!branch && branch.startsWith(SCRATCH_BRANCH_PREFIX);\n}\n\n/**\n * True when a push to `branch` is a *sanctioned* push that may bypass the\n * relay's confirm prompt: it's the box's own `agentbox/<name>` scratch branch\n * (always its job), or it exactly matches the branch the host last put the box\n * on (`sanctionedBranch`). An in-box agent that self-switches HEAD to some\n * other branch (e.g. `main`) fails both arms, so its push still prompts.\n * Undefined-safe; empty/`HEAD` never matches the sanctioned arm.\n */\nexport function isSanctionedPushBranch(\n branch: string | undefined,\n sanctionedBranch: string | undefined,\n): boolean {\n if (isScratchBranch(branch)) return true;\n return isResolvedBranch(branch ?? '') && !!sanctionedBranch && branch === sanctionedBranch;\n}\n\n/**\n * Resolve the push remote, defaulting to 'origin'.\n *\n * MUST be `??`, not `||`: only an *undefined* remote falls back to 'origin'.\n * A legitimately-empty wire remote must stay '' — `||` would coerce it and\n * silently change the push target.\n */\nexport function resolveRemote(remote?: string): string {\n return remote ?? 'origin';\n}\n\n/**\n * Host-only land destination branch: the requested `as` when non-empty, else\n * the source branch (server.ts `handleGitSaveToHost` ≡ host-actions.ts\n * `runGitRpc` host-only path).\n */\nexport function resolveLandDest(src: string, as?: string): string {\n return as && as.length > 0 ? as : src;\n}\n\n/**\n * Host-only land refspec for `git fetch . <refspec>` (docker) / `git fetch\n * <bundle> <refspec>` (cloud). Force prepends `+` for a non-fast-forward\n * overwrite of the destination branch.\n */\nexport function landRefspec(src: string, dest: string, force?: boolean): string {\n return `${force ? '+' : ''}${src}:refs/heads/${dest}`;\n}\n\n/** Upstream ref for `git branch --set-upstream-to=<remote>/<branch>`. */\nexport function upstreamRef(remote: string, branch: string): string {\n return `${remote}/${branch}`;\n}\n\n/**\n * Remote-tracking ref for the cloud in-box `git update-ref\n * refs/remotes/<remote>/<branch>` (docker shares .git/, so the ref updates\n * during the push and only the upstream config is missing). Kept beside\n * `upstreamRef` to document the two distinct ref shapes side-by-side.\n */\nexport function remoteTrackingRef(remote: string, branch: string): string {\n return `refs/remotes/${remote}/${branch}`;\n}\n\n/**\n * Detached-HEAD guard for a probed branch name (cloud `runGitRpc` resolves the\n * branch via `rev-parse --abbrev-ref HEAD`). NOTE: intentionally NOT used by\n * ctl's weaker `!branch` check — adopting it there would add a `=== 'HEAD'`\n * rejection on the control-plane lease push path (a behavior change).\n */\nexport function isResolvedBranch(s: string): boolean {\n return s.length > 0 && s !== 'HEAD';\n}\n\n/**\n * Filter a user-supplied extra-argv tail down to strings. The argv *prefixes*\n * differ per site (`git -C repo push …` vs `-C repo push …` vs `push …`) and\n * stay site-local; only this trailing arg-filter is shared.\n */\nexport function sanitizeGitArgs(args: unknown): string[] {\n return Array.isArray(args) ? args.filter((a): a is string => typeof a === 'string') : [];\n}\n\n/**\n * Wire params for the `git.push` / `git.fetch` RPCs. Canonical home for the\n * shape that the relay receives and the in-box ctl builds (previously declared\n * independently in `relay/src/types.ts` and `ctl/src/commands/git.ts`).\n */\nexport interface GitRpcParams {\n /** Container path identifying which worktree to run against. Defaults to /workspace. */\n path?: string;\n /** Remote name; defaults to 'origin'. */\n remote?: string;\n /** Extra argv tail appended after the standard args (e.g. ['--set-upstream', 'origin', 'branch']). */\n args?: string[];\n /**\n * git.push only: land the box's branch in the host's *local* repo instead of\n * pushing to the remote. Nothing is published online; the relay skips the\n * host-initiated-token / confirm-prompt gate (that gate guards remote pushes).\n */\n hostOnly?: boolean;\n /**\n * git.push --host-only only: destination branch name in the host repo.\n * Defaults to the box's current branch name when omitted.\n */\n as?: string;\n /** git.push --host-only only: allow a non-fast-forward overwrite of the destination branch. */\n force?: boolean;\n /**\n * One-time token minted by the host CLI via `/admin/host-initiated/mint`\n * before invoking this RPC through `agentbox-ctl`. The relay validates the\n * token against its in-memory store, scoped to `(boxId, method)`; on\n * match, the token is consumed and the confirm prompt is skipped. Boxes\n * cannot mint these (the admin endpoint is loopback-only), so a malicious\n * agent cannot forge \"host-initiated\" calls. Invalid/expired tokens fall\n * through to the normal prompt path.\n */\n hostInitiated?: string;\n}\n"],"mappings":";;;;;;;AAUA,SAAS,QAAAA,aAAY;;;AiBVrB,SAAS,mBAAmB;ACiB5B,SAAS,kBAAkB;AKP3B,SAAS,eAAe;AACxB,SAAS,YAAY,MAAM,eAAe;ACC1C,SAAS,gBAAgB;AACzB,SAAS,UAAU,SAAS,cAAAC,aAAY,WAAW,WAAAC,UAAS,WAAW;AfIvE,IAAM,0BAA0B;AAGzB,SAAS,gBAAgB,MAAsB;AACpD,SAAO,GAAG,uBAAuB,GAAG,IAAI;AAC1C;AAQA,IAAM,oBAAoB;AAQnB,SAAS,qBAAqB,MAA6B;AAChE,QAAM,OAAO,KAAK,QAAQ,mBAAmB,EAAE;AAC/C,SAAO,KAAK,WAAW,uBAAuB,IAC1C,KAAK,MAAM,wBAAwB,MAAM,IACzC;AACN;AC3BA,SAAS,uBAAuB,MAAqC;AACnE,SAAO;IACL;IACA,UAAU,gBAAgB,UAAU;AAClC,UAAI,CAAC,eAAgB,QAAO,CAAC,GAAG,QAAQ;AACxC,aAAO,CAAC,gBAAgB,GAAG,QAAQ;IACrC;EACF;AACF;AAEO,SAAS,qBAAqB,MAAqC;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isAbsolute","resolve","resolve","isAbsolute","join","join","join","join","dirname","join","BOX_HOME","agentDirPrelude","BOX_CREDS_DIR","BOX_USER","STATE_DIR","sq","normalize","dirname"]}
|