@madarco/agentbox 0.29.0 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/{_cloud-attach-HKRHYCY7.js → _cloud-attach-EUO2OL7W.js} +11 -11
  3. package/dist/{chunk-GWKGSXDC.js → chunk-2JHPGPLE.js} +2 -2
  4. package/dist/{chunk-THUST2QK.js → chunk-4KYP775X.js} +3 -3
  5. package/dist/{chunk-HP4L45LW.js → chunk-4NUETVTR.js} +8 -8
  6. package/dist/{chunk-UPVP6YGJ.js → chunk-53OTEDBS.js} +3 -3
  7. package/dist/{chunk-VY54AX4T.js → chunk-6YSYQZRH.js} +3 -3
  8. package/dist/{chunk-NGERWFSA.js → chunk-73D2HKA3.js} +14 -11
  9. package/dist/chunk-73D2HKA3.js.map +1 -0
  10. package/dist/{chunk-EFVTQ7YB.js → chunk-7LC5IG5K.js} +4 -4
  11. package/dist/{chunk-DYETLPUT.js → chunk-A2TATHHJ.js} +2 -2
  12. package/dist/{chunk-QU5BI2HC.js → chunk-AC3HU25W.js} +4 -4
  13. package/dist/{chunk-CO2I3CQI.js → chunk-AUHYXXCA.js} +4 -4
  14. package/dist/{chunk-RZCLRWNY.js → chunk-B4YFG5TB.js} +6 -6
  15. package/dist/{chunk-DBXCFLAR.js → chunk-BIKWXLX7.js} +5 -5
  16. package/dist/{chunk-GWYD7YBK.js → chunk-CZPVVFCF.js} +5 -5
  17. package/dist/{chunk-BWE2I5QG.js → chunk-F4PPZ4SI.js} +2 -2
  18. package/dist/{chunk-RQURMAPA.js → chunk-FEFLAITR.js} +5 -5
  19. package/dist/{chunk-HO2ACZES.js → chunk-FELVUIIM.js} +2 -2
  20. package/dist/{chunk-EPFXLXCW.js → chunk-I2DEYQLZ.js} +4 -4
  21. package/dist/{chunk-WGNI24H2.js → chunk-I7BSBUPC.js} +9 -9
  22. package/dist/{chunk-7QU6XENE.js → chunk-PAWAGULH.js} +2 -2
  23. package/dist/{chunk-6PIGTR4D.js → chunk-PFEBKXFD.js} +14 -14
  24. package/dist/{chunk-NAT2H7J4.js → chunk-QDU7YDME.js} +46 -26
  25. package/dist/chunk-QDU7YDME.js.map +1 -0
  26. package/dist/{chunk-3INUZQTR.js → chunk-S32GHLVU.js} +3 -3
  27. package/dist/{chunk-7Q6BG5AN.js → chunk-THKVKVRF.js} +3 -3
  28. package/dist/{chunk-VVNXQ4XS.js → chunk-UEEW5TW7.js} +8 -8
  29. package/dist/{chunk-LHOKRCNF.js → chunk-UTOC2NHC.js} +3 -3
  30. package/dist/{chunk-HNWZO2XU.js → chunk-WDBDFLH3.js} +4 -4
  31. package/dist/{chunk-WHJYOO5H.js → chunk-WJUKN4L4.js} +2 -2
  32. package/dist/{chunk-OKLEPEWZ.js → chunk-XENTK32L.js} +5 -2
  33. package/dist/chunk-XENTK32L.js.map +1 -0
  34. package/dist/cloud-backends.js +4 -4
  35. package/dist/{control-plane-UKKYXHIQ.js → control-plane-YQFX2ILX.js} +16 -16
  36. package/dist/{cp-hub-upload-BM2OLTOS.js → cp-hub-upload-RMJ3XJ65.js} +6 -6
  37. package/dist/{custody-client-NPXJ46TB.js → custody-client-L4FEFW4C.js} +3 -3
  38. package/dist/{deploy-hetzner-Y3ILCDRF.js → deploy-hetzner-EECQ4JCM.js} +8 -8
  39. package/dist/{dist-5OGQ3CJQ.js → dist-3BKIPZR3.js} +3 -3
  40. package/dist/{dist-ZNYS7CVF.js → dist-C5B6NGBO.js} +5 -5
  41. package/dist/{dist-DOEGENNW.js → dist-E5EXDZG4.js} +7 -7
  42. package/dist/{dist-EOGD7KD6.js → dist-NFF2KEMB.js} +7 -7
  43. package/dist/{dist-7B3VCLZI.js → dist-NTUHJOK3.js} +7 -7
  44. package/dist/{dist-SMDXLPZO.js → dist-PTYASENV.js} +2 -2
  45. package/dist/{dist-MUTFY7FA.js → dist-Q4UDCSZQ.js} +7 -7
  46. package/dist/{dist-VTLQKZ2E.js → dist-TXFTYNNE.js} +6 -6
  47. package/dist/{dist-A5ZEIVAW.js → dist-XUOHE22G.js} +8 -8
  48. package/dist/{dist-ZJIJHCZB.js → dist-Z2TPC3EN.js} +7 -7
  49. package/dist/{host-reach-drainer-ZJU2STQQ.js → host-reach-drainer-N4JSFUBY.js} +2 -2
  50. package/dist/hub-3HPYOV5O.js +37 -0
  51. package/dist/{hub-adopt-OA336ZXZ.js → hub-adopt-NCCCMMXL.js} +6 -6
  52. package/dist/{hub-docker-target-JKFCABK4.js → hub-docker-target-ZKAWXVPH.js} +11 -11
  53. package/dist/index.js +48 -48
  54. package/dist/prepare-KIVDQRMN.js +41 -0
  55. package/dist/prepared-custody-EFSOOAIQ.js +36 -0
  56. package/dist/{prepared-state-LNQ7DYSU-AR5RMXAO.js → prepared-state-LNQ7DYSU-2YFSDOCV.js} +3 -3
  57. package/dist/{publish-credentials-3SQXX45P.js → publish-credentials-F2A5OVCO.js} +7 -7
  58. package/dist/{registry-AFKV3EO2.js → registry-O3X2CDDU.js} +4 -4
  59. package/dist/{relay-QH6OEY2V.js → relay-3T57T4RI.js} +7 -7
  60. package/dist/{remote-docker-share-RMS6IB5X.js → remote-docker-share-QDCBM5UM.js} +8 -8
  61. package/dist/{tool-grant-push-T6DRBY3W.js → tool-grant-push-6ISDIJKH.js} +3 -3
  62. package/package.json +1 -1
  63. package/runtime/_shared/ctl.cjs +4 -1
  64. package/runtime/digitalocean/ctl.cjs +4 -1
  65. package/runtime/docker/packages/ctl/dist/bin.cjs +4 -1
  66. package/runtime/e2b/ctl.cjs +4 -1
  67. package/runtime/hetzner/ctl.cjs +4 -1
  68. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  69. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  70. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  71. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  72. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  73. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  74. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  75. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  76. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  77. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  78. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  79. package/runtime/hub/apps/hub/{chunk-UQ5XNPOF.js → chunk-2WB3A5IN.js} +3 -3
  80. package/runtime/hub/apps/hub/{chunk-3AD3MYNV.js → chunk-BI4MPGQT.js} +9 -9
  81. package/runtime/hub/apps/hub/{chunk-GBYD2ODL.js → chunk-G6FJR7TN.js} +4 -1
  82. package/runtime/hub/apps/hub/{chunk-3ZDBZYOY.js → chunk-QGAP34GN.js} +4 -4
  83. package/runtime/hub/apps/hub/{chunk-H5SUXDZA.js → chunk-QWSP6WJ2.js} +3 -3
  84. package/runtime/hub/apps/hub/{chunk-WHGY7HOC.js → chunk-RPPOFMPA.js} +2 -2
  85. package/runtime/hub/apps/hub/{dist-TH2JZYZY.js → dist-4F6XEJHK.js} +5 -5
  86. package/runtime/hub/apps/hub/{dist-XPRGHQH2.js → dist-A3JOKKYG.js} +4 -4
  87. package/runtime/hub/apps/hub/{dist-CMVSARW5.js → dist-F547YSBE.js} +5 -5
  88. package/runtime/hub/apps/hub/{dist-EOGGFZZS.js → dist-FEHV4PC7.js} +4 -4
  89. package/runtime/hub/apps/hub/{dist-Z2Y5F7AF.js → dist-P7NT6VLK.js} +4 -4
  90. package/runtime/hub/apps/hub/{dist-LJBHOO3K.js → dist-W2YXTEQN.js} +1 -1
  91. package/runtime/hub/apps/hub/{dist-37EKQ6RZ.js → dist-W5SGEJLA.js} +4 -4
  92. package/runtime/hub/apps/hub/{dist-R77W6WJ5.js → dist-YB3Y2XDK.js} +4 -4
  93. package/runtime/hub/apps/hub/{dist-EGXZRZH2.js → dist-ZTJMZLED.js} +3 -3
  94. package/runtime/hub/apps/hub/{hub-worker-DXVMUQWF.js → hub-worker-I5QBLSRU.js} +6 -6
  95. package/runtime/hub/apps/hub/{prepared-state-LNQ7DYSU-ABC2EQVI.js → prepared-state-LNQ7DYSU-4I7FNNNS.js} +2 -2
  96. package/runtime/hub/apps/hub/server.js +12 -12
  97. package/runtime/hub/apps/hub/tsconfig.tsbuildinfo +1 -1
  98. package/runtime/relay/bin.cjs +4 -1
  99. package/runtime/vercel/ctl.cjs +4 -1
  100. package/dist/chunk-NAT2H7J4.js.map +0 -1
  101. package/dist/chunk-NGERWFSA.js.map +0 -1
  102. package/dist/chunk-OKLEPEWZ.js.map +0 -1
  103. package/dist/hub-Q4VOF4WN.js +0 -37
  104. package/dist/prepare-GFWWKWGF.js +0 -41
  105. package/dist/prepared-custody-KU4PDVBT.js +0 -36
  106. /package/dist/{_cloud-attach-HKRHYCY7.js.map → _cloud-attach-EUO2OL7W.js.map} +0 -0
  107. /package/dist/{chunk-GWKGSXDC.js.map → chunk-2JHPGPLE.js.map} +0 -0
  108. /package/dist/{chunk-THUST2QK.js.map → chunk-4KYP775X.js.map} +0 -0
  109. /package/dist/{chunk-HP4L45LW.js.map → chunk-4NUETVTR.js.map} +0 -0
  110. /package/dist/{chunk-UPVP6YGJ.js.map → chunk-53OTEDBS.js.map} +0 -0
  111. /package/dist/{chunk-VY54AX4T.js.map → chunk-6YSYQZRH.js.map} +0 -0
  112. /package/dist/{chunk-EFVTQ7YB.js.map → chunk-7LC5IG5K.js.map} +0 -0
  113. /package/dist/{chunk-DYETLPUT.js.map → chunk-A2TATHHJ.js.map} +0 -0
  114. /package/dist/{chunk-QU5BI2HC.js.map → chunk-AC3HU25W.js.map} +0 -0
  115. /package/dist/{chunk-CO2I3CQI.js.map → chunk-AUHYXXCA.js.map} +0 -0
  116. /package/dist/{chunk-RZCLRWNY.js.map → chunk-B4YFG5TB.js.map} +0 -0
  117. /package/dist/{chunk-DBXCFLAR.js.map → chunk-BIKWXLX7.js.map} +0 -0
  118. /package/dist/{chunk-GWYD7YBK.js.map → chunk-CZPVVFCF.js.map} +0 -0
  119. /package/dist/{chunk-BWE2I5QG.js.map → chunk-F4PPZ4SI.js.map} +0 -0
  120. /package/dist/{chunk-RQURMAPA.js.map → chunk-FEFLAITR.js.map} +0 -0
  121. /package/dist/{chunk-HO2ACZES.js.map → chunk-FELVUIIM.js.map} +0 -0
  122. /package/dist/{chunk-EPFXLXCW.js.map → chunk-I2DEYQLZ.js.map} +0 -0
  123. /package/dist/{chunk-WGNI24H2.js.map → chunk-I7BSBUPC.js.map} +0 -0
  124. /package/dist/{chunk-7QU6XENE.js.map → chunk-PAWAGULH.js.map} +0 -0
  125. /package/dist/{chunk-6PIGTR4D.js.map → chunk-PFEBKXFD.js.map} +0 -0
  126. /package/dist/{chunk-3INUZQTR.js.map → chunk-S32GHLVU.js.map} +0 -0
  127. /package/dist/{chunk-7Q6BG5AN.js.map → chunk-THKVKVRF.js.map} +0 -0
  128. /package/dist/{chunk-VVNXQ4XS.js.map → chunk-UEEW5TW7.js.map} +0 -0
  129. /package/dist/{chunk-LHOKRCNF.js.map → chunk-UTOC2NHC.js.map} +0 -0
  130. /package/dist/{chunk-HNWZO2XU.js.map → chunk-WDBDFLH3.js.map} +0 -0
  131. /package/dist/{chunk-WHJYOO5H.js.map → chunk-WJUKN4L4.js.map} +0 -0
  132. /package/dist/{control-plane-UKKYXHIQ.js.map → control-plane-YQFX2ILX.js.map} +0 -0
  133. /package/dist/{cp-hub-upload-BM2OLTOS.js.map → cp-hub-upload-RMJ3XJ65.js.map} +0 -0
  134. /package/dist/{custody-client-NPXJ46TB.js.map → custody-client-L4FEFW4C.js.map} +0 -0
  135. /package/dist/{deploy-hetzner-Y3ILCDRF.js.map → deploy-hetzner-EECQ4JCM.js.map} +0 -0
  136. /package/dist/{dist-5OGQ3CJQ.js.map → dist-3BKIPZR3.js.map} +0 -0
  137. /package/dist/{dist-7B3VCLZI.js.map → dist-C5B6NGBO.js.map} +0 -0
  138. /package/dist/{dist-DOEGENNW.js.map → dist-E5EXDZG4.js.map} +0 -0
  139. /package/dist/{dist-EOGD7KD6.js.map → dist-NFF2KEMB.js.map} +0 -0
  140. /package/dist/{dist-A5ZEIVAW.js.map → dist-NTUHJOK3.js.map} +0 -0
  141. /package/dist/{dist-MUTFY7FA.js.map → dist-PTYASENV.js.map} +0 -0
  142. /package/dist/{dist-SMDXLPZO.js.map → dist-Q4UDCSZQ.js.map} +0 -0
  143. /package/dist/{dist-VTLQKZ2E.js.map → dist-TXFTYNNE.js.map} +0 -0
  144. /package/dist/{dist-ZJIJHCZB.js.map → dist-XUOHE22G.js.map} +0 -0
  145. /package/dist/{dist-ZNYS7CVF.js.map → dist-Z2TPC3EN.js.map} +0 -0
  146. /package/dist/{host-reach-drainer-ZJU2STQQ.js.map → host-reach-drainer-N4JSFUBY.js.map} +0 -0
  147. /package/dist/{hub-Q4VOF4WN.js.map → hub-3HPYOV5O.js.map} +0 -0
  148. /package/dist/{hub-adopt-OA336ZXZ.js.map → hub-adopt-NCCCMMXL.js.map} +0 -0
  149. /package/dist/{hub-docker-target-JKFCABK4.js.map → hub-docker-target-ZKAWXVPH.js.map} +0 -0
  150. /package/dist/{prepare-GFWWKWGF.js.map → prepare-KIVDQRMN.js.map} +0 -0
  151. /package/dist/{prepared-custody-KU4PDVBT.js.map → prepared-custody-EFSOOAIQ.js.map} +0 -0
  152. /package/dist/{prepared-state-LNQ7DYSU-AR5RMXAO.js.map → prepared-state-LNQ7DYSU-2YFSDOCV.js.map} +0 -0
  153. /package/dist/{publish-credentials-3SQXX45P.js.map → publish-credentials-F2A5OVCO.js.map} +0 -0
  154. /package/dist/{registry-AFKV3EO2.js.map → registry-O3X2CDDU.js.map} +0 -0
  155. /package/dist/{relay-QH6OEY2V.js.map → relay-3T57T4RI.js.map} +0 -0
  156. /package/dist/{remote-docker-share-RMS6IB5X.js.map → remote-docker-share-QDCBM5UM.js.map} +0 -0
  157. /package/dist/{tool-grant-push-T6DRBY3W.js.map → tool-grant-push-6ISDIJKH.js.map} +0 -0
  158. /package/runtime/hub/apps/hub/.next/static/{XIx10ozuCZRzwSsiCF_5t → nDHi_1342DzyGDC14ocQo}/_buildManifest.js +0 -0
  159. /package/runtime/hub/apps/hub/.next/static/{XIx10ozuCZRzwSsiCF_5t → nDHi_1342DzyGDC14ocQo}/_clientMiddlewareManifest.js +0 -0
  160. /package/runtime/hub/apps/hub/.next/static/{XIx10ozuCZRzwSsiCF_5t → nDHi_1342DzyGDC14ocQo}/_ssgManifest.js +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/control-plane.ts","../src/control-plane/bake-share.ts","../src/control-plane/github-app-manifest.ts","../src/control-plane/deploy-vercel.ts","../src/control-plane/github-fork.ts","../src/control-plane/ensure-repo-installed.ts","../src/control-plane/deploy-digitalocean.ts","../src/lib/update-check.ts","../src/exec-method.ts","../src/version.ts","../src/commands/install-app.ts","../src/lib/channel.ts","../src/lib/semver-lite.ts","../src/lib/update-state.ts","../src/control-plane/expose.ts","../src/control-plane/tunnel.ts","../src/lib/autostart.ts","../src/control-plane/deploy-ref.ts","../src/control-plane/host-git-token.ts","../src/lib/git-host.ts","../src/lib/log-file.ts","../src/control-plane/hub-auth-env.ts"],"sourcesContent":["import { confirm, isCancel, log, note, select, spinner } from '@clack/prompts';\nimport { Command, Option } from 'commander';\nimport { spawn } from 'node:child_process';\nimport { execa } from 'execa';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { hostname, homedir, tmpdir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport {\n findProjectRoot,\n loadEffectiveConfig,\n setConfigValue,\n unsetConfigValue,\n type HubGitAuthMode,\n} from '@agentbox/config';\nimport {\n DEFAULT_ENV_PATTERNS,\n projectSlugFromOriginUrl,\n readPreparedStateRaw,\n relayPort,\n} from '@agentbox/sandbox-core';\nimport {\n applyProjectSeed,\n deadlineFetch,\n hostReachable,\n pushPreparedToCustody,\n pushProjectSeedToCustody,\n readGitOriginUrl,\n} from '@agentbox/sandbox-cloud';\n\n/** Bound on the worker's seed download once the control box is known to be up. */\nconst SEED_FETCH_MS = 120_000;\nimport {\n drainCreateJobs,\n GitHubAppLeaser,\n loadGitHubAppConfig,\n parseGitRemote,\n PostgresStore,\n toAuthedHttpsUrl,\n} from '@agentbox/relay';\nimport { randomBytes } from 'node:crypto';\nimport { providerForCreate } from '../provider/registry.js';\nimport { getRuntimeProviderNames, loadProviderModule } from '../provider/loaders.js';\nimport {\n buildRebakeNote,\n buildShareFailedNote,\n classifyBakeShare,\n hasCredentialChanges,\n isShareablePreparedProvider,\n summarizeBakeShare,\n type BakeShareResult,\n} from '../control-plane/bake-share.js';\nimport { makeControlPlaneCreateBox, cloneRepoWithLfs } from '../control-plane/create-box.js';\nimport { runGitHubAppManifestFlow } from '../control-plane/github-app-manifest.js';\nimport { deployControlPlaneToVercel } from '../control-plane/deploy-vercel.js';\nimport {\n assertReachableRecord,\n purgeLocalControlPlaneState,\n readDeployRecord,\n recoveryHint,\n runHetznerDeploy,\n runHetznerDestroy,\n runHetznerUpdate,\n} from '../control-plane/deploy-hetzner.js';\nimport {\n recoveryHint as recoveryHintDigitalOcean,\n runDigitalOceanDeploy,\n runDigitalOceanDestroy,\n runDigitalOceanUpdate,\n} from '../control-plane/deploy-digitalocean.js';\nimport { fetchNpmBest } from '../lib/update-check.js';\nimport {\n runExpose,\n runLocalUpdate,\n runLocalDestroy,\n type ExposeResult,\n} from '../control-plane/expose.js';\nimport type { TunnelKind } from '../control-plane/tunnel.js';\nimport {\n defaultDeployRef,\n describeHubDeploySource,\n resolveHubDeploySource,\n} from '../control-plane/deploy-ref.js';\nimport { AGENTBOX_VERSION } from '../version.js';\nimport {\n findHostGitToken,\n originGitHost,\n overbroadScopes,\n resolveTokenLogin,\n resolveTokenScopes,\n} from '../control-plane/host-git-token.js';\nimport { openCommandLog } from '../lib/log-file.js';\nimport { AGENTBOX_HUB_SSH_ALIAS, type ControlPlaneDeployRecord } from '@agentbox/sandbox-core';\nimport { resolveHubAuthEnv } from '../control-plane/hub-auth-env.js';\nimport {\n addRepoUrl,\n checkRepoInstalled,\n loadControlPlaneMeta,\n openInBrowser,\n resolveOwnerRepo,\n} from '../control-plane/ensure-repo-installed.js';\nimport {\n CustodyClient,\n collectAgentCredentialUploads,\n planPush,\n type UploadItem,\n} from '../control-plane/custody-client.js';\nimport { HubApiClient, HubApiError, type HubApiJob } from '../control-plane/hub-api-client.js';\nimport { hubApiTargetFrom, withHubClient } from '../control-plane/with-hub.js';\nimport { loadControlPlaneEnv } from '../control-plane/env-file.js';\nimport { AGENT_SYNC_SPECS } from '@agentbox/sandbox-core';\nimport { handleLifecycleError } from './_errors.js';\n\nconst CP_DIR = join(homedir(), '.agentbox', 'control-plane');\nconst PEM_PATH = join(CP_DIR, 'github-app.pem');\nconst ENV_PATH = join(CP_DIR, 'control-plane.env');\nconst META_PATH = join(CP_DIR, 'control-plane.json');\n\n/** Default GitHub repo the control plane is deployed from (Vercel + Hetzner). */\nconst DEFAULT_DEPLOY_REPO = 'madarco/agentbox';\n/** `--repo` accepts an `owner/name` slug or a full git URL; the VPS clones a URL. */\nfunction repoSlugToUrl(spec: string): string {\n return spec.includes('://') ? spec : `https://github.com/${spec}.git`;\n}\n/** Tracks the running CLI — see `deployRefForVersion` for why it can't be a constant. */\nconst DEFAULT_DEPLOY_REF = defaultDeployRef();\n\n/** Persist `relay.controlPlaneUrl` and report it. Shared by set-url + setup. */\nasync function applyControlPlaneUrl(url: string): Promise<string> {\n const trimmed = url.replace(/\\/$/, '');\n await setConfigValue('global', 'relay.controlPlaneUrl', trimmed, process.cwd());\n return trimmed;\n}\n\n/** Poll a deployed plane's /healthz until it answers (or the deadline elapses). */\nasync function waitForHealthz(url: string, deadlineMs: number): Promise<boolean> {\n const stop = Date.now() + deadlineMs;\n while (Date.now() < stop) {\n try {\n const res = await fetch(`${url}/healthz`, { signal: AbortSignal.timeout(8000) });\n if (res.ok) return true;\n } catch {\n /* retry */\n }\n await delay(4000);\n }\n return false;\n}\n\n/**\n * The hetzner hub-auth env block appended to `control-plane.env`. The full-hub\n * compose sets the profile literally, but these secrets (`BETTER_AUTH_SECRET`,\n * admin email/password) are read from the `.env` by the compose file, so a\n * network-reachable hub is login-gated.\n */\nfunction hetznerAuthBody(hubAuth: {\n AGENTBOX_HUB_AUTH: string;\n BETTER_AUTH_SECRET: string;\n AGENTBOX_HUB_ADMIN_EMAIL: string;\n AGENTBOX_HUB_ADMIN_PASSWORD: string;\n}): string {\n return (\n `AGENTBOX_HUB_PROFILE=hetzner\\n` +\n `AGENTBOX_HUB_AUTH=${hubAuth.AGENTBOX_HUB_AUTH}\\n` +\n `BETTER_AUTH_SECRET=${hubAuth.BETTER_AUTH_SECRET}\\n` +\n `AGENTBOX_HUB_ADMIN_EMAIL=${hubAuth.AGENTBOX_HUB_ADMIN_EMAIL}\\n` +\n `AGENTBOX_HUB_ADMIN_PASSWORD=${hubAuth.AGENTBOX_HUB_ADMIN_PASSWORD}\\n`\n );\n}\n\n/**\n * Ensure `control-plane.env` carries the hub-auth block (a prior `setup --deploy\n * none` writes only the App creds). Appends it when `BETTER_AUTH_SECRET` is\n * absent; returns false only if the operator cancels the login prompt.\n */\nasync function ensureHetznerHubAuth(): Promise<boolean> {\n const body = existsSync(ENV_PATH) ? readFileSync(ENV_PATH, 'utf8') : '';\n if (/^BETTER_AUTH_SECRET=/m.test(body)) return true;\n const hubAuth = await resolveHubAuthEnv();\n if (!hubAuth) return false;\n await writeFile(ENV_PATH, body + hetznerAuthBody(hubAuth), { mode: 0o600 });\n await chmod(ENV_PATH, 0o600);\n return true;\n}\n\n/**\n * The auth block for a LOCAL exposed hub: just the login secret + admin creds.\n * Unlike {@link hetznerAuthBody} it omits `AGENTBOX_HUB_PROFILE`/`AGENTBOX_HUB_AUTH`\n * — those are set on the spawn env by `buildExposedHubEnv`, not read from the\n * file (and leaving the profile out of the file keeps it from bleeding into the\n * CLI's own `process.env` via `loadControlPlaneEnv`).\n */\nfunction localHubAuthBody(hubAuth: {\n BETTER_AUTH_SECRET: string;\n AGENTBOX_HUB_ADMIN_EMAIL: string;\n AGENTBOX_HUB_ADMIN_PASSWORD: string;\n}): string {\n return (\n `BETTER_AUTH_SECRET=${hubAuth.BETTER_AUTH_SECRET}\\n` +\n `AGENTBOX_HUB_ADMIN_EMAIL=${hubAuth.AGENTBOX_HUB_ADMIN_EMAIL}\\n` +\n `AGENTBOX_HUB_ADMIN_PASSWORD=${hubAuth.AGENTBOX_HUB_ADMIN_PASSWORD}\\n`\n );\n}\n\n/** Ensure the local exposed hub's login secret + admin creds are in the env file. */\nasync function ensureLocalHubAuth(): Promise<boolean> {\n const body = existsSync(ENV_PATH) ? readFileSync(ENV_PATH, 'utf8') : '';\n if (/^BETTER_AUTH_SECRET=/m.test(body)) return true;\n const hubAuth = await resolveHubAuthEnv();\n if (!hubAuth) return false;\n await writeFile(ENV_PATH, body + localHubAuthBody(hubAuth), { mode: 0o600 });\n await chmod(ENV_PATH, 0o600);\n return true;\n}\n\ntype DeployTarget = 'vercel' | 'hetzner' | 'digitalocean' | 'local' | 'none';\n\ninterface SetupOpts {\n gitAuth?: string;\n name?: string;\n org?: string;\n deploy?: string;\n ref?: string;\n repo?: string;\n package?: string;\n // --deploy local passthrough (see `hub expose`).\n bind?: string;\n tunnel?: string;\n tunnelToken?: string;\n publicUrl?: string;\n autostart?: boolean;\n}\n\n/**\n * `gh` is mandatory for the remote hub: the control box leases the push tokens\n * its cloud boxes use through the GitHub CLI. Given the resolved path (or null\n * when it isn't on PATH), returns the error to print, else null. Pure over the\n * lookup so the message is unit-testable without spawning anything.\n */\nexport function ghPreflightError(ghPath: string | null): string | null {\n if (ghPath) return null;\n return (\n 'The GitHub CLI (`gh`) is required to set up a remote Hub — the control box leases push tokens through it.\\n' +\n 'Install it from https://cli.github.com, run `gh auth login`, then re-run `agentbox hub setup`.'\n );\n}\n\n/** Resolve `bin` on PATH (definitive install check), or null when absent. */\nasync function onPath(bin: string): Promise<string | null> {\n const r = await execa('which', [bin], { reject: false });\n if (r.exitCode !== 0) return null;\n const p = (r.stdout ?? '').trim();\n return p.length > 0 ? p : null;\n}\n\n/** The flag, else the config default (`gh`). An unknown value is a hard error. */\nasync function resolveGitAuthMode(flag: string | undefined): Promise<HubGitAuthMode> {\n if (flag === 'gh' || flag === 'app') return flag;\n if (flag) throw new Error(`unknown --git-auth \"${flag}\" (expected: gh | app)`);\n const cfg = await loadEffectiveConfig(process.cwd()).catch(() => null);\n return cfg?.effective.hub.gitAuth ?? 'gh';\n}\n\n/**\n * Find (and confirm) the GitHub token the control box will use as its own.\n *\n * Shown before it leaves the machine — this is a credential being copied to a\n * server, so \"which token, whose account, what can it do\" has to be visible\n * rather than inferred. Returns null when the user declines or none is found.\n */\nasync function resolveHubGitToken(logLine: (line: string) => void): Promise<string | null> {\n const s = spinner();\n s.start('looking for a GitHub token on this machine');\n const found = await findHostGitToken();\n if (!found) {\n s.stop('no GitHub token found', 1);\n // Name the host: on a GitHub Enterprise Server repo a plain `gh auth login`\n // authenticates github.com and leaves this exactly as broken.\n const host = await originGitHost(process.cwd());\n const loginCmd = host === 'github.com' ? 'gh auth login' : `gh auth login --hostname ${host}`;\n log.error(\n 'No GitHub credential found on this machine.\\n' +\n `Run \\`${loginCmd}\\` (browser flow, no admin approval needed) and try again.`,\n );\n return null;\n }\n const [login, scopes] = await Promise.all([\n resolveTokenLogin(found.token, found.host),\n resolveTokenScopes(found.token, found.host),\n ]);\n s.stop(\n `found a GitHub token via ${found.source === 'gh' ? '`gh auth token`' : \"git's credential helper\"}` +\n (login ? ` (@${login})` : ''),\n );\n logLine(\n `git token source=${found.source} host=${found.host} login=${login ?? '?'} scopes=${scopes.join(',') || '(none reported)'}`,\n );\n\n const wide = overbroadScopes(scopes);\n const detail = [\n `The control box will hold this token and use it to clone and push on your boxes' behalf.`,\n `Boxes never receive it.`,\n login ? `Account: @${login}` : null,\n scopes.length > 0 ? `Scopes: ${scopes.join(', ')}` : null,\n wide.length > 0\n ? `Warning: this token carries ${wide.join(', ')} — far more than the hub needs (contents + pull requests). Consider a fine-grained token scoped to the repos you'll use.`\n : null,\n ]\n .filter(Boolean)\n .join('\\n');\n note(detail, 'Git credential');\n\n const ok = await confirm({ message: 'Copy this token to the control box?' });\n if (isCancel(ok) || !ok) {\n log.warn('cancelled — no token copied.');\n return null;\n }\n return found.token;\n}\n\nconst setupSub = new Command('setup')\n .description('Set up a persistent remote Hub for your AgentBoxes')\n // The GitHub-App path is no longer surfaced (we want a plain `gh` token) but\n // still works when passed explicitly, so these three options are hidden, not\n // removed. gh is the default, so nobody needs `--git-auth` for the normal path.\n .addOption(\n new Option(\n '--git-auth <mode>',\n 'how the control box reaches GitHub (default: reuse your own gh token)',\n ).hideHelp(),\n )\n .addOption(new Option('--name <name>', 'GitHub App name').hideHelp())\n .addOption(new Option('--org <org>', 'create the App under an organization').hideHelp())\n .option(\n '--deploy <target>',\n 'what to do after writing the config: hetzner | digitalocean | vercel | local (expose this machine) | none',\n )\n .option(\n '--repo <owner/name>',\n \"GitHub repo to deploy the plane from (default madarco/agentbox; fork + pass this if you don't own it). Implies building from source\",\n )\n .option(\n '--ref <ref>',\n `build the hub from source at this git ref instead of installing the published package (branch/tag/sha; ${DEFAULT_DEPLOY_REF} matches this CLI)`,\n )\n .option(\n '--package <spec>',\n `npm spec of @madarco/agentbox to install on the control box (default ${AGENTBOX_VERSION}, this CLI's own version)`,\n )\n .option(\n '--bind <addr>',\n '--deploy local: hub bind address (default 0.0.0.0 for LAN; 127.0.0.1 = loopback + tunnel only)',\n )\n .option(\n '--tunnel <kind>',\n '--deploy local: make cloud boxes able to reach the hub: cloudflare | tailscale',\n )\n .option(\n '--tunnel-token <token>',\n '--deploy local: named Cloudflare tunnel token (stable hostname)',\n )\n .option(\n '--public-url <url>',\n '--deploy local: the box-facing URL (your own proxy/DNS); skips tunnel URL scraping',\n )\n .option('--no-autostart', '--deploy local: do not install a launchd/systemd autostart unit')\n .action(async (opts: SetupOpts) => {\n // Every progress line here goes to a @clack spinner, which overwrites\n // itself — a failed deploy left nothing to read afterwards. Tee to\n // ~/.agentbox/logs/hub-setup.log (and latest.log) like create/claude do.\n const cmdLog = openCommandLog('hub-setup');\n try {\n // gh is mandatory for the remote hub — fail fast before any App/deploy work.\n const ghErr = ghPreflightError(await onPath('gh'));\n if (ghErr) {\n log.error(ghErr);\n cmdLog.write(`preflight: ${ghErr.replace(/\\n/g, ' ')}`);\n process.exitCode = 1;\n return;\n }\n const gitAuth = await resolveGitAuthMode(opts.gitAuth);\n cmdLog.write(`git auth mode: ${gitAuth}`);\n\n // The App path is now opt-in: it needs the repo OWNER to install the App,\n // which in most work orgs is an admin decision the user can't make.\n let app: Awaited<ReturnType<typeof runGitHubAppManifestFlow>> | null = null;\n let hostToken: string | null = null;\n if (gitAuth === 'app') {\n // Globally-unique by default — GitHub rejects duplicate App names.\n const name = opts.name ?? `agentbox-${randomBytes(4).toString('hex')}`;\n note(\n 'Your browser will open to GitHub to create the App. Review the\\n' +\n 'permissions (Contents + Pull requests: write) and click \"Create\".',\n 'GitHub App',\n );\n const s = spinner();\n s.start('waiting for the GitHub App to be created in your browser');\n app = await runGitHubAppManifestFlow({\n appName: String(name),\n org: opts.org,\n // Honor GHES overrides (and make the flow scriptable in tests).\n githubUrl: process.env.GITHUB_URL,\n apiBaseUrl: process.env.GITHUB_API_URL,\n openBrowser: openInBrowser,\n log: (line) => {\n s.message(line);\n cmdLog.write(line);\n },\n });\n s.stop(`GitHub App created: ${app.slug} (id ${app.appId})`);\n cmdLog.write(`GitHub App created: ${app.slug} (id ${app.appId})`);\n } else {\n hostToken = await resolveHubGitToken(cmdLog.write.bind(cmdLog));\n if (!hostToken) {\n process.exitCode = 1;\n return;\n }\n }\n\n // Persist the credential + a generated admin token as the plane's deploy env.\n const adminToken = randomBytes(32).toString('hex');\n // Headless bearer for the hub's public /api/v1 (CLI / tray against a remote\n // control box, which can't carry the browser session cookie). Separate from\n // the admin token, which gates the internal /admin/* wire.\n const hubApiKey = randomBytes(32).toString('hex');\n await mkdir(CP_DIR, { recursive: true });\n let credentialLines = '';\n if (app) {\n await writeFile(PEM_PATH, app.pem, { mode: 0o600 });\n await chmod(PEM_PATH, 0o600);\n credentialLines =\n `GITHUB_APP_ID=${app.appId}\\n` +\n `GITHUB_APP_PRIVATE_KEY=${Buffer.from(app.pem, 'utf8').toString('base64')}\\n`;\n } else if (hostToken) {\n // Routed to the VPS's data-volume secrets.env by the deploy, never into\n // the compose `environment:` block (readable via `docker inspect`).\n credentialLines = `GH_TOKEN=${hostToken}\\n`;\n }\n const envBody =\n `# AgentBox control plane deploy env (generated by 'agentbox hub setup').\\n` +\n `# Feed to docker compose (--env-file) or 'vercel env add'. Keep secret.\\n` +\n credentialLines +\n `AGENTBOX_RELAY_ADMIN_TOKEN=${adminToken}\\n` +\n `AGENTBOX_HUB_API_KEY=${hubApiKey}\\n`;\n await writeFile(ENV_PATH, envBody, { mode: 0o600 });\n await chmod(ENV_PATH, 0o600);\n if (app) {\n await writeFile(\n META_PATH,\n JSON.stringify(\n { appId: app.appId, slug: app.slug, htmlUrl: app.htmlUrl, installUrl: app.installUrl },\n null,\n 2,\n ) + '\\n',\n { mode: 0o600 },\n );\n }\n\n log.success(\n app\n ? `GitHub App ready. Deploy config written to ${ENV_PATH} (0600).`\n : `Git credential ready. Deploy config written to ${ENV_PATH} (0600).`,\n );\n\n // --- Deploy step (after the App exists) ---\n const target = await resolveDeployTarget(opts.deploy);\n\n // Local: flip THIS machine's hub into the control box — no VPS. Own path\n // (no remote deploy spinner / healthz-over-the-internet), then return.\n if (target === 'local') {\n if (!(await ensureLocalHubAuth())) {\n log.warn('cancelled — no admin login set; the exposed hub would be open. Not exposing.');\n return;\n }\n const exposed = await runLocalExpose(opts, cmdLog.write.bind(cmdLog));\n // This machine is now the control box (reached over loopback) — get its\n // agent logins + bake records in place before the first hub-created box.\n if (exposed) await finalizeControlBoxState(undefined);\n return;\n }\n\n let deployedUrl: string | null = null;\n if (target !== 'none') {\n // Prompt for the hub login admin BEFORE the deploy spinner starts (a\n // spinner and @clack prompts can't share the terminal). Setting these\n // turns login on in the deployed hub so it is never left loginless — both\n // vercel and hetzner (the Caddy-HTTPS docker-compose deploy).\n const hubAuth = await resolveHubAuthEnv();\n // hetzner + digitalocean read ENV_PATH (written to the VPS .env) — the\n // same docker-compose deploy — so append the auth env + the profile so\n // docker-compose enforces login there too.\n if ((target === 'hetzner' || target === 'digitalocean') && hubAuth) {\n await writeFile(ENV_PATH, envBody + hetznerAuthBody(hubAuth), { mode: 0o600 });\n await chmod(ENV_PATH, 0o600);\n }\n const ds = spinner();\n ds.start(`deploying the control plane to ${target}`);\n // Captured from the deploy's onProvisioned so a later failure can still\n // tell the user how to reach the (still-running) VPS.\n let provisioned: ControlPlaneDeployRecord | null = null;\n try {\n const onLog = (line: string): void => {\n ds.message(line);\n cmdLog.write(line);\n };\n const repo = opts.repo ?? DEFAULT_DEPLOY_REPO;\n const ref = opts.ref ?? DEFAULT_DEPLOY_REF;\n if (target === 'vercel') {\n // Vercel has no data volume, so the git token has to ride the\n // project env there (encrypted at rest) rather than a secrets file.\n const env = {\n ...(app\n ? {\n GITHUB_APP_ID: app.appId,\n GITHUB_APP_PRIVATE_KEY: Buffer.from(app.pem, 'utf8').toString('base64'),\n }\n : {}),\n ...(hostToken ? { GH_TOKEN: hostToken } : {}),\n AGENTBOX_RELAY_ADMIN_TOKEN: adminToken,\n AGENTBOX_HUB_API_KEY: hubApiKey,\n ...(hubAuth ?? {}),\n };\n deployedUrl = (await deployControlPlaneToVercel({ env, repo, ref, log: onLog })).url;\n } else {\n const source = resolveHubDeploySource(AGENTBOX_VERSION, {\n ref: opts.ref,\n // `--repo` is an owner/name slug for Vercel; the VPS clones a URL.\n ...(opts.repo ? { repoUrl: repoSlugToUrl(opts.repo) } : {}),\n ...(opts.package ? { packageSpec: opts.package } : {}),\n });\n onLog(`hub source: ${describeHubDeploySource(source)}`);\n // hetzner + digitalocean share the same docker-compose VPS deploy,\n // signature-compatible; only the provisioned cloud differs.\n const runVpsDeploy =\n target === 'digitalocean' ? runDigitalOceanDeploy : runHetznerDeploy;\n deployedUrl = (\n await runVpsDeploy({\n envPath: ENV_PATH,\n source,\n log: onLog,\n onProvisioned: (info) => {\n provisioned = info;\n },\n })\n ).url;\n }\n ds.stop(`deployed: ${deployedUrl}`);\n } catch (e) {\n // Stop the spinner (code 1) before printing — otherwise it keeps\n // animating its last \"creating the firewall…\" frame under the error.\n ds.stop(`deploy to ${target} failed`, 1);\n const msg = e instanceof Error ? e.message : String(e);\n cmdLog.write(`deploy to ${target} failed: ${msg}`);\n log.warn(`deploy to ${target} failed: ${msg}`);\n const hint = target === 'digitalocean' ? recoveryHintDigitalOcean : recoveryHint;\n if (provisioned) note(hint(provisioned).join('\\n'), 'Debug the VPS');\n log.info(`Full deploy log: ${cmdLog.path}`);\n printManualDeploy();\n }\n } else {\n printManualDeploy();\n }\n\n if (deployedUrl) {\n const url = await applyControlPlaneUrl(deployedUrl);\n log.success(`Pointed the CLI at ${url} (relay.controlPlaneUrl).`);\n const ok = await waitForHealthz(url, 60_000);\n // Terse on success; the failure branch stays informative (names the URL).\n if (ok) log.success('Healthy');\n else log.warn(`Could not confirm ${url}/healthz yet — check the deployment.`);\n // Only once the box answers is there anything to push to.\n if (ok) await finalizeControlBoxState(url);\n }\n\n if (app) {\n // Open the repo-selection page so the user can authorize repos right away.\n log.info(`Install the App on your repos: ${app.installUrl}`);\n openInBrowser(app.installUrl);\n }\n } catch (err) {\n cmdLog.write(`FAILED: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);\n handleLifecycleError(err);\n } finally {\n cmdLog.close();\n }\n });\n\n/**\n * The deploy targets offered in the interactive picker. Vercel is intentionally\n * absent — `--deploy vercel` still works when passed explicitly, it's just no\n * longer surfaced. Exported so the omission is unit-testable.\n */\nexport const INTERACTIVE_DEPLOY_OPTIONS: ReadonlyArray<{ value: DeployTarget; label: string }> = [\n { value: 'local', label: 'This machine — turn the local hub into the control box (no VPS)' },\n { value: 'hetzner', label: 'Hetzner VPS — HTTPS via <ip>.sslip.io + Caddy/Let’s Encrypt' },\n {\n value: 'digitalocean',\n label: 'DigitalOcean Droplet — HTTPS via <ip>.sslip.io + Caddy/Let’s Encrypt',\n },\n { value: 'none', label: 'Skip — I’ll deploy later (print manual steps)' },\n];\n\n/** Resolve the deploy target from the flag, or ask interactively. */\nexport async function resolveDeployTarget(flag: string | undefined): Promise<DeployTarget> {\n if (\n flag === 'vercel' ||\n flag === 'hetzner' ||\n flag === 'digitalocean' ||\n flag === 'local' ||\n flag === 'none'\n )\n return flag;\n if (flag) {\n log.warn(`unknown --deploy \"${flag}\"; choose interactively`);\n }\n const choice = await select({\n message: 'Deploy the control plane now?',\n options: [...INTERACTIVE_DEPLOY_OPTIONS],\n initialValue: 'local',\n });\n if (isCancel(choice)) return 'none';\n return choice as DeployTarget;\n}\n\nfunction printManualDeploy(): void {\n log.info(\n [\n 'Deploy later with the written env:',\n ` This machine: agentbox hub expose (no VPS — the local hub becomes the control box)`,\n ` Self-host: cd apps/hub && docker compose --env-file ${ENV_PATH} up --build`,\n ` Vercel: agentbox hub setup --deploy vercel (or 'vercel env add' the vars + 'vercel deploy --prod')`,\n ` Then: agentbox hub set-url https://<your-plane-url>`,\n ].join('\\n'),\n );\n}\n\ninterface ExposeCliOpts {\n bind?: string;\n tunnel?: string;\n tunnelToken?: string;\n publicUrl?: string;\n autostart?: boolean;\n}\n\n/**\n * Run the expose flow with a spinner, then report reachability + autostart.\n * Returns the {@link ExposeResult} on success, or null when the flow bailed (bad\n * flag / expose error) so the caller knows not to run the post-expose steps.\n */\nasync function runLocalExpose(\n opts: ExposeCliOpts,\n logWrite: (l: string) => void,\n): Promise<ExposeResult | null> {\n const tunnel = opts.tunnel;\n if (tunnel && tunnel !== 'cloudflare' && tunnel !== 'tailscale') {\n log.error(`unknown --tunnel \"${tunnel}\" (expected: cloudflare | tailscale)`);\n process.exitCode = 1;\n return null;\n }\n const s = spinner();\n s.start('exposing the local hub as the control box');\n let result: ExposeResult;\n try {\n result = await runExpose({\n ...(opts.bind ? { bind: opts.bind } : {}),\n ...(tunnel ? { tunnel: tunnel as TunnelKind } : {}),\n ...(opts.tunnelToken ? { tunnelToken: opts.tunnelToken } : {}),\n ...(opts.publicUrl ? { publicUrl: opts.publicUrl } : {}),\n autostart: opts.autostart !== false,\n onLog: (l) => {\n s.message(l);\n logWrite(l);\n },\n });\n s.stop(`hub exposed on ${result.publicUrl}`);\n } catch (e) {\n s.stop('expose failed', 1);\n const msg = e instanceof Error ? e.message : String(e);\n logWrite(`expose failed: ${msg}`);\n log.error(msg);\n process.exitCode = 1;\n return null;\n }\n note(\n [\n `Box-facing URL: ${result.publicUrl}`,\n `CLI / UI (local): ${result.localUrl}`,\n result.record.tunnel ? `Tunnel: ${result.record.tunnel}` : null,\n result.autostart?.path ? `Autostart: ${result.autostart.path}` : null,\n ]\n .filter(Boolean)\n .join('\\n'),\n 'Control box',\n );\n if (!result.cloudReachable) {\n log.warn(\n 'LAN/loopback only: cloud boxes (e2b/daytona/hetzner/vercel) cannot reach this hub, so they will ' +\n 'not register or push with your machine off. Re-run with `--tunnel cloudflare` (or `--tunnel tailscale`) to enable that.',\n );\n }\n if (result.autostart?.note) log.info(result.autostart.note);\n log.success(\n `This machine is now the control box — sign in at ${result.localUrl}; cloud creates route here.`,\n );\n return result;\n}\n\nconst exposeSub = new Command('expose')\n .description(\"Turn this machine's local hub into the control box (deployed profile, no VPS)\")\n .option(\n '--bind <addr>',\n 'bind address (default 0.0.0.0 for LAN; 127.0.0.1 = loopback + tunnel only)',\n )\n .option('--tunnel <kind>', 'let cloud boxes reach the hub: cloudflare | tailscale')\n .option('--tunnel-token <token>', 'named Cloudflare tunnel token (stable hostname)')\n .option(\n '--public-url <url>',\n 'the box-facing URL (your own proxy/DNS); skips tunnel URL scraping',\n )\n .option('--no-autostart', 'do not install a launchd/systemd autostart unit')\n .action(async (opts: ExposeCliOpts) => {\n try {\n if (!existsSync(ENV_PATH)) {\n log.error(\n 'No control-box credentials yet. Run `agentbox hub setup --deploy local` first — it mints the ' +\n 'admin token + API key and the git credential, then exposes.',\n );\n process.exitCode = 1;\n return;\n }\n if (!(await ensureLocalHubAuth())) {\n log.warn('cancelled — an admin login is required so the exposed hub is not left open.');\n return;\n }\n const exposed = await runLocalExpose(opts, () => {});\n // Re-exposing is still \"a control box just came up\" — get its logins +\n // bake records in place, exactly as `hub setup --deploy local` does.\n if (exposed) await finalizeControlBoxState(undefined);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\n/**\n * The loopback URL of a control box that IS this machine (`hub expose`), or null.\n * The CLI-facing local shortcut: when a hub is exposed here, `hub boxes`,\n * custody, and `hub target` talk to `127.0.0.1:<port>` rather than the\n * box-facing `relay.controlPlaneUrl` (which is the LAN/tunnel URL boxes use).\n */\nexport async function localExposedLoopbackUrl(): Promise<string | null> {\n const rec = await readDeployRecord();\n if (rec?.provider === 'local') return `http://127.0.0.1:${String(rec.port ?? relayPort())}`;\n return null;\n}\n\n/** Prefer the loopback shortcut for a locally-exposed hub, unless `--url` is explicit. */\nasync function applyLocalShortcut(url: string, urlFlag: string | undefined): Promise<string> {\n if (urlFlag) return url;\n const loop = await localExposedLoopbackUrl();\n return loop ?? url;\n}\n\nconst setUrlSub = new Command('set-url')\n .description('Point boxes + the CLI at a deployed control plane (sets relay.controlPlaneUrl)')\n .argument('<url>', 'base URL of the deployed control plane, e.g. https://plane.example.com')\n .action(async (url: string) => {\n try {\n const trimmed = await applyControlPlaneUrl(url);\n log.success(`Set relay.controlPlaneUrl = ${trimmed}`);\n // No ssh key to that box necessarily — but if IT knows its own engine, the\n // default can still move there, because the create is routed over the API.\n const { ensureHubDockerTarget } = await import('../control-plane/hub-docker-target.js');\n await ensureHubDockerTarget((line) => {\n log.info(line);\n });\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst unsetUrlSub = new Command('unset-url')\n .description('Stop using a control plane on this machine (removes relay.controlPlaneUrl)')\n .option(\n '--purge',\n \"also delete this machine's local App metadata + admin token (~/.agentbox/control-plane)\",\n )\n .action(async (opts: { purge?: boolean }) => {\n try {\n // set-url writes the global scope; also clear a per-project override if one\n // exists. A cwd with no project config just yields `existed:false` (the\n // project unset never throws for that) — real I/O/write errors from either\n // scope propagate to handleLifecycleError rather than being masked.\n const g = await unsetConfigValue('global', 'relay.controlPlaneUrl', process.cwd());\n const p = await unsetConfigValue('project', 'relay.controlPlaneUrl', process.cwd());\n if (!g.existed && !p.existed) {\n log.info('No control plane was configured (relay.controlPlaneUrl not set).');\n } else {\n // Whatever this machine defaults to, it must not be the engine of a\n // control box it no longer talks to.\n const { removeHubDockerTarget } = await import('../control-plane/hub-docker-target.js');\n await removeHubDockerTarget((line) => {\n log.info(line);\n });\n const where = [g.existed ? 'global' : null, p.existed ? 'project' : null]\n .filter(Boolean)\n .join(' + ');\n log.success(\n `Removed relay.controlPlaneUrl (${where}). New cloud boxes now push through the host relay ` +\n '(your laptop must be on), and the GitHub-App repo-authorization prompt no longer fires.',\n );\n }\n if (existsSync(CP_DIR)) {\n if (opts.purge) {\n // Same teardown `hub destroy` performs locally — including refreshing\n // the managed ssh config, which this used to skip and so left a\n // `Host agentbox-hub` block pointing at a machine you no longer use.\n await purgeLocalControlPlaneState({ dir: CP_DIR, keepCredentials: false });\n log.success(`Purged this machine's control-plane credentials (${CP_DIR}).`);\n } else {\n log.info(\n `This machine's App metadata + admin token remain in ${CP_DIR} (use --purge to delete).`,\n );\n log.info('To also delete the VPS itself, use `agentbox hub destroy`.');\n }\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\n/** Reachability + box/event counts for a configured (remote) hub. */\nexport interface ControlPlaneStatus {\n url: string;\n healthy: boolean;\n boxes: number;\n events: number;\n detail: string;\n /**\n * The AgentBox version the remote hub is actually running, when it reports one.\n * Undefined for a control box deployed before the images exported\n * `AGENTBOX_CLI_VERSION` — callers fall back to the deploy record.\n */\n version?: string;\n}\n\n/**\n * Probe a remote hub's `/healthz` for reachability + box/event counts. Used by\n * the unified `agentbox hub status` when a control box is configured (the local\n * hub renders `getHubStatus()` instead). Never throws — an unreachable hub comes\n * back `healthy:false` with the error name in `detail`.\n */\nexport async function probeControlPlaneStatus(url: string): Promise<ControlPlaneStatus> {\n let healthy = false;\n let boxes = 0;\n let events = 0;\n let detail = '';\n let version: string | undefined;\n try {\n const res = await fetch(`${url}/healthz`, { signal: AbortSignal.timeout(8000) });\n healthy = res.ok;\n const body = (await res.json().catch(() => ({}))) as {\n boxes?: number;\n events?: number;\n version?: string;\n };\n boxes = body.boxes ?? 0;\n events = body.events ?? 0;\n version = body.version;\n detail = `${String(boxes)} box(es), ${String(events)} event(s)`;\n } catch (e) {\n detail = e instanceof Error ? e.name : String(e);\n }\n return { url, healthy, boxes, events, detail, ...(version ? { version } : {}) };\n}\n\nconst addSub = new Command('add')\n .description(\"Authorize the current project's git repo on the control plane's GitHub App\")\n .action(async () => {\n try {\n const cfg = await loadEffectiveConfig(process.cwd());\n const controlPlaneUrl = cfg.effective.relay.controlPlaneUrl;\n if (!controlPlaneUrl) {\n log.error('No control plane configured. Run `agentbox hub set-url <url>` first.');\n process.exitCode = 1;\n return;\n }\n const ownerRepo = await resolveOwnerRepo(process.cwd());\n if (!ownerRepo) {\n log.error('No git origin found here — `cd` into a project with a GitHub remote.');\n process.exitCode = 1;\n return;\n }\n const { owner, repo } = ownerRepo;\n const installed = await checkRepoInstalled(owner, repo, controlPlaneUrl);\n if (installed === true) {\n log.success(`${owner}/${repo} is already authorized on the GitHub App.`);\n return;\n }\n const url = addRepoUrl(loadControlPlaneMeta());\n if (!url) {\n log.error(\n 'No GitHub App metadata found locally. Run this from a machine that ran `hub setup`,\\n' +\n 'or open your App settings on GitHub and add the repo manually.',\n );\n process.exitCode = 1;\n return;\n }\n log.info(`Opening ${url} — select ${owner}/${repo}, then approve.`);\n openInBrowser(url);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\n/** Run `git <args>`, rejecting on a non-zero exit. */\nfunction runGit(args: string[], env?: Record<string, string>, timeoutMs?: number): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn('git', args, {\n stdio: ['ignore', 'ignore', 'pipe'],\n env: env ? { ...process.env, ...env } : process.env,\n });\n const timer = timeoutMs ? setTimeout(() => child.kill('SIGKILL'), timeoutMs) : undefined;\n let err = '';\n child.stderr.on('data', (c: Buffer) => (err += c.toString('utf8')));\n child.on('error', (e) => {\n if (timer) clearTimeout(timer);\n reject(e);\n });\n child.on('close', (code) => {\n if (timer) clearTimeout(timer);\n if (code === 0) resolve();\n else reject(new Error(`git ${args[0]} failed (${String(code)}): ${err.trim()}`));\n });\n });\n}\n\ninterface WorkerOpts {\n store: string;\n once?: boolean;\n pollInterval: string;\n}\n\nconst workerSub = new Command('worker')\n .description(\n 'Drain the control plane box-creation queue and provision real boxes (long-running; needs provider creds + the App key)',\n )\n .requiredOption('--store <url>', 'Postgres URL of the control plane (same store the plane uses)')\n .option('--once', 'drain the queue once and exit (default: loop)')\n .option('--poll-interval <ms>', 'poll interval when looping', '5000')\n .action(async (opts: WorkerOpts) => {\n try {\n loadControlPlaneEnv();\n const store = new PostgresStore({ connectionString: opts.store });\n await store.migrate();\n const cfg = await loadEffectiveConfig(process.cwd());\n\n const createBox = makeControlPlaneCreateBox({\n // Per job, and App-optional — see the same comment in apps/hub/lib/hub-worker.ts.\n // Without an App the bare URL is returned and git's credential helper\n // (`gh auth setup-git` + GH_TOKEN) authenticates the clone.\n leaseRemoteUrl: async (repoUrl) => {\n const appCfg = loadGitHubAppConfig();\n if (!appCfg) return repoUrl;\n const { path } = parseGitRemote(repoUrl);\n const [owner, repo] = path.replace(/\\.git$/, '').split('/');\n if (!owner || !repo) throw new Error(`cannot derive owner/repo from ${repoUrl}`);\n const { token } = await new GitHubAppLeaser(appCfg).leaseRepoToken(owner, repo);\n return toAuthedHttpsUrl(repoUrl, token);\n },\n cloneRepo: (authedUrl, repoUrl, dest, branch) =>\n cloneRepoWithLfs(runGit, authedUrl, repoUrl, dest, branch, (line) => log.info(line)),\n createBox: async ({ workspacePath, name, provider, agent, onLog }) => {\n const p = await providerForCreate({ flag: provider, config: cfg.effective });\n const created = await p.create({\n workspacePath,\n name,\n projectRoot: workspacePath,\n // Registered on the plane so an adopting PC relaunches the right agent.\n agent:\n agent === 'claude' || agent === 'codex' || agent === 'opencode' ? agent : undefined,\n onLog,\n });\n return { id: created.record.id };\n },\n // Overlay the project's custody seed onto the clone, exactly as the\n // resident hub worker does — without this, boxes drained by THIS worker\n // come up missing the untracked files + env material the seed exists to\n // provide. Unlike the hub, this worker is not the custody host, so it\n // reads the blobs over HTTP.\n fetchSeedMaterial: async (repoUrl, dest) => {\n const target = await resolveCustodyApiTarget(undefined, {\n quiet: true,\n remoteOnly: true,\n });\n if (!target) return null;\n const slug = projectSlugFromOriginUrl(repoUrl);\n if (!slug) return null;\n // Probe + bound like every other custody call: a down control box must\n // not park each blob `get` on undici's ~10s connect timeout and stall\n // a create the user is waiting on (see sandbox-cloud/reachability.ts).\n if (!(await hostReachable(target.url))) {\n process.stdout.write(\n 'agentbox-cp-worker: control box unreachable — bare clone, no seed\\n',\n );\n return null;\n }\n const client = new CustodyClient({\n ...target,\n fetchImpl: deadlineFetch(AbortSignal.timeout(SEED_FETCH_MS)),\n });\n return applyProjectSeed({\n source: { get: (rel) => client.get(`projects/${slug}/seed/${rel}`) },\n dest,\n log: (line) => process.stdout.write(`agentbox-cp-worker: ${line}\\n`),\n });\n },\n tmpDir: (jobId) => join(tmpdir(), `agentbox-cp-worker-${jobId}`),\n cleanup: (dir) => rm(dir, { recursive: true, force: true }),\n log: (line) => process.stdout.write(`agentbox-cp-worker: ${line}\\n`),\n });\n\n const workerId = `worker-${hostname()}-${String(process.pid)}`;\n const interval = Number.parseInt(opts.pollInterval, 10) || 5000;\n let running = true;\n const stop = (): void => {\n running = false;\n };\n process.on('SIGINT', stop);\n process.on('SIGTERM', stop);\n process.stdout.write(`agentbox-cp-worker: draining create jobs as ${workerId}\\n`);\n do {\n const n = await drainCreateJobs(store, createBox, workerId);\n if (n > 0) process.stdout.write(`agentbox-cp-worker: processed ${String(n)} job(s)\\n`);\n if (opts.once) break;\n await delay(interval);\n } while (running);\n await store.close();\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\n/**\n * Resolve the control-plane URL (`--url` > `relay.controlPlaneUrl`) and the\n * admin bearer (`AGENTBOX_RELAY_ADMIN_TOKEN` > the setup-written env file).\n * Returns null and prints an actionable error when either is missing.\n *\n * `quiet` suppresses those errors, for callers where a control box is optional\n * and its absence is a normal outcome rather than a user mistake (the recover\n * key fallback, the by-name auto-adopt hook).\n */\nexport async function resolveCustodyTarget(\n urlFlag: string | undefined,\n opts: { quiet?: boolean } = {},\n): Promise<{ url: string; adminToken: string } | null> {\n const cfg = await loadEffectiveConfig(process.cwd());\n const configured = (urlFlag ?? cfg.effective.relay.controlPlaneUrl ?? '').replace(/\\/$/, '');\n // A hub exposed on THIS machine is reached over loopback, not its box-facing URL.\n const url = (await applyLocalShortcut(configured, urlFlag)).replace(/\\/$/, '');\n if (!url) {\n if (!opts.quiet)\n log.error('No control plane configured. Run `agentbox hub set-url <url>` (or pass --url).');\n return null;\n }\n loadControlPlaneEnv();\n const adminToken = process.env.AGENTBOX_RELAY_ADMIN_TOKEN ?? '';\n if (!adminToken) {\n if (!opts.quiet)\n log.error(\n 'No admin token available. Set AGENTBOX_RELAY_ADMIN_TOKEN, or run this from the machine that\\n' +\n 'ran `agentbox hub setup` (it writes the token to ~/.agentbox/control-plane).',\n );\n return null;\n }\n return { url, adminToken };\n}\n\n/** The credentials a {@link CustodyClient} uses; it picks the surface from them. */\nexport interface CustodyApiTarget {\n url: string;\n /**\n * Hub API key (or a local hub token) — the Bearer for the `/api/v1/custody`\n * surface. Absent → the client uses the `/admin/custody` fallback (needs\n * `adminToken`).\n */\n apiKey?: string;\n /**\n * Admin token. On `/api/v1` the elevated credential a byte-read (`pull`) needs on\n * a control box; the sole credential for the `/admin` fallback when no API key is\n * available. Undefined on a plain local hub (whose hub token is the API key and\n * gates byte-reads itself).\n */\n adminToken?: string;\n}\n\n/**\n * Resolve the credentials a custody op should use. Returns whatever is available —\n * the API key (→ `/api/v1/custody`) and/or the admin token (byte-read elevation,\n * or the `/admin/custody` fallback) — so a custody op works with EITHER credential\n * and never silently no-ops for lack of the other. {@link CustodyClient} picks the\n * surface. Distinct from {@link resolveCustodyTarget} (admin-only, `/admin` shape).\n *\n * Failure modes are explicit, never a quiet skip:\n * - **no control box** and (in default mode) no local hub → `null` (a genuine\n * no-op: there is no custody to reach).\n * - **a control box IS configured but NEITHER credential is present** → a loud\n * error naming the missing credential, then `null`; a `quiet` caller (a\n * best-effort background flow) suppresses the print but still returns `null`,\n * and its own caller surfaces the gap (adoption flags `sshKeysMissing`).\n *\n * Works against a plain LOCAL hub too (default mode): the acceptance's\n * `credentials push`/`pull` round-trip there, via the local hub token as the API\n * key (autostarted by {@link resolveHubApiTarget}). `remoteOnly` refuses a local\n * hub, for the automated callers whose job is a configured CONTROL BOX\n * (agent-credential sync, the queue worker's seed fetch, SSH-key adoption).\n */\nexport async function resolveCustodyApiTarget(\n urlFlag: string | undefined,\n opts: { quiet?: boolean; remoteOnly?: boolean } = {},\n): Promise<CustodyApiTarget | null> {\n const { resolveHubTarget } = await import('./hub.js');\n const noCredentialError =\n 'A control box is configured but no custody credential is available. Set AGENTBOX_HUB_API_KEY\\n' +\n '(or AGENTBOX_RELAY_ADMIN_TOKEN), or run this from the machine that ran `agentbox hub setup`\\n' +\n '(it writes both to ~/.agentbox/control-plane) — custody / SSH-key pull needs one of them.';\n\n // Remote control box (a configured plane, or a `hub expose`d loopback). The API\n // key drives `/api/v1`; the admin token is the byte-read elevation there and the\n // sole credential for the `/admin` fallback when no API key is present.\n const target = await resolveHubTarget(urlFlag);\n if (target.mode === 'remote') {\n loadControlPlaneEnv();\n const apiKey = target.token || undefined;\n const adminToken = process.env.AGENTBOX_RELAY_ADMIN_TOKEN || undefined;\n if (!apiKey && !adminToken) {\n if (!opts.quiet) log.error(noCredentialError);\n return null;\n }\n return { url: target.url, apiKey, adminToken };\n }\n\n // No control box. `remoteOnly` callers stop here (expected no-op, silent).\n if (opts.remoteOnly) return null;\n\n // Default: the plain local hub (autostarted). Its hub token is the API key; no\n // admin token exists (and none is needed — the token gates the whole surface).\n const api = await resolveHubApiTarget(urlFlag, opts);\n if (!api) return null;\n return { url: api.url, apiKey: api.apiKey };\n}\n\n/**\n * Bring the local hub up so it can answer `/api/v1`, returning true on success.\n * One spinner, one clear failure line — the autostart step behind\n * {@link resolveHubApiTarget} when the target resolves to a local hub that isn't\n * running yet.\n */\nasync function autostartLocalHub(): Promise<boolean> {\n // Dynamic imports mirror how `hub start` itself is wired. The hub lifecycle now\n // lives in sandbox-core (Step 12), so a docker-free host never pulls in docker\n // machinery to start a hub.\n const { ensureHub } = await import('@agentbox/sandbox-core');\n const { rehydrateFromState } = await import('./relay.js');\n const s = spinner();\n s.start('starting local hub');\n try {\n const ep = await ensureHub({ onLog: (line) => s.message(line) });\n // Same as `hub start`/`restart`: a cold-started relay has an empty in-memory\n // box registry (and no cloud pollers) until the persisted state is re-pushed,\n // so a listing right after autostart would otherwise miss registered boxes.\n await rehydrateFromState();\n s.stop(`local hub running on ${ep.hostUrl}`);\n return true;\n } catch (err) {\n s.stop('local hub failed to start');\n log.error(err instanceof Error ? err.message : String(err));\n return false;\n }\n}\n\n/**\n * Stop then start the local hub so it re-mints `~/.agentbox/hub/token`, returning\n * true on success. The recovery behind {@link resolveHubApiTarget} for a live hub\n * whose token file was deleted underneath it.\n */\nasync function restartLocalHubForToken(): Promise<boolean> {\n const { ensureHub, stopHub } = await import('@agentbox/sandbox-core');\n const { rehydrateFromState } = await import('./relay.js');\n const s = spinner();\n s.start('hub token missing — restarting local hub');\n try {\n await stopHub();\n const ep = await ensureHub({ onLog: (line) => s.message(line) });\n await rehydrateFromState();\n s.stop(`local hub restarted on ${ep.hostUrl}`);\n return true;\n } catch (err) {\n s.stop('local hub failed to restart');\n log.error(err instanceof Error ? err.message : String(err));\n return false;\n }\n}\n\n/**\n * Resolve the hub's public REST API target — its URL + the Bearer that authorizes\n * `/api/v1` — for BOTH modes. Delegates the local⇄remote decision to\n * {@link resolveHubTarget} (the same seam `agentbox hub target` and the tray\n * follow): a configured/exposed control box yields its `AGENTBOX_HUB_API_KEY`; a\n * local hub yields `~/.agentbox/hub/token`. The local hub's `proxy.ts` accepts\n * that token as `Authorization: Bearer`, so the returned target is URL-swappable\n * with a control box's with no client change.\n *\n * When the target is a local hub that isn't running, it is auto-started (unless\n * `quiet`, where a best-effort probe must not spawn a daemon). Returns null (with\n * an actionable error unless `quiet`) when a remote hub has no API key, or a local\n * hub can't be started / still reports no token.\n */\nexport async function resolveHubApiTarget(\n urlFlag: string | undefined,\n opts: { quiet?: boolean; preferLocal?: boolean } = {},\n): Promise<{ url: string; apiKey: string } | null> {\n // Lazy import breaks the hub.ts <-> control-plane.ts cycle: hub.ts consumes\n // `controlPlaneSubcommands` (defined at the bottom of this file) at load time,\n // so a static edge back the other way would read it before it's initialized.\n const { resolveHubTarget } = await import('./hub.js');\n let target = await resolveHubTarget(urlFlag, { preferLocal: opts.preferLocal });\n\n // Bring the full local hub up before its token is used. Two traps this gate\n // avoids: (1) the token at `~/.agentbox/hub/token` PERSISTS across `hub stop`,\n // so token presence is NOT a liveness signal — a stopped hub still resolves with\n // one; (2) a bare `agentbox relay` (e.g. spawned by `create`) answers `/healthz`\n // (`running:true`) but serves no `/api/v1` — so requiring the delegated Next UI\n // (`ui`) is what distinguishes the full hub from a lean relay holding the port.\n // `ensureHub` idempotently reclaims a lean relay / version-mismatched hub, so\n // autostart is safe to trigger in both cases. Skipped under `quiet` (a probe\n // must not spawn a daemon); `getHubStatus` is local-only, so irrelevant remote.\n if (target.mode === 'local' && !opts.quiet) {\n const { getHubStatus, readHubToken } = await import('@agentbox/sandbox-core');\n const st = await getHubStatus();\n if (!(st.running && st.ui)) {\n if (!(await autostartLocalHub())) return null;\n target = await resolveHubTarget(urlFlag, { preferLocal: opts.preferLocal });\n } else if (!(await readHubToken())) {\n // Live hub, but `~/.agentbox/hub/token` is gone — the usual cause is\n // wiping ~/.agentbox while the daemon kept running. The hub only ever\n // reads that file at boot and then serves from the in-memory value, so\n // the secret is unrecoverable and no amount of `agentbox hub` (a no-op\n // against a live daemon) rewrites it. Restarting is the only recovery:\n // `ensureHubToken` mints a fresh one on the next boot.\n if (!(await restartLocalHubForToken())) return null;\n target = await resolveHubTarget(urlFlag, { preferLocal: opts.preferLocal });\n }\n }\n\n const resolved = hubApiTargetFrom(target);\n if (!resolved.ok) {\n if (!opts.quiet)\n log.error(\n resolved.mode === 'remote'\n ? 'No hub API key available. Set AGENTBOX_HUB_API_KEY, or run this from the machine that\\n' +\n 'ran `agentbox hub setup` (it writes the key to ~/.agentbox/control-plane).'\n : 'The local hub reports no API token. Start it with `agentbox hub` and retry.',\n );\n return null;\n }\n return { url: resolved.url, apiKey: resolved.apiKey };\n}\n\n/**\n * Build a {@link HubApiClient} for the configured hub from {@link resolveHubApiTarget}\n * (URL + `/api/v1` key), or null (with an actionable error unless `quiet`) when\n * unconfigured. The one client the CLI builds for hub box/fleet operations.\n */\nexport async function resolveHubApiClient(\n urlFlag: string | undefined,\n opts: { quiet?: boolean; preferLocal?: boolean } = {},\n): Promise<HubApiClient | null> {\n const target = await resolveHubApiTarget(urlFlag, opts);\n return target ? new HubApiClient(target) : null;\n}\n\n/**\n * Slug a project into a custody `projects/<slug>` key: `owner__repo`, else the\n * dir name.\n *\n * Delegates to the shared `projectSlugFromOriginUrl` — every producer and\n * consumer of the `projects/<slug>` scope MUST derive the same key from the same\n * origin, and a second local implementation is exactly how they drift apart. (It\n * did: this used to take the *first* two path segments unsanitized, while the\n * create path and the hub worker take the last two and sanitize — so for a\n * nested remote like `gitlab.com/group/subgroup/repo` a push landed under\n * `group__subgroup` while the worker looked in `subgroup__repo`.)\n */\nasync function projectSlug(explicit: string | undefined, projectRoot: string): Promise<string> {\n if (explicit) return explicit.replace(/[^A-Za-z0-9._-]/g, '-');\n const origin = await readGitOriginUrl(projectRoot).catch(() => undefined);\n const slug = origin ? projectSlugFromOriginUrl(origin) : null;\n if (slug) return slug;\n return basename(projectRoot).replace(/[^A-Za-z0-9._-]/g, '-') || 'project';\n}\n\n/** Upload a set of items with a hash-skip pass; logs one line per decision. */\nasync function pushItems(\n client: CustodyClient,\n items: UploadItem[],\n prefix: string,\n force: boolean,\n): Promise<void> {\n if (items.length === 0) {\n log.info('Nothing to push.');\n return;\n }\n const manifest = await client.list(prefix);\n const plan = planPush(items, manifest, { force });\n let uploaded = 0;\n let skipped = 0;\n for (const item of items) {\n const decision = plan.find((d) => d.path === item.path)!;\n if (decision.action === 'skip') {\n skipped++;\n continue;\n }\n const res = await client.put(item.path, item.data);\n if (res.changed) uploaded++;\n else skipped++;\n }\n log.success(`Pushed ${String(uploaded)} item(s), skipped ${String(skipped)} unchanged.`);\n}\n\nconst credentialsPushSub = new Command('push')\n .description(\n 'Push host agent-credential backups (claude/codex/opencode) to the control box custody store',\n )\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--agent <id>', 'push only one agent: claude | codex | opencode')\n .option('--force', 'upload even when the stored hash matches')\n .action(async (opts: { url?: string; agent?: string; force?: boolean }) => {\n try {\n const target = await resolveCustodyApiTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const only = opts.agent as 'claude' | 'codex' | 'opencode' | undefined;\n if (opts.agent && !['claude', 'codex', 'opencode'].includes(opts.agent)) {\n log.error(`unknown --agent \"${opts.agent}\" (expected claude | codex | opencode)`);\n process.exitCode = 1;\n return;\n }\n const items = await collectAgentCredentialUploads(only);\n const client = new CustodyClient(target);\n await pushItems(client, items, 'agents', opts.force === true);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst credentialsPullSub = new Command('pull')\n .description('Pull agent-credential backups from the control box custody store into ~/.agentbox')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--agent <id>', 'pull only one agent: claude | codex | opencode')\n .action(async (opts: { url?: string; agent?: string }) => {\n try {\n const target = await resolveCustodyApiTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n if (opts.agent && !['claude', 'codex', 'opencode'].includes(opts.agent)) {\n log.error(`unknown --agent \"${opts.agent}\" (expected claude | codex | opencode)`);\n process.exitCode = 1;\n return;\n }\n const client = new CustodyClient(target);\n let pulled = 0;\n for (const spec of AGENT_SYNC_SPECS) {\n if (opts.agent && spec.id !== opts.agent) continue;\n const data = await client.get(`agents/${spec.id}/${spec.credential.boxRelPath}`);\n if (data === null) continue;\n await mkdir(dirname(spec.credential.hostBackup), { recursive: true });\n await writeFile(spec.credential.hostBackup, data, { mode: 0o600 });\n await chmod(spec.credential.hostBackup, 0o600);\n log.info(`pulled ${spec.id} credentials → ${spec.credential.hostBackup}`);\n pulled++;\n }\n if (pulled === 0) log.info('No agent credentials in custody to pull.');\n else log.success(`Pulled ${String(pulled)} agent credential set(s).`);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst credentialsCmd = new Command('credentials')\n .description('Manage agent credentials on the control box custody store')\n .addCommand(credentialsPushSub)\n .addCommand(credentialsPullSub);\n\nconst secretsPushSub = new Command('push')\n .description('Push project secret/env files to the control box custody store')\n .argument('[files...]', 'files to push (default: ./.env if present)')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option(\n '--project <slug>',\n 'custody project slug (default: owner__repo, else the directory name)',\n )\n .option('--force', 'upload even when the stored hash matches')\n .action(async (files: string[], opts: { url?: string; project?: string; force?: boolean }) => {\n try {\n const target = await resolveCustodyApiTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const root = process.cwd();\n const slug = await projectSlug(opts.project, root);\n const chosen =\n files.length > 0 ? files : existsSync(join(root, '.env')) ? [join(root, '.env')] : [];\n if (chosen.length === 0) {\n log.error('No files to push (no ./.env found; pass files explicitly).');\n process.exitCode = 1;\n return;\n }\n const items: UploadItem[] = [];\n for (const f of chosen) {\n items.push({ path: `projects/${slug}/${basename(f)}`, data: await readFile(f) });\n }\n const client = new CustodyClient(target);\n await pushItems(client, items, `projects/${slug}`, opts.force === true);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst secretsCmd = new Command('secrets')\n .description('Manage per-project secrets/envs on the control box custody store')\n .addCommand(secretsPushSub);\n\nconst projectPushSub = new Command('push')\n .description(\n \"Push this project's seed material (untracked files + env/secrets) to the control box, so boxes created from its web UI get the files a fresh clone can't provide. A PC create does this automatically; run this to register a project before creating a box from it.\",\n )\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option(\n '--project <slug>',\n 'custody project slug (default: owner__repo, else the directory name)',\n )\n .option('--force', 'upload even when the stored hash matches')\n .action(async (opts: { url?: string; project?: string; force?: boolean }) => {\n try {\n const target = await resolveCustodyApiTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const root = (await findProjectRoot(process.cwd())).root;\n const slug = await projectSlug(opts.project, root);\n const cfg = await loadEffectiveConfig(root).catch(() => null);\n const client = new CustodyClient(target);\n const res = await pushProjectSeedToCustody({\n // Client surface: the seed rides the hub's /api/v1 custody (writes need\n // only the API key). The create path uses the /admin sink instead.\n sink: {\n list: (prefix) => client.list(prefix),\n put: async (path, data) => {\n await client.put(path, data);\n },\n },\n probeUrl: target.url,\n slug,\n projectRoot: root,\n // The default env set (same one `--with-env` uses). Unlike a create —\n // which mirrors that box's own wizard picks and must not widen them —\n // this command has no box and no picks: the user is explicitly asking to\n // register the project's seed, so the default set is the intent. What\n // actually gets captured is reported below.\n envPatterns: DEFAULT_ENV_PATTERNS,\n // Honour the configured cap, so raising it actually admits a bigger seed.\n maxBodyBytes: cfg?.effective.relay.custodyMaxBlobBytes,\n force: opts.force,\n log: (line) => log.info(line),\n });\n if (res.unreachable) {\n log.error(\n `Control box unreachable at ${target.url} — nothing was pushed. The project is NOT registered; re-run when it is up.`,\n );\n process.exitCode = 1;\n return;\n }\n const head = res.manifest.repoHeadSha?.slice(0, 8) ?? 'unknown';\n log.success(\n `Pushed ${String(res.uploaded)} item(s), skipped ${String(res.skipped)} unchanged → projects/${slug}/seed (at ${head}).`,\n );\n // Name the env files that went up. This command captures the default env\n // set rather than a per-box selection, so the user should never have to\n // guess which secrets now live on the control box.\n if (res.envFiles.length > 0) {\n log.info(`env/secret files captured: ${res.envFiles.join(', ')}`);\n }\n if (res.skippedTarBytes !== undefined) {\n log.warn(\n `The untracked-files tar (${String(Math.round(res.skippedTarBytes / 1024 / 1024))}MB) exceeded this machine's custody body cap and was NOT pushed — ` +\n 'hub-created boxes will miss those files. To include it, raise `relay.custodyMaxBlobBytes` here AND ' +\n 'AGENTBOX_CUSTODY_MAX_BLOB_BYTES on the control box (it enforces its own cap).',\n );\n }\n if (res.dropped.length > 0) {\n log.warn(\n `The control box refused ${res.dropped.join(', ')} — hub-created boxes will miss those files. ` +\n 'If it is a size limit, raise AGENTBOX_CUSTODY_MAX_BLOB_BYTES on the control box.',\n );\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst projectCmd = new Command('project')\n .description('Manage a project on the control box (seed material for hub-created boxes)')\n .addCommand(projectPushSub);\n\nconst custodyListSub = new Command('list')\n .description('List custody entries (paths + hashes; values are never returned)')\n .argument('[prefix]', 'scope to a prefix, e.g. agents or projects/owner__repo')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .action(async (prefix: string | undefined, opts: { url?: string }) => {\n try {\n const target = await resolveCustodyApiTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const client = new CustodyClient(target);\n const entries = await client.list(prefix);\n if (entries.length === 0) {\n log.info('No custody entries.');\n return;\n }\n for (const e of entries) {\n process.stdout.write(`${e.path} ${String(e.size)}B ${e.sha256.slice(0, 12)}\\n`);\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst custodyPullSub = new Command('pull')\n .description('Download a custody scope to a local directory (0600 files)')\n .argument('<scope>', 'custody scope/prefix, e.g. agents, projects/owner__repo, boxes/<id>')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--dest <dir>', 'destination directory (default: ./agentbox-custody)')\n .action(async (scope: string, opts: { url?: string; dest?: string }) => {\n try {\n const target = await resolveCustodyApiTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const dest = opts.dest ?? join(process.cwd(), 'agentbox-custody');\n const client = new CustodyClient(target);\n const entries = await client.list(scope);\n if (entries.length === 0) {\n log.info(`No custody entries under '${scope}'.`);\n return;\n }\n let pulled = 0;\n for (const e of entries) {\n const data = await client.get(e.path);\n if (data === null) continue;\n const out = join(dest, e.path);\n await mkdir(dirname(out), { recursive: true, mode: 0o700 });\n await writeFile(out, data, { mode: 0o600 });\n await chmod(out, 0o600);\n pulled++;\n }\n log.success(\n `Pulled ${String(pulled)} entr${pulled === 1 ? 'y' : 'ies'} under '${scope}' to ${dest}.`,\n );\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst custodyRmSub = new Command('rm')\n .description('Delete a custody entry (one path) from the control box')\n .argument(\n '<path>',\n 'custody path, e.g. boxes/<sandboxId>/ssh/id_ed25519 or agents/claude/.credentials.json',\n )\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .action(async (path: string, opts: { url?: string }) => {\n try {\n const target = await resolveCustodyApiTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const deleted = await new CustodyClient(target).delete(path);\n if (deleted) log.success(`Deleted custody entry '${path}'.`);\n else log.info(`No custody entry at '${path}'.`);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst custodyCmd = new Command('custody')\n .description('Inspect + download the control box custody store')\n .addCommand(custodyListSub)\n .addCommand(custodyPullSub)\n .addCommand(custodyRmSub);\n\n// --- control-plane box registry (the PC's admin view of the control box) ---\n\nconst boxesListSub = new Command('list')\n .description('List boxes on the hub (via its /api/v1) — a control box, or the local hub')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--json', 'print raw JSON')\n .action(async (opts: { url?: string; json?: boolean }) => {\n await withHubClient(opts, async (client) => {\n const boxes = await client.listBoxes();\n if (opts.json) {\n process.stdout.write(`${JSON.stringify({ boxes }, null, 2)}\\n`);\n return;\n }\n if (boxes.length === 0) {\n log.info('No boxes on the hub.');\n return;\n }\n for (const b of boxes) {\n process.stdout.write(\n `${b.id} ${b.name ?? b.task} ${b.provider} ${b.state ?? b.status}\\n`,\n );\n }\n });\n });\n\n// Box lifecycle (start/stop/pause/resume/destroy) is NOT a `hub boxes`\n// subcommand: the top-level `agentbox start|stop|pause|unpause|destroy` route\n// through the same hub `/api/v1` in both modes (Step 5), so a redundant\n// `hub boxes <action>` stopgap would be a second way to do the same thing.\n// `hub boxes list` stays — it's the PC's admin view of the hub's registry.\nconst boxesCmd = new Command('boxes')\n .description('List boxes on the hub over its public /api/v1 (a control box, or the local hub)')\n .addCommand(boxesListSub);\n\n// --- control-plane approvals (answerable from the PC over /api/v1) ---\n\nconst approvalsListSub = new Command('list')\n .description('List pending host-action approvals across control-box boxes')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--json', 'print raw JSON')\n .action(async (opts: { url?: string; json?: boolean }) => {\n try {\n const client = await resolveHubApiClient(opts.url);\n if (!client) {\n process.exitCode = 1;\n return;\n }\n // One call returns every pending approval (vs the admin wire's N per-box\n // fetches); cross-ref the box list once for human-readable names.\n const [approvals, boxes] = await Promise.all([\n client.listApprovals(),\n client.listBoxes().catch(() => []),\n ]);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(approvals, null, 2)}\\n`);\n return;\n }\n if (approvals.length === 0) {\n log.info('No pending approvals.');\n return;\n }\n const nameBy = new Map(boxes.map((b) => [b.id, b.name ?? b.task]));\n for (const a of approvals) {\n process.stdout.write(`${a.id} [${nameBy.get(a.boxId) ?? a.boxId}] ${a.message}\\n`);\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst approvalsAnswerSub = new Command('answer')\n .description('Answer a pending approval on the control box')\n .argument('<id>', 'the approval id from `hub approvals list`')\n .argument('[answer]', 'y | n (default: y)', 'y')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .action(async (id: string, answer: string, opts: { url?: string }) => {\n try {\n if (answer !== 'y' && answer !== 'n') {\n log.error(`answer must be 'y' or 'n' (got '${answer}')`);\n process.exitCode = 1;\n return;\n }\n const client = await resolveHubApiClient(opts.url);\n if (!client) {\n process.exitCode = 1;\n return;\n }\n await client.answerApproval(id, answer);\n log.success(`Answered ${id} → ${answer}.`);\n } catch (err) {\n if (err instanceof HubApiError && err.code === 'not_found') {\n log.info(`No pending approval with id ${id} (already answered or expired?).`);\n process.exitCode = 1;\n return;\n }\n handleLifecycleError(err);\n }\n });\n\nconst approvalsCmd = new Command('approvals')\n .description('List + answer control-box host-action approvals from the PC')\n .addCommand(approvalsListSub)\n .addCommand(approvalsAnswerSub);\n\n// --- the hub's create queue (via `/api/v1/jobs`; a control box when configured,\n// else the local hub — one queue view, one route). ---\n\n/** `<id> <status> <provider> <name/box/error>` — one job per line. */\nfunction jobLine(job: HubApiJob): string {\n const label = job.name ?? '-';\n const boxOrError =\n job.error !== undefined\n ? ` ${job.error.split('\\n')[0]?.slice(0, 80) ?? ''}`\n : job.boxId\n ? ` box ${job.boxId}`\n : '';\n return `${job.id.slice(0, 12)} ${job.status.padEnd(7)} ${(job.provider ?? '-').padEnd(9)} ${label}${boxOrError}`;\n}\n\nconst jobsListSub = new Command('list')\n .description(\n 'List create jobs on the hub. With a control box configured this is its create queue ' +\n \"(where background `-i` cloud runs go); otherwise it is the local hub's queue.\",\n )\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--json', 'print raw JSON')\n .action(async (opts: { url?: string; json?: boolean }) => {\n await withHubClient({ url: opts.url }, async (client) => {\n const jobs = await client.listJobs();\n if (opts.json) {\n process.stdout.write(`${JSON.stringify({ jobs }, null, 2)}\\n`);\n return;\n }\n if (jobs.length === 0) {\n log.info('No create jobs on the hub.');\n return;\n }\n for (const job of jobs) process.stdout.write(`${jobLine(job)}\\n`);\n });\n });\n\nconst jobsShowSub = new Command('show')\n .description('Dump one hub create job')\n .argument('<jobId>', 'job id (or the short prefix `hub jobs list` prints)')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .action(async (jobId: string, opts: { url?: string }) => {\n await withHubClient({ url: opts.url }, async (client) => {\n // `jobs list` prints a 12-char prefix, so the id you copy may not be the full\n // id the by-id route wants. Try it verbatim first, then resolve as a prefix.\n let job = await client.getJob(jobId).catch((err) => {\n if (err instanceof HubApiError && err.code === 'not_found') return null;\n throw err;\n });\n if (!job) {\n const matches = (await client.listJobs()).filter((j) => j.id.startsWith(jobId));\n if (matches.length > 1) {\n log.error(\n `'${jobId}' matches ${String(matches.length)} jobs (${matches.map((m) => m.id.slice(0, 12)).join(', ')}) — pass more of the id.`,\n );\n process.exitCode = 1;\n return;\n }\n job = matches[0] ?? null;\n }\n if (!job) {\n log.info(`No job '${jobId}' on the hub.`);\n process.exitCode = 1;\n return;\n }\n process.stdout.write(`${JSON.stringify(job, null, 2)}\\n`);\n });\n });\n\nconst jobsCmd = new Command('jobs')\n .description(\"Inspect the hub's box-create queue\")\n .addCommand(jobsListSub)\n .addCommand(jobsShowSub);\n\ninterface DeployOpts {\n ref?: string;\n repo?: string;\n package?: string;\n domain?: string;\n}\n\n/**\n * Ensure `control-plane.env` carries a non-empty `AGENTBOX_HUB_API_KEY` (the\n * headless `/api/v1` bearer), minting + appending one if absent, and return it.\n * `setup` writes the key into a fresh env; this covers **redeploys** of a control\n * box whose env predates the key (or a hand-managed env), so every deploy — fresh\n * or repeat — ships a hub that accepts the headless key. Idempotent.\n */\nasync function ensureHubApiKeyInEnv(): Promise<string> {\n const body = await readFile(ENV_PATH, 'utf8');\n const existing = /^AGENTBOX_HUB_API_KEY=(.+)$/m.exec(body)?.[1]?.trim();\n if (existing) return existing;\n const key = randomBytes(32).toString('hex');\n const nl = body.length === 0 || body.endsWith('\\n') ? '' : '\\n';\n await writeFile(ENV_PATH, `${body}${nl}AGENTBOX_HUB_API_KEY=${key}\\n`, { mode: 0o600 });\n await chmod(ENV_PATH, 0o600);\n return key;\n}\n\n// Re-deploy the FULL hub to a fresh Hetzner VPS, REUSING the existing\n// ~/.agentbox/control-plane App creds + env — no GitHub-App manifest flow.\n// Installs the published package by default; --ref/--repo switch to a VPS-side\n// clone + build so a feature branch can be deployed for live verify.\n//\n// Note the deliberate absence of default values on --ref/--repo: an always-set\n// flag would pin EVERY deploy to source mode, which is exactly what the default\n// is meant to avoid.\nconst deployHetznerSub = new Command('hetzner')\n .description('Deploy the full hub to a new Hetzner VPS, reusing the App creds from `hub setup`')\n .option(\n '--ref <ref>',\n `build from source at this branch / tag / sha instead of installing the published package (${DEFAULT_DEPLOY_REF} matches this CLI)`,\n )\n .option(\n '--repo <url>',\n `git repo the VPS clones when building from source (default ${DEFAULT_DEPLOY_REPO})`,\n )\n .option(\n '--package <spec>',\n `npm spec of @madarco/agentbox to install (default ${AGENTBOX_VERSION}, this CLI's own version)`,\n )\n .option(\n '--domain <host>',\n 'serve on a hostname you control (point its DNS at the VPS first) instead of the default <ip>.sslip.io',\n )\n .action(async (opts: DeployOpts) => {\n // Tee the spinner's progress to ~/.agentbox/logs/hub-deploy.log — a deploy\n // that dies at `compose up` or on a 502 otherwise leaves nothing to read.\n const cmdLog = openCommandLog('hub-deploy');\n try {\n if (!existsSync(ENV_PATH)) {\n log.error(\n 'No control-plane env found. Run `agentbox hub setup` first (it creates the GitHub App + admin token).',\n );\n process.exitCode = 1;\n return;\n }\n if (!(await ensureHetznerHubAuth())) {\n log.warn('login prompt cancelled — deploying without web-UI auth.');\n }\n // Mint the headless /api/v1 bearer into the env if it isn't there yet, so a\n // redeploy of a pre-existing control box also gets it (setup writes it for\n // fresh installs). It rides the same scp'd .env into the container.\n await ensureHubApiKeyInEnv();\n const source = resolveHubDeploySource(AGENTBOX_VERSION, {\n ...(opts.ref ? { ref: opts.ref } : {}),\n ...(opts.repo ? { repoUrl: repoSlugToUrl(opts.repo) } : {}),\n ...(opts.package ? { packageSpec: opts.package } : {}),\n });\n if (source.kind === 'package' && source.spec !== AGENTBOX_VERSION) {\n log.warn(\n `deploying @madarco/agentbox@${source.spec}, which differs from this CLI (${AGENTBOX_VERSION}) — ` +\n 'the host and the control box will run different builds.',\n );\n }\n const ds = spinner();\n ds.start('deploying the control box to hetzner');\n cmdLog.write(`hub source: ${describeHubDeploySource(source)}`);\n let deployedUrl: string;\n let provisioned: ControlPlaneDeployRecord | null = null;\n try {\n deployedUrl = (\n await runHetznerDeploy({\n envPath: ENV_PATH,\n source,\n ...(opts.domain ? { domain: opts.domain } : {}),\n log: (line) => {\n ds.message(line);\n cmdLog.write(line);\n },\n onProvisioned: (info) => {\n provisioned = info;\n },\n })\n ).url;\n ds.stop(`deployed: ${deployedUrl}`);\n } catch (e) {\n ds.stop('deploy failed');\n const msg = e instanceof Error ? e.message : String(e);\n cmdLog.write(`deploy failed: ${msg}`);\n log.error(msg);\n if (provisioned) note(recoveryHint(provisioned).join('\\n'), 'Debug the VPS');\n log.info(`Full deploy log: ${cmdLog.path}`);\n process.exitCode = 1;\n return;\n }\n const url = await applyControlPlaneUrl(deployedUrl);\n log.success(`Pointed the CLI at ${url} (relay.controlPlaneUrl).`);\n const ok = await waitForHealthz(url, 60_000);\n log[ok ? 'success' : 'warn'](\n ok\n ? `Control box is healthy (${url}/healthz).`\n : `Could not confirm ${url}/healthz yet — check the deployment.`,\n );\n if (ok) await finalizeControlBoxState(url);\n log.info(`Reach the VPS with \\`ssh ${AGENTBOX_HUB_SSH_ALIAS}\\`. Deploy log: ${cmdLog.path}`);\n } catch (err) {\n cmdLog.write(`FAILED: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);\n handleLifecycleError(err);\n } finally {\n cmdLog.close();\n }\n });\n\ninterface DeployDigitalOceanOpts extends DeployOpts {\n region?: string;\n size?: string;\n}\n\n// The same full-hub docker-compose deploy as `hub deploy hetzner`, on a\n// DigitalOcean Droplet. Reuses the ~/.agentbox/control-plane env + auth from\n// `hub setup` — no GitHub-App manifest flow.\nconst deployDigitalOceanSub = new Command('digitalocean')\n .description(\n 'Deploy the full hub to a new DigitalOcean Droplet, reusing the creds from `hub setup`',\n )\n .option(\n '--ref <ref>',\n `build from source at this branch / tag / sha instead of installing the published package (${DEFAULT_DEPLOY_REF} matches this CLI)`,\n )\n .option(\n '--repo <url>',\n `git repo the Droplet clones when building from source (default ${DEFAULT_DEPLOY_REPO})`,\n )\n .option(\n '--package <spec>',\n `npm spec of @madarco/agentbox to install (default ${AGENTBOX_VERSION}, this CLI's own version)`,\n )\n .option(\n '--domain <host>',\n 'serve on a hostname you control (point its DNS at the Droplet first) instead of the default <ip>.sslip.io',\n )\n .option('--region <slug>', 'DigitalOcean region slug (default nyc3)')\n .option('--size <slug>', 'Droplet size slug (default s-2vcpu-4gb)')\n .action(async (opts: DeployDigitalOceanOpts) => {\n const cmdLog = openCommandLog('hub-deploy');\n try {\n if (!existsSync(ENV_PATH)) {\n log.error(\n 'No control-plane env found. Run `agentbox hub setup` first (it writes the git credential + admin token).',\n );\n process.exitCode = 1;\n return;\n }\n if (!(await ensureHetznerHubAuth())) {\n log.warn('login prompt cancelled — deploying without web-UI auth.');\n }\n await ensureHubApiKeyInEnv();\n const source = resolveHubDeploySource(AGENTBOX_VERSION, {\n ...(opts.ref ? { ref: opts.ref } : {}),\n ...(opts.repo ? { repoUrl: repoSlugToUrl(opts.repo) } : {}),\n ...(opts.package ? { packageSpec: opts.package } : {}),\n });\n if (source.kind === 'package' && source.spec !== AGENTBOX_VERSION) {\n log.warn(\n `deploying @madarco/agentbox@${source.spec}, which differs from this CLI (${AGENTBOX_VERSION}) — ` +\n 'the host and the control box will run different builds.',\n );\n }\n const ds = spinner();\n ds.start('deploying the control box to digitalocean');\n cmdLog.write(`hub source: ${describeHubDeploySource(source)}`);\n let deployedUrl: string;\n let provisioned: ControlPlaneDeployRecord | null = null;\n try {\n deployedUrl = (\n await runDigitalOceanDeploy({\n envPath: ENV_PATH,\n source,\n ...(opts.domain ? { domain: opts.domain } : {}),\n ...(opts.region ? { region: opts.region } : {}),\n ...(opts.size ? { size: opts.size } : {}),\n log: (line) => {\n ds.message(line);\n cmdLog.write(line);\n },\n onProvisioned: (info) => {\n provisioned = info;\n },\n })\n ).url;\n ds.stop(`deployed: ${deployedUrl}`);\n } catch (e) {\n ds.stop('deploy failed');\n const msg = e instanceof Error ? e.message : String(e);\n cmdLog.write(`deploy failed: ${msg}`);\n log.error(msg);\n if (provisioned) note(recoveryHintDigitalOcean(provisioned).join('\\n'), 'Debug the VPS');\n log.info(`Full deploy log: ${cmdLog.path}`);\n process.exitCode = 1;\n return;\n }\n const url = await applyControlPlaneUrl(deployedUrl);\n log.success(`Pointed the CLI at ${url} (relay.controlPlaneUrl).`);\n const ok = await waitForHealthz(url, 60_000);\n log[ok ? 'success' : 'warn'](\n ok\n ? `Control box is healthy (${url}/healthz).`\n : `Could not confirm ${url}/healthz yet — check the deployment.`,\n );\n if (ok) await finalizeControlBoxState(url);\n log.info(\n `Reach the Droplet with \\`ssh ${AGENTBOX_HUB_SSH_ALIAS}\\`. Deploy log: ${cmdLog.path}`,\n );\n } catch (err) {\n cmdLog.write(`FAILED: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);\n handleLifecycleError(err);\n } finally {\n cmdLog.close();\n }\n });\n\ninterface UpdateOpts {\n ref?: string;\n repo?: string;\n package?: string;\n channel?: string;\n yes?: boolean;\n}\n\n/**\n * Resolve `--channel` to a concrete published version, so the control box is\n * pinned to an exact build the way `hub deploy` pins it. Mirrors `self-update`:\n * the newest build on a channel can live under either dist-tag, so install the\n * resolved VERSION rather than the tag.\n */\nasync function specForChannel(channel: string): Promise<string> {\n if (channel !== 'nightly' && channel !== 'stable') {\n throw new Error(`unknown --channel \"${channel}\" (expected: nightly | stable)`);\n }\n const best = await fetchNpmBest(channel);\n if (!best) {\n throw new Error(`could not reach the npm registry to resolve the newest ${channel} build`);\n }\n return best;\n}\n\n/**\n * `hub update` for a LOCAL control box. Its \"build\" is this CLI's own hub\n * bundle, so an update restarts the exposed hub in place. Changing the machine's\n * AgentBox build is `agentbox self-update` — a whole-machine action, not this\n * command's job — so a spec flag here just points there.\n */\nasync function runLocalUpdateFlow(opts: UpdateOpts, logWrite: (l: string) => void): Promise<void> {\n if (opts.channel || opts.package || opts.ref || opts.repo) {\n log.warn(\n \"This control box IS this machine's hub, so its build is this CLI. To change the build, run \" +\n '`agentbox self-update` (it reloads the hub too); `hub update` just restarts the exposed hub.',\n );\n }\n const loopback = (await localExposedLoopbackUrl()) ?? `http://127.0.0.1:${String(relayPort())}`;\n const before = await probeControlPlaneStatus(loopback);\n log.info(`control box: this machine (${loopback}) — ${before.version ?? 'running'}`);\n if (!opts.yes) {\n const ok = await confirm({ message: 'Restart the exposed hub?', initialValue: true });\n if (isCancel(ok) || !ok) {\n log.info('cancelled');\n return;\n }\n }\n await ensureHubApiKeyInEnv();\n const s = spinner();\n s.start('restarting the exposed hub');\n try {\n await runLocalUpdate((l) => {\n s.message(l);\n logWrite(l);\n });\n s.stop('exposed hub restarted');\n } catch (e) {\n s.stop('restart failed', 1);\n log.error(e instanceof Error ? e.message : String(e));\n process.exitCode = 1;\n return;\n }\n const after = await probeControlPlaneStatus(loopback);\n log[after.healthy ? 'success' : 'warn'](\n after.healthy\n ? `Control box is healthy${after.version ? `, running ${after.version}` : ''}.`\n : `Hub did not answer just now (${after.detail}) — check with \\`agentbox hub status\\`.`,\n );\n await syncBakesWithControlBox(loopback);\n}\n\n/** `hub destroy` for a LOCAL control box: stop exposing, revert to the plain hub. */\nasync function runLocalDestroyFlow(\n record: ControlPlaneDeployRecord,\n opts: DestroyOpts,\n): Promise<void> {\n const loopback = `http://127.0.0.1:${String(record.port ?? relayPort())}`;\n // Registered cloud boxes outlive the hub and its store may be their only\n // record — the same hard gate as the VPS path, probed over loopback.\n const boxes = await listHubBoxesForDestroy({ ...record, url: loopback });\n const gate = destroyGate(boxes, Boolean(opts.force));\n if (!gate.allowed) {\n log.error(\n `The control box still has ${String(gate.orphanCount)} box(es) registered. Stopping it now would orphan them:`,\n );\n for (const b of gate.orphans) {\n process.stdout.write(` ${b.id} ${b.name ?? ''} ${b.provider ?? ''} ${b.state ?? ''}\\n`);\n }\n log.info('Destroy them first (`agentbox hub boxes rm <id>`), or re-run with --force.');\n process.exitCode = 1;\n return;\n }\n const lines = [\n 'stop exposing (the plain localhost hub returns on the next `agentbox hub start`)',\n 'the tunnel + autostart unit, if any',\n opts.keepCredentials\n ? `${CP_DIR}/deploy.json (control-plane.env kept — 'hub expose' again needs no setup)`\n : `${CP_DIR} (credentials + deploy record)`,\n 'relay.controlPlaneUrl (global + project)',\n 'The shared ~/.agentbox (store.db / custody / boxes) is kept.',\n ];\n if (gate.note) lines.push(`NOTE: ${gate.note}`);\n note(lines.join('\\n'), 'This will');\n if (!opts.yes) {\n const ok = await confirm({ message: 'Stop being the control box?', initialValue: false });\n if (isCancel(ok) || !ok) {\n log.info('cancelled');\n return;\n }\n }\n await runLocalDestroy({\n keepCredentials: Boolean(opts.keepCredentials),\n log: (l) => log.info(l),\n });\n log.success(\n 'This machine is no longer the control box — the plain localhost hub is back on the next `agentbox hub start`.',\n );\n if (opts.keepCredentials) {\n log.info(\n `Credentials kept in ${CP_DIR} — \\`agentbox hub expose\\` re-exposes without \\`hub setup\\`.`,\n );\n }\n}\n\nconst updateSub = new Command('update')\n .description('Update the deployed control box in place to a new AgentBox build')\n .option('--channel <nightly|stable>', 'install the newest published build on this channel')\n .option(\n '--package <spec>',\n `npm spec to install (default ${AGENTBOX_VERSION}, this CLI's own version)`,\n )\n .option('--ref <ref>', 'switch the control box to building from source at this git ref')\n .option('--repo <url>', 'git repo the VPS clones when building from source')\n .option('-y, --yes', 'skip the confirmation prompt')\n .action(async (opts: UpdateOpts) => {\n const cmdLog = openCommandLog('hub-update');\n try {\n if (!existsSync(ENV_PATH)) {\n log.error('No control-plane env found. Run `agentbox hub setup` first.');\n process.exitCode = 1;\n return;\n }\n const record = await readDeployRecord();\n\n // A local control box IS this machine's hub — its \"build\" is this CLI, so\n // an update restarts the exposed hub in place. Changing the CLI build is a\n // separate whole-machine action (`agentbox self-update`).\n if (record?.provider === 'local') {\n await runLocalUpdateFlow(opts, cmdLog.write.bind(cmdLog));\n return;\n }\n\n assertReachableRecord(record);\n\n const source = opts.channel\n ? ({ kind: 'package', spec: await specForChannel(opts.channel) } as const)\n : resolveHubDeploySource(AGENTBOX_VERSION, {\n ...(opts.ref ? { ref: opts.ref } : {}),\n ...(opts.repo ? { repoUrl: repoSlugToUrl(opts.repo) } : {}),\n ...(opts.package ? { packageSpec: opts.package } : {}),\n });\n\n // What it runs NOW comes from the live hub when it can answer — the record\n // only says what was last *deployed*, which is wrong if a previous update\n // failed halfway.\n const live = await probeControlPlaneStatus(record.url);\n const from = live.version ?? describeRecordedSource(record) ?? 'unknown';\n log.info(`control box: ${record.url} (server ${String(record.serverId ?? '?')})`);\n log.info(` ${from} → ${describeHubDeploySource(source)}`);\n if (!live.healthy) {\n log.warn('The hub is not answering right now — updating anyway will also restart it.');\n }\n if (!opts.yes) {\n const ok = await confirm({ message: 'Update the control box?', initialValue: true });\n if (isCancel(ok) || !ok) {\n log.info('cancelled');\n return;\n }\n }\n\n // Pick up keys added by CLI versions newer than the one that deployed this\n // box (the same gap `hub deploy hetzner` covers for a redeploy).\n await ensureHubApiKeyInEnv();\n\n const isDigitalOcean = record.provider === 'digitalocean';\n const runVpsUpdate = isDigitalOcean ? runDigitalOceanUpdate : runHetznerUpdate;\n const updateHint = isDigitalOcean ? recoveryHintDigitalOcean : recoveryHint;\n const ds = spinner();\n ds.start(`updating the control box${isDigitalOcean ? ' (digitalocean)' : ''}`);\n cmdLog.write(`hub update: ${from} -> ${describeHubDeploySource(source)}`);\n try {\n await runVpsUpdate({\n envPath: ENV_PATH,\n source,\n log: (line) => {\n ds.message(line);\n cmdLog.write(line);\n },\n });\n ds.stop(`updated: ${record.url}`);\n } catch (e) {\n ds.stop('update failed');\n const msg = e instanceof Error ? e.message : String(e);\n cmdLog.write(`update failed: ${msg}`);\n log.error(msg);\n note(updateHint(record).join('\\n'), 'Debug the VPS');\n log.info(`Full update log: ${cmdLog.path}`);\n process.exitCode = 1;\n return;\n }\n // Report what the probe actually found. The update already waited for a\n // healthy hub, so a failing probe here is usually transient — but claiming\n // health from a probe that failed is exactly the false success this whole\n // command was just taught to avoid.\n const after = await probeControlPlaneStatus(record.url);\n if (!after.healthy) {\n log.warn(\n `Update applied, but ${record.url}/healthz did not answer just now (${after.detail}). Re-check with \\`agentbox hub status\\`.`,\n );\n } else {\n log.success(\n after.version\n ? `Control box is healthy, running ${after.version}.`\n : `Control box is healthy (${record.url}/healthz).`,\n );\n }\n // Re-assert everything a fresh setup would have put in place. A version\n // change is exactly when a shared bake record starts (or stops) matching\n // the control box's fingerprint — and an update is also how a box deployed\n // by an older AgentBox first learns about its own docker engine, so the PC\n // side (the `hub` host alias + the `docker:hub` default) has to be brought\n // up with it. All of it is idempotent and best-effort.\n await finalizeControlBoxState(record.url);\n } catch (err) {\n cmdLog.write(`FAILED: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);\n handleLifecycleError(err);\n } finally {\n cmdLog.close();\n }\n });\n\n/** The build `deploy.json` last recorded, as one line. */\nfunction describeRecordedSource(record: ControlPlaneDeployRecord): string | null {\n if (!record.source) return null;\n return record.source.kind === 'package'\n ? `@madarco/agentbox@${record.source.spec}`\n : `${record.source.repoUrl}@${record.source.repoRef}`;\n}\n\ninterface DestroyOpts {\n yes?: boolean;\n force?: boolean;\n keepCredentials?: boolean;\n}\n\n/**\n * `hub unexpose` — the friendly name for tearing down a LOCAL control box.\n *\n * It is the same flow as `hub destroy`, which is deliberate: there is one\n * teardown, not two. But \"destroy\" reads as data loss when the control box is\n * your own laptop, where the honest description is \"stop exposing\" — nothing is\n * deleted except the exposed mode itself (the shared `~/.agentbox` stays).\n */\nconst unexposeSub = new Command('unexpose')\n .description('Stop this machine being the control box (the plain localhost hub returns)')\n .option('-y, --yes', 'skip the confirmation prompt')\n .option('--force', 'stop even while the hub still has boxes registered')\n .option('--keep-credentials', 'keep control-plane.env so `hub expose` needs no setup again')\n .action(async (opts: DestroyOpts) => {\n try {\n const record = await readDeployRecord();\n if (record?.provider !== 'local') {\n log.error(\n record\n ? 'This machine is not the control box — the configured one is a deployed VPS. Use `agentbox hub destroy` to tear that down.'\n : 'This machine is not exposed as a control box (nothing to undo).',\n );\n process.exitCode = 1;\n return;\n }\n await runLocalDestroyFlow(record, opts);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst destroySub = new Command('destroy')\n .description(\n \"Tear down the control box: a deployed VPS + its firewall, or this machine's exposed hub, plus the local state\",\n )\n .option('-y, --yes', 'skip the confirmation prompt')\n .option('--force', 'destroy even while the hub still has boxes registered')\n .option('--keep-credentials', 'keep control-plane.env so a redeploy needs no `hub setup`')\n .action(async (opts: DestroyOpts) => {\n try {\n const record = await readDeployRecord();\n if (!record) {\n log.error(\n 'No control box was deployed from this machine (~/.agentbox/control-plane/deploy.json is missing).',\n );\n log.info(\n 'To stop using a hub configured with `hub set-url`, run `agentbox hub unset-url`.',\n );\n process.exitCode = 1;\n return;\n }\n\n if (record.provider === 'local') {\n await runLocalDestroyFlow(record, opts);\n return;\n }\n\n // Cloud boxes the hub created outlive it, and its store is often the only\n // record they exist — so enumerate before destroying it, not after.\n const boxes = await listHubBoxesForDestroy(record);\n const gate = destroyGate(boxes, Boolean(opts.force));\n if (!gate.allowed) {\n log.error(\n `The control box still has ${String(gate.orphanCount)} box(es) registered. Destroying it now would orphan them:`,\n );\n for (const b of gate.orphans) {\n process.stdout.write(\n ` ${b.id} ${b.name ?? ''} ${b.provider ?? ''} ${b.state ?? ''}\\n`,\n );\n }\n log.info('Destroy them first (`agentbox hub boxes rm <id>`), or re-run with --force.');\n process.exitCode = 1;\n return;\n }\n\n const isDigitalOcean = record.provider === 'digitalocean';\n const cloudLabel = isDigitalOcean ? 'DigitalOcean' : 'Hetzner';\n const serverKind = isDigitalOcean ? 'droplet' : 'server';\n const lines = [\n `${cloudLabel} ${serverKind} ${String(record.serverId ?? '?')} (${record.ip ?? '?'})`,\n ...(record.firewallId !== undefined\n ? [`${cloudLabel} firewall ${String(record.firewallId)}`]\n : []),\n opts.keepCredentials\n ? `${CP_DIR}/deploy.json + ssh/ (control-plane.env kept)`\n : `${CP_DIR} (credentials, ssh key, deploy record)`,\n `the \\`${AGENTBOX_HUB_SSH_ALIAS}\\` SSH alias`,\n 'relay.controlPlaneUrl (global + project)',\n ];\n if (gate.note) lines.push(`NOTE: ${gate.note}`);\n note(lines.join('\\n'), 'This will delete');\n\n if (!opts.yes) {\n const ok = await confirm({ message: 'Destroy the control box?', initialValue: false });\n if (isCancel(ok) || !ok) {\n log.info('cancelled');\n return;\n }\n }\n\n const result = isDigitalOcean\n ? await runDigitalOceanDestroy({ record, log: (l) => log.info(l) })\n : await runHetznerDestroy({ record, log: (l) => log.info(l) });\n for (const w of result.warnings) log.warn(w);\n // Purge regardless: a server that was already deleted by hand must not\n // leave this machine pointing at it with no way to clear the state.\n await purgeLocalControlPlaneState({\n dir: CP_DIR,\n keepCredentials: Boolean(opts.keepCredentials),\n });\n await unsetConfigValue('global', 'relay.controlPlaneUrl', process.cwd());\n await unsetConfigValue('project', 'relay.controlPlaneUrl', process.cwd());\n\n log.success('Control box destroyed. Cloud boxes now build on this machine again.');\n if (opts.keepCredentials) {\n log.info(\n `Credentials kept in ${CP_DIR} — \\`agentbox hub deploy ${isDigitalOcean ? 'digitalocean' : 'hetzner'}\\` redeploys without \\`hub setup\\`.`,\n );\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\n/** Boxes the hub still owns, or why we couldn't ask. */\nexport type HubBoxesProbe =\n | { kind: 'boxes'; rows: Array<{ id: string; name?: string; provider?: string; state?: string }> }\n | { kind: 'unreachable'; reason: string };\n\n/**\n * Whether `hub destroy` may proceed.\n *\n * Cloud boxes the control box created keep running in their provider, and the\n * hub's store is often the only record they exist — so a non-empty list is a\n * hard stop rather than a warning. An **unreachable** hub is not: a deploy that\n * never came up is the single most common thing people want to delete, and\n * refusing there would leave no way to clean up at all.\n *\n * Pure so the gate is testable without a live hub.\n */\nexport function destroyGate(\n probe: HubBoxesProbe,\n force: boolean,\n): {\n allowed: boolean;\n orphanCount: number;\n note: string | null;\n orphans: Array<{ id: string; name?: string; provider?: string; state?: string }>;\n} {\n if (probe.kind === 'unreachable') {\n return {\n allowed: true,\n orphanCount: 0,\n orphans: [],\n note: `the hub did not answer, so its boxes could not be listed (${probe.reason})`,\n };\n }\n // Only boxes that would actually be stranded count. A local `docker` box runs\n // on this machine against the host's own `.git` and is never handed to the\n // control box, so losing the hub does not orphan it — gating on it made an\n // exposed hub refuse to stand down because of a container sitting next to it.\n // `remote-docker` is NOT exempt: that one lives on another machine.\n const orphans = probe.rows.filter((b) => b.provider !== 'docker');\n const orphanCount = orphans.length;\n if (orphanCount === 0) return { allowed: true, orphanCount: 0, orphans: [], note: null };\n if (!force) return { allowed: false, orphanCount, orphans, note: null };\n return {\n allowed: true,\n orphanCount,\n orphans,\n note: `--force — ${String(orphanCount)} registered box(es) will be orphaned`,\n };\n}\n\nasync function listHubBoxesForDestroy(record: ControlPlaneDeployRecord): Promise<HubBoxesProbe> {\n if (!record.url) return { kind: 'unreachable', reason: 'no url in the deploy record' };\n try {\n // Pin to the record's URL rather than the configured one: destroy must ask\n // the box it is about to delete, even if `relay.controlPlaneUrl` has since\n // been pointed somewhere else.\n const client = await resolveHubApiClient(record.url, { quiet: true });\n if (!client) return { kind: 'unreachable', reason: 'no /api/v1 key configured for this hub' };\n return { kind: 'boxes', rows: await client.listBoxes() };\n } catch (e) {\n return { kind: 'unreachable', reason: e instanceof Error ? e.message : String(e) };\n }\n}\n\n/**\n * This CLI's live native fingerprint for a provider's base build context, or\n * undefined when it can't be computed (a dev tree with no staged runtime, or a\n * provider that doesn't fingerprint). Loads the module WITHOUT its credential\n * gate — `baseFingerprint` only hashes the staged runtime files, no SDK/network.\n */\nasync function cliNativeFingerprint(provider: string): Promise<string | undefined> {\n try {\n return await (await loadProviderModule(provider)).provider.baseFingerprint?.('native');\n } catch {\n return undefined;\n }\n}\n\n/**\n * Reconcile this machine's cloud bake records with a control box's, in BOTH\n * directions, so whichever side already baked this build context settles it.\n *\n * Per provider:\n * - our record matches this CLI's build context → **push** it, so the box's\n * first web-UI create boots it instead of spending minutes re-baking.\n * - it doesn't → **pull** first. A CLI update moves the build context, which\n * staled every local cloud base at once; when the box already holds one for\n * the new context, adopting it costs a GET instead of a multi-minute bake.\n * Sharing used to be push-only, so this case only ever produced a nag.\n * - neither side has one → say so, once, per provider.\n *\n * The push always succeeds if the box is reachable, but the box only ADOPTS a\n * record whose build-context fingerprint matches its own — so a record from a\n * different build context (an older local bake, or a hub on a different version)\n * is uploaded and then ignored, and the hub re-bakes. `classifyBakeShare`\n * predicts that here so setup ends with an explicit per-provider message rather\n * than a silent \"shared it\" that isn't the whole truth.\n *\n * Best-effort: a fresh deploy is still perfectly usable without any of this (it\n * just bakes on demand).\n */\nasync function syncBakesWithControlBox(url: string | undefined): Promise<void> {\n const target = await resolveCustodyTarget(url, { quiet: true });\n if (!target) return;\n // The version the box actually runs decides whether its fingerprint matches\n // ours; a box that doesn't report one leaves the version-skew check inert.\n const hubVersion = (await probeControlPlaneStatus(target.url)).version;\n const results: BakeShareResult[] = [];\n // Derive the provider set from the live runtime registry (built-ins AND\n // registered plugins) filtered by the single shareable rule — never a\n // hardcoded list, or a new provider is silently skipped from bake sharing.\n const providers = getRuntimeProviderNames().filter(isShareablePreparedProvider);\n // The pull direction first, in one sweep: it skips any provider whose local\n // record is already current, so it only ever touches the ones a push couldn't\n // help with anyway. Imported lazily — `prepared-custody` reaches back here for\n // `resolveCustodyTarget`, and a static edge both ways is a module cycle.\n const { adoptPreparedBases } = await import('../control-plane/prepared-custody.js');\n const pulled = await adoptPreparedBases().catch(() => ({\n adopted: [] as string[],\n pending: [] as string[],\n }));\n for (const provider of providers) {\n const adopted = pulled.adopted.includes(provider);\n // Read AFTER the sweep — an adopted record is the current local one.\n const local = readPreparedStateRaw(provider) as { base?: { contextSha256?: string } } | null;\n const storedFingerprint = local?.base?.contextSha256;\n const liveFingerprint = await cliNativeFingerprint(provider);\n if (!adopted && !storedFingerprint) continue; // nothing here, nothing there\n // Capture the real upload outcome — a swallowed failure must not be reported\n // as a share (the record never left this machine, so the hub will re-bake).\n const pushSucceeded =\n !adopted && storedFingerprint\n ? await pushPreparedToCustody(provider, {\n controlPlaneUrl: target.url,\n adminToken: target.adminToken,\n }).catch(() => false)\n : false;\n results.push(\n classifyBakeShare({\n provider,\n storedFingerprint,\n cliNativeFingerprint: liveFingerprint,\n hubVersion,\n cliVersion: AGENTBOX_VERSION,\n pushSucceeded,\n adopted,\n }),\n );\n }\n const { matched, adopted, mismatched, shareFailed } = summarizeBakeShare(results);\n if (matched.length > 0) {\n log.success(\n `Shared your ${matched.join(', ')} base bake(s) with the control box — it won't re-bake them.`,\n );\n }\n if (adopted.length > 0) {\n log.success(\n `Adopted the control box's ${adopted.join(', ')} base bake(s) — no re-bake needed here.`,\n );\n }\n const rebakeNote = buildRebakeNote(mismatched);\n if (rebakeNote) log.warn(rebakeNote);\n const failedNote = buildShareFailedNote(shareFailed);\n if (failedNote) log.warn(failedNote);\n}\n\n/** Bound on a credential-sync round-trip once the control box is known to be up. */\nconst CREDENTIAL_SYNC_FETCH_MS = 15_000;\n\n/**\n * Push host agent-credential backups (claude/codex/opencode) to the control box,\n * hash-skipping unchanged blobs — the same work `hub credentials push` does, so\n * a hub-created box is never launched loginless.\n *\n * `announce` picks the failure policy:\n * - `true` (end of `hub setup`/`deploy`): report what went up; on failure WARN\n * and name the manual command — never throw, so it can't fail the setup.\n * - `false` (change-detected re-push): silent when nothing changed, and every\n * error is swallowed — a stale-cred refresh must never break the command\n * that triggered it.\n *\n * Returns the number of credential sets uploaded (0 when unchanged / no box).\n */\nasync function syncAgentCredentials(\n url: string | undefined,\n opts: { announce: boolean },\n): Promise<number> {\n try {\n const target = await resolveCustodyApiTarget(url, { quiet: true, remoteOnly: true });\n if (!target) {\n if (opts.announce) {\n log.warn(\n 'No control box reachable, so agent credentials were not pushed. Run `agentbox hub credentials push` once it is up.',\n );\n }\n return 0;\n }\n // A down box must not park the sync on undici's ~10s connect timeout: probe\n // first, then bound every custody call.\n if (!(await hostReachable(target.url))) {\n if (opts.announce) {\n log.warn(\n `Control box unreachable at ${target.url}, so agent credentials were not pushed. Run \\`agentbox hub credentials push\\` once it is up.`,\n );\n }\n return 0;\n }\n const items = await collectAgentCredentialUploads();\n if (items.length === 0) {\n if (opts.announce) {\n log.info(\n 'No host agent logins to push yet — sign in with `agentbox claude login`, then `agentbox hub credentials push`.',\n );\n }\n return 0;\n }\n const client = new CustodyClient({\n ...target,\n fetchImpl: deadlineFetch(AbortSignal.timeout(CREDENTIAL_SYNC_FETCH_MS)),\n });\n const plan = planPush(items, await client.list('agents'), {});\n if (!hasCredentialChanges(plan)) {\n if (opts.announce) log.info('Agent logins already up to date on the control box.');\n return 0;\n }\n const uploaded = new Set<string>();\n for (const item of items) {\n if (plan.find((d) => d.path === item.path)?.action !== 'upload') continue;\n await client.put(item.path, item.data);\n // `agents/<id>/<file>` → the agent id.\n uploaded.add(item.path.split('/')[1] ?? item.path);\n }\n if (opts.announce && uploaded.size > 0) {\n log.success(`Pushed ${[...uploaded].join(', ')} login(s) to the control box.`);\n }\n return uploaded.size;\n } catch (err) {\n if (opts.announce) {\n log.warn(\n `Could not push agent credentials to the control box (${err instanceof Error ? err.message : String(err)}). ` +\n 'Run `agentbox hub credentials push` manually.',\n );\n }\n return 0;\n }\n}\n\n/**\n * Best-effort, silent-when-unchanged credential re-push, for the points where a\n * stale login on the control box actually bites: a cloud create routed to the\n * hub, and a fresh `agentbox claude login`. Cheap (hash compare, skips when the\n * host backup hasn't changed) and never throws — a no-op when no control box is\n * configured. Reuses the existing custody client + relay, no new channel.\n */\nexport async function syncAgentCredentialsIfChanged(url?: string): Promise<void> {\n await syncAgentCredentials(url, { announce: false });\n}\n\n/**\n * The end-of-setup/deploy step for a control box that just came up: get its\n * agent logins, bake records and shared docker hosts in place so its first\n * hub-created box is signed in and boots a baked base rather than re-baking. Both steps are best-effort\n * and self-reporting; neither fails the setup. `url` is undefined for a local\n * exposed hub (resolved to loopback by the custody target).\n */\nasync function finalizeControlBoxState(url: string | undefined): Promise<void> {\n await syncAgentCredentials(url, { announce: true });\n await syncBakesWithControlBox(url);\n // Re-register any remote-docker host this machine has shared before. A fresh\n // control box knows none of them, and the user should not have to remember\n // which engines they had handed over.\n const { syncSharedHosts } = await import('../control-plane/remote-docker-share.js');\n await syncSharedHosts(url, (line) => {\n log.info(line);\n });\n // The control box's own engine: register it here as `hub` and, if this machine\n // was still defaulting to plain docker (which a control box turns off), make it\n // the default. Best-effort — a hub that came up is not undone by this failing.\n try {\n const { ensureHubDockerTarget } = await import('../control-plane/hub-docker-target.js');\n await ensureHubDockerTarget((line) => {\n log.info(line);\n });\n } catch (err) {\n log.warn(\n `could not set up the control box's docker engine as a target: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\nconst deployCmd = new Command('deploy')\n .description('Deploy the full hub to a VPS, reusing the App creds from `hub setup`')\n .addCommand(deployHetznerSub)\n .addCommand(deployDigitalOceanSub);\n\n/**\n * The remote-hub admin subcommands, folded into the one `hub` command group\n * (`apps/cli/src/commands/hub.ts`). AgentBox is unreleased, so there is no\n * standalone `control-plane` group anymore — `hub setup`/`hub deploy`/`hub boxes`\n * etc. are the single surface. `status` is not here: it merged into `hub status`\n * (local process vs remote reachability, resolved by target).\n */\nexport const controlPlaneSubcommands = [\n setupSub,\n exposeSub,\n deployCmd,\n updateSub,\n destroySub,\n unexposeSub,\n setUrlSub,\n unsetUrlSub,\n addSub,\n workerSub,\n credentialsCmd,\n secretsCmd,\n projectCmd,\n custodyCmd,\n boxesCmd,\n approvalsCmd,\n jobsCmd,\n] as const;\n","/**\n * Pure logic for sharing this machine's bake records with the control box and\n * predicting whether the control box will actually ACCEPT them.\n *\n * The control box adopts a shared `prepared/<provider>.json` only when its\n * `base.contextSha256` equals the fingerprint the hub computes for the same\n * provider (`hydratePreparedFromCustody` → `matchClaudeInstallFingerprint`). A\n * push always succeeds if the box is reachable, so a plain \"shared it\" is not\n * the whole truth: a record from a different build context is uploaded and then\n * silently ignored, and the hub re-bakes. Callers need to say so.\n *\n * Two things break the match, both knowable here without a hub round-trip — a\n * local record stale vs THIS CLI's build context, and a deployed hub running a\n * different AgentBox version. This module classifies each, so setup/deploy can\n * end with an explicit per-provider \"will need baking again\" message.\n *\n * Everything here is pure (fingerprints/versions in, verdict out) so it is unit\n * testable without a hub or the filesystem.\n */\nimport { matchClaudeInstallFingerprint } from '@agentbox/sandbox-core';\nimport type { PushDecision } from './custody-client.js';\n\n/**\n * The ONE rule for \"does this provider bake a base worth sharing?\" — derive the\n * provider set from it (enumerate the runtime providers and filter), never a\n * hardcoded list, or a new built-in / community-plugin provider is silently\n * skipped from bake sharing.\n *\n * A cloud provider's base is an id-addressed snapshot any machine with the API\n * key can boot, so it is worth sharing. `docker` is not: its base is a local\n * image rebuilt (or pulled) per machine. `remote-docker` is the non-obvious\n * case — despite living on another host, its base is still a local docker image\n * built on that host, not a portable snapshot, so it is docker-shaped and\n * excluded the same way.\n */\nexport function isShareablePreparedProvider(provider: string): boolean {\n return provider !== 'docker' && provider !== 'remote-docker';\n}\n\n/**\n * Whether what this machine already has rules out adopting the control box's\n * bake: only a record that matches OUR live build context does.\n *\n * The rule used to be \"any local record at all\", which inverted the intent — the\n * machine that most needs the shared base, one holding an outdated record, was\n * the only one that could never take it, and re-baked for minutes instead. A\n * record from a different context is precisely what adoption is for. (Adopting\n * something *worse* isn't a risk: the pull only writes when custody's\n * fingerprint equals ours.)\n *\n * `nativeFingerprint` is the raw context hash, and the match is fold-tolerant —\n * the SAME rule the pull and the hub's hydration apply. A strict compare here\n * would call an `box.claudeInstall=npm` machine's perfectly current base a\n * miss (it stores the folded hash), so a `prepare` that found nothing in\n * custody would re-bake a base it already had, every time.\n */\nexport function localBakeBlocksAdoption(\n local: { base?: { contextSha256?: string } } | null,\n nativeFingerprint: string,\n): boolean {\n const stored = local?.base?.contextSha256;\n return !!stored && matchClaudeInstallFingerprint(stored, nativeFingerprint) !== null;\n}\n\n/**\n * The change-detection predicate for the credential re-push: true when at least\n * one item is due for upload (its hash differs from custody), false when every\n * item is a hash-skip. Callers use it to stay silent when nothing changed.\n */\nexport function hasCredentialChanges(plan: PushDecision[]): boolean {\n return plan.some((d) => d.action === 'upload');\n}\n\nexport interface BakeShareInput {\n provider: string;\n /** The local record's `base.contextSha256`, or undefined when nothing is baked here. */\n storedFingerprint: string | undefined;\n /**\n * This CLI's live native fingerprint for the same provider, or undefined when\n * it can't be computed (a dev tree with no staged runtime). Undefined disables\n * the local-staleness check — an unverifiable base must not be flagged.\n */\n cliNativeFingerprint: string | undefined;\n /** The version the deployed hub reports (`/healthz`), or undefined when it doesn't. */\n hubVersion: string | undefined;\n /** This CLI's own version. */\n cliVersion: string;\n /**\n * Whether the record's upload to custody actually succeeded. When false the\n * record never left this machine, so no verdict about the hub's fingerprint\n * applies — the outcome is `share-failed`, never a false `match`.\n */\n pushSucceeded: boolean;\n /**\n * Whether the OTHER direction already settled this provider: the control box\n * held a record for our build context and we took it. Nothing about our own\n * (by definition stale) record matters then, so it wins over every verdict\n * below — including the \"re-bake this\" warning it exists to silence.\n */\n adopted?: boolean;\n}\n\nexport type BakeShareStatus =\n /** Nothing baked locally — nothing to share. */\n | 'not-baked'\n /** The upload to custody failed, so nothing was shared (the hub will re-bake). */\n | 'share-failed'\n /** Shared; the hub's fingerprint will match, so its first create boots the base. */\n | 'match'\n /** Shared; the hub computes a different fingerprint, so it will re-bake. */\n | 'mismatch'\n /** The other direction: the hub's record matched OUR context, so we took it. */\n | 'adopted';\n\nexport interface BakeShareResult {\n provider: string;\n status: BakeShareStatus;\n /** Present for `mismatch` / `share-failed`: why the hub won't boot the record. */\n reason?: string;\n}\n\n/**\n * Predict whether the control box will boot this machine's bake record for\n * `provider`.\n *\n * - Adoption settles it: when the pull already took the hub's record for our\n * build context, our own record is stale by definition and there is nothing\n * to warn about.\n * - The upload has to have actually succeeded; a swallowed push failure must\n * never be reported as a share (that is the false \"Shared it\" bug).\n * - A local record whose fingerprint matches neither install-mode fold of THIS\n * CLI's build context is stale here too: no same-version hub would take it.\n * - A hub on a different version has a different build context, so the record —\n * even one perfectly current for this CLI — won't match on the far side.\n */\nexport function classifyBakeShare(input: BakeShareInput): BakeShareResult {\n const { provider, storedFingerprint, cliNativeFingerprint, hubVersion, cliVersion } = input;\n if (input.adopted) return { provider, status: 'adopted' };\n if (!storedFingerprint) return { provider, status: 'not-baked' };\n if (!input.pushSucceeded) {\n return {\n provider,\n status: 'share-failed',\n reason: `could not upload the ${provider} bake record to the control box`,\n };\n }\n if (\n cliNativeFingerprint &&\n !matchClaudeInstallFingerprint(storedFingerprint, cliNativeFingerprint)\n ) {\n return {\n provider,\n status: 'mismatch',\n reason: `neither side has a ${provider} base for this build context — \\`agentbox prepare --provider ${provider}\\` bakes one on the control box`,\n };\n }\n if (hubVersion && hubVersion !== cliVersion) {\n return {\n provider,\n status: 'mismatch',\n reason: `the hub runs ${hubVersion} but this CLI is ${cliVersion}, so its build context differs`,\n };\n }\n return { provider, status: 'match' };\n}\n\nexport interface BakeShareSummary {\n /** Providers whose record the hub will boot from (status `match`). */\n matched: string[];\n /** Providers we took the hub's record for instead (status `adopted`). */\n adopted: string[];\n /** Providers shared but that the hub will re-bake (status `mismatch`). */\n mismatched: BakeShareResult[];\n /** Providers whose upload failed, so nothing was shared (status `share-failed`). */\n shareFailed: BakeShareResult[];\n}\n\nexport function summarizeBakeShare(results: BakeShareResult[]): BakeShareSummary {\n return {\n matched: results.filter((r) => r.status === 'match').map((r) => r.provider),\n adopted: results.filter((r) => r.status === 'adopted').map((r) => r.provider),\n mismatched: results.filter((r) => r.status === 'mismatch'),\n shareFailed: results.filter((r) => r.status === 'share-failed'),\n };\n}\n\n/**\n * The end-of-setup message for providers the hub will have to bake again, or\n * null when there is nothing to warn about. Per-provider and explicit: staying\n * silent here is the bug this reports against.\n */\nexport function buildRebakeNote(mismatched: BakeShareResult[]): string | null {\n if (mismatched.length === 0) return null;\n const lines = mismatched.map(\n (m) => ` - ${m.provider}: ${m.reason ?? 'the build context differs'}`,\n );\n return (\n 'These providers are configured, but the hub will need to bake them again before its first box:\\n' +\n lines.join('\\n')\n );\n}\n\n/**\n * The message for bakes whose upload failed (e.g. the box was unreachable) — a\n * distinct outcome from `mismatch`: there the record reached the hub and was\n * rejected on its fingerprint; here it never arrived. Returns null when nothing\n * failed. Sharing stays best-effort, so this warns rather than failing setup.\n */\nexport function buildShareFailedNote(shareFailed: BakeShareResult[]): string | null {\n if (shareFailed.length === 0) return null;\n const names = shareFailed.map((r) => r.provider);\n return (\n 'Could not share these base bake records with the control box, so the hub will re-bake them on ' +\n `first use: ${names.join(', ')}.\\n` +\n 'Re-run `agentbox hub setup` (or `agentbox prepare --provider <name>`) once it is reachable to share them.'\n );\n}\n","import { createServer } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { randomBytes } from 'node:crypto';\n\n/**\n * GitHub App **manifest flow** — create a GitHub App from a manifest without\n * hand-filling the web form. We serve a one-shot local page that auto-POSTs the\n * manifest to GitHub; the user reviews + clicks \"Create\"; GitHub redirects back\n * to our localhost callback with a `code`; we exchange it for the App's id +\n * private key. See https://docs.github.com/apps/sharing-github-apps/registering-a-github-app-from-a-manifest\n *\n * The GitHub base URLs and the browser-open are injectable so this is e2e\n * testable against a fake GitHub (and so it works against GitHub Enterprise).\n */\nexport interface ManifestFlowOptions {\n /** Desired App name (must be globally unique on GitHub). */\n appName: string;\n /** Create under an org instead of the user account. */\n org?: string;\n /** Public-facing URL recorded on the App. */\n homepageUrl?: string;\n /** github.com base (override for GHES / tests). Default https://github.com. */\n githubUrl?: string;\n /** api.github.com base (override for GHES / tests). Default https://api.github.com. */\n apiBaseUrl?: string;\n /** Opens the URL in the user's browser. Injected in tests. */\n openBrowser: (url: string) => void | Promise<void>;\n /** How long to wait for the user to complete the flow. Default 5 min. */\n timeoutMs?: number;\n log?: (line: string) => void;\n fetchImpl?: typeof fetch;\n}\n\nexport interface ManifestFlowResult {\n appId: string;\n slug: string;\n /** PEM private key (store 0600). */\n pem: string;\n /** The App's html_url, e.g. https://github.com/apps/<slug>. */\n htmlUrl: string;\n /** Where to install it: https://github.com/apps/<slug>/installations/new. */\n installUrl: string;\n}\n\nfunction htmlEscape(s: string): string {\n return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}\n\n/**\n * Wrap page content in a small self-contained styled shell — system font,\n * centered card, light/dark aware, AgentBox accent green. No external assets or\n * network fetches (this is a one-shot loopback server, sometimes seen for only a\n * moment during the GitHub redirect). `body` is placed inside the card verbatim,\n * so callers keep full control of it (e.g. the auto-submitting manifest form).\n */\nfunction renderPage(title: string, body: string): string {\n return (\n `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">` +\n `<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">` +\n `<title>${htmlEscape(title)}</title><style>` +\n `:root{color-scheme:light dark}*{box-sizing:border-box}` +\n `body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px;` +\n `font-family:system-ui,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;background:#f4f6f5;color:#141a17}` +\n `.card{width:100%;max-width:28rem;background:#fff;border:1px solid #e2e8e5;border-radius:14px;` +\n `padding:32px;box-shadow:0 6px 24px rgba(0,0,0,.06);text-align:center}` +\n `.mark{width:44px;height:44px;margin:0 auto 18px;border-radius:12px;background:#128a4f;color:#fff;` +\n `display:flex;align-items:center;justify-content:center;font-weight:700;font-size:22px}` +\n `h1{margin:0 0 8px;font-size:1.2rem}p{margin:0;line-height:1.5;color:#4a5551;font-size:.95rem}` +\n `.btn{display:inline-block;margin-top:20px;padding:10px 18px;border:0;border-radius:9px;background:#128a4f;` +\n `color:#fff;font:inherit;font-weight:600;cursor:pointer;text-decoration:none}.btn:hover{background:#0f7443}` +\n `@media(prefers-color-scheme:dark){body{background:#0e1512;color:#e6ebe8}` +\n `.card{background:#16201c;border-color:#24322c;box-shadow:0 6px 24px rgba(0,0,0,.4)}p{color:#9fb0a8}}` +\n `</style></head><body><main class=\"card\"><div class=\"mark\">A</div>${body}</main></body></html>`\n );\n}\n\nexport async function runGitHubAppManifestFlow(\n opts: ManifestFlowOptions,\n): Promise<ManifestFlowResult> {\n const githubUrl = (opts.githubUrl ?? 'https://github.com').replace(/\\/$/, '');\n const apiBaseUrl = (opts.apiBaseUrl ?? 'https://api.github.com').replace(/\\/$/, '');\n const fetchImpl = opts.fetchImpl ?? fetch;\n const log = opts.log ?? (() => {});\n const state = randomBytes(16).toString('hex');\n\n return new Promise<ManifestFlowResult>((resolve, reject) => {\n // Captured once at listen() time — NEVER read server.address() per request:\n // after the flow settles we close the server, and a stray follow-up request\n // (favicon, a reloaded tab) would otherwise hit a null address and throw.\n let listenPort = 0;\n let settled = false;\n const server = createServer((req, res) => {\n if (settled) {\n res.writeHead(204);\n res.end();\n return;\n }\n const url = new URL(req.url ?? '/', `http://127.0.0.1`);\n const redirectUrl = `http://127.0.0.1:${String(listenPort)}/callback`;\n\n if (url.pathname === '/') {\n // The manifest GitHub will turn into an App. Repo-scoped write perms.\n const manifest = {\n name: opts.appName,\n url: opts.homepageUrl ?? 'https://agent-box.sh',\n redirect_url: redirectUrl,\n public: false,\n default_permissions: { contents: 'write', pull_requests: 'write' },\n };\n const action = opts.org\n ? `${githubUrl}/organizations/${encodeURIComponent(opts.org)}/settings/apps/new?state=${state}`\n : `${githubUrl}/settings/apps/new?state=${state}`;\n const page = renderPage(\n 'Redirecting to GitHub',\n `<h1>Creating your GitHub App…</h1>` +\n `<p>Redirecting to GitHub. If this page doesn't redirect on its own, use the button below.</p>` +\n `<form id=\"f\" method=\"post\" action=\"${htmlEscape(action)}\">` +\n `<input type=\"hidden\" name=\"manifest\" value=\"${htmlEscape(JSON.stringify(manifest))}\">` +\n `<button class=\"btn\" type=\"submit\">Continue to GitHub</button></form>` +\n `<script>document.getElementById('f').submit()</script>`,\n );\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });\n res.end(page);\n return;\n }\n\n if (url.pathname === '/callback') {\n const code = url.searchParams.get('code') ?? '';\n const gotState = url.searchParams.get('state') ?? '';\n if (gotState !== state) {\n res.writeHead(400, { 'content-type': 'text/plain' });\n res.end('state mismatch');\n return;\n }\n if (code.length === 0) {\n res.writeHead(400, { 'content-type': 'text/plain' });\n res.end('missing code');\n return;\n }\n // Exchange the temporary code for the App's id + private key.\n void fetchImpl(`${apiBaseUrl}/app-manifests/${encodeURIComponent(code)}/conversions`, {\n method: 'POST',\n headers: {\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': 'agentbox',\n },\n })\n .then(async (r) => {\n if (!r.ok) throw new Error(`manifest conversion failed (→ ${String(r.status)})`);\n const body = (await r.json()) as {\n id?: number;\n slug?: string;\n pem?: string;\n html_url?: string;\n };\n if (typeof body.id !== 'number' || !body.slug || !body.pem) {\n throw new Error('manifest conversion response missing id/slug/pem');\n }\n const result: ManifestFlowResult = {\n appId: String(body.id),\n slug: body.slug,\n pem: body.pem,\n htmlUrl: body.html_url ?? `${githubUrl}/apps/${body.slug}`,\n installUrl: `${githubUrl}/apps/${body.slug}/installations/new`,\n };\n settled = true;\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });\n res.end(\n renderPage(\n 'GitHub App created',\n `<h1>GitHub App created</h1>` +\n `<p>App: ${htmlEscape(result.slug)} (id ${result.appId}). ` +\n `You can close this tab and return to the terminal.</p>`,\n ),\n );\n server.close();\n resolve(result);\n })\n .catch((err: unknown) => {\n settled = true;\n res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });\n res.end('conversion failed');\n server.close();\n reject(err instanceof Error ? err : new Error(String(err)));\n });\n return;\n }\n\n res.writeHead(404);\n res.end();\n });\n\n const timer = setTimeout(\n () => {\n server.close();\n reject(new Error('timed out waiting for the GitHub App manifest flow to complete'));\n },\n opts.timeoutMs ?? 5 * 60_000,\n );\n if (typeof timer.unref === 'function') timer.unref();\n\n server.on('error', (err) => {\n clearTimeout(timer);\n reject(err);\n });\n server.listen(0, '127.0.0.1', () => {\n listenPort = (server.address() as AddressInfo).port;\n const startUrl = `http://127.0.0.1:${String(listenPort)}/`;\n log(`opening ${startUrl} to create the GitHub App…`);\n void Promise.resolve(opts.openBrowser(startUrl)).catch((err: unknown) => {\n log(`could not open the browser automatically: ${err instanceof Error ? err.message : String(err)}`);\n log(`open this URL manually: ${startUrl}`);\n });\n });\n });\n}\n","import { spawn } from 'node:child_process';\nimport { mkdtempSync, rmSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport {\n createGitDeployment,\n createGitProject,\n deleteProject,\n getDeployment,\n getProductionAlias,\n getProject,\n patchProjectSettings,\n projectHasEnv,\n resolveVercelApiAuth,\n upsertProjectEnv,\n type VercelProjectFull,\n} from '@agentbox/sandbox-vercel';\nimport { ensureFork, ghAvailable, ghLogin, ownerOf } from './github-fork.js';\nimport { openInBrowser } from './ensure-repo-installed.js';\n\n/**\n * Deploy the control plane to Vercel **from GitHub**, in tiers so it works for\n * everyone without a local checkout:\n * 1. If the deployer doesn't own `repo`, `gh`-fork it to their account.\n * 2. API deploy the owned/forked repo (headless; needs the Vercel GitHub App).\n * 3. Fallback: open the Vercel Deploy Button (clones the repo into the user's\n * account + installs the App + provisions Postgres in-browser), then finish\n * via the API (set the secrets + redeploy) — no manual paste.\n */\nexport interface VercelDeployOptions {\n /** App env baked into the build: GITHUB_APP_ID / _PRIVATE_KEY / ADMIN_TOKEN. */\n env: Record<string, string>;\n /** `owner/name` GitHub slug to deploy from. */\n repo: string;\n /** Branch / tag / sha to build. */\n ref: string;\n project?: string;\n log: (line: string) => void;\n}\n\nconst PROJECT_DEFAULT = 'agentbox-control-plane';\nconst ROOT_DIRECTORY = 'apps/hub';\n\n/** Raised when Vercel can't connect the repo (GitHub App not installed on the owner). */\nclass GitConnectError extends Error {}\n\nfunction connectedTo(p: VercelProjectFull | null, repo: string): boolean {\n return (\n !!p?.link &&\n p.link.type === 'github' &&\n `${p.link.org ?? ''}/${p.link.repo ?? ''}`.toLowerCase() === repo.toLowerCase()\n );\n}\n\nfunction isConnectError(msg: string): boolean {\n return /install the GitHub integration|integration first|github integration/i.test(msg);\n}\n\n/** Best-effort Neon provisioning via the logged-in `vercel` CLI, in a temp cwd. */\nfunction provisionNeon(teamId: string | undefined, projectId: string, log: (l: string) => void): Promise<void> {\n return new Promise((resolve) => {\n const work = mkdtempSync(join(tmpdir(), 'agentbox-neon-'));\n const env = { ...process.env, VERCEL_PROJECT_ID: projectId, ...(teamId ? { VERCEL_ORG_ID: teamId } : {}) };\n const child = spawn('vercel', ['integration', 'add', 'neon', '--non-interactive'], {\n cwd: work,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n const onData = (c: Buffer): void => {\n for (const l of c.toString('utf8').split(/\\r?\\n/)) if (l.trim()) log(`neon: ${l.trim()}`);\n };\n child.stdout.on('data', onData);\n child.stderr.on('data', onData);\n const done = (): void => {\n try {\n rmSync(work, { recursive: true, force: true });\n } catch {\n /* best-effort */\n }\n resolve();\n };\n child.on('error', (e) => {\n log(`neon: could not run \\`vercel integration add neon\\` (${e.message}) — continuing`);\n done();\n });\n child.on('close', (code) => {\n if (code !== 0) log(`neon: integration add exited ${String(code)} — continuing (it may already be attached)`);\n done();\n });\n });\n}\n\nasync function pollDeployment(\n token: string,\n teamId: string | undefined,\n id: string,\n log: (l: string) => void,\n): Promise<void> {\n const stop = Date.now() + 20 * 60_000;\n let last = '';\n while (Date.now() < stop) {\n const d = await getDeployment(token, teamId, id);\n if (d.readyState !== last) {\n log(`build: ${d.readyState.toLowerCase()}`);\n last = d.readyState;\n }\n if (d.readyState === 'READY') return;\n if (d.readyState === 'ERROR' || d.readyState === 'CANCELED' || d.readyState === 'BLOCKED') {\n throw new Error(\n `Vercel build ${d.readyState.toLowerCase()}${d.errorStep ? ` at ${d.errorStep}` : ''}: ${d.errorMessage ?? 'see the Vercel dashboard'}`,\n );\n }\n await new Promise((r) => setTimeout(r, 6_000));\n }\n throw new Error('timed out waiting for the Vercel build to finish');\n}\n\nfunction envVars(env: Record<string, string>): Array<{ key: string; value: string }> {\n return Object.entries(env).map(([key, value]) => ({ key, value }));\n}\n\ninterface DeployArgs {\n token: string;\n teamId: string | undefined;\n repo: string;\n ref: string;\n env: Record<string, string>;\n projectName: string;\n log: (line: string) => void;\n}\n\n/** Headless API deploy of a repo Vercel can connect (owned/forked). */\nasync function apiDeploy(a: DeployArgs): Promise<{ url: string }> {\n const [owner, repoName] = a.repo.split('/');\n a.log(`ensuring Vercel project \"${a.projectName}\" is connected to ${a.repo}…`);\n let project = await getProject(a.token, a.teamId, a.projectName);\n if (project && !connectedTo(project, a.repo)) {\n a.log(`project exists but is not connected to ${a.repo}; recreating…`);\n await deleteProject(a.token, a.teamId, project.id);\n project = null;\n }\n if (!project) {\n try {\n project = await createGitProject(a.token, a.teamId, {\n name: a.projectName,\n repo: a.repo,\n rootDirectory: ROOT_DIRECTORY,\n });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n if (isConnectError(msg)) throw new GitConnectError(msg);\n throw e;\n }\n } else {\n await patchProjectSettings(a.token, a.teamId, project.id, {\n framework: 'nextjs',\n rootDirectory: ROOT_DIRECTORY,\n });\n }\n\n // Idempotent: only provision Neon when the project has no Postgres yet —\n // re-running otherwise provisions an orphan Neon that collides on the\n // already-present POSTGRES_URL_NON_POOLING.\n if (await projectHasEnv(a.token, a.teamId, project.id, 'POSTGRES_URL')) {\n a.log('Postgres already attached — skipping Neon provisioning');\n } else {\n a.log('provisioning Neon Postgres…');\n await provisionNeon(a.teamId, project.id, a.log);\n }\n a.log('setting environment variables…');\n await upsertProjectEnv(a.token, a.teamId, project.id, envVars(a.env));\n\n a.log(`triggering a production build of ${a.repo}@${a.ref}…`);\n const dep = await createGitDeployment(a.token, a.teamId, {\n name: a.projectName,\n projectId: project.id,\n owner: owner!,\n repo: repoName!,\n ref: a.ref,\n });\n await pollDeployment(a.token, a.teamId, dep.id, a.log);\n const alias = (await getProductionAlias(a.token, a.teamId, project.id)) ?? dep.url ?? null;\n if (!alias) throw new Error('build is ready but no production URL was found');\n return { url: alias.startsWith('http') ? alias : `https://${alias}` };\n}\n\nfunction deployButtonUrl(repo: string, projectName: string): string {\n const p = new URLSearchParams({\n 'repository-url': `https://github.com/${repo}`,\n 'root-directory': ROOT_DIRECTORY,\n stores: '[{\"type\":\"postgres\"}]',\n 'project-name': projectName,\n 'repository-name': projectName,\n });\n return `https://vercel.com/new/clone?${p.toString()}`;\n}\n\n/**\n * Fallback when Vercel can't connect the repo via the API (App not installed):\n * the Deploy Button does the clone + App install + Postgres in-browser; we then\n * set the secrets + redeploy via the API (the control plane boots gracefully\n * unconfigured in the meantime).\n */\nasync function buttonDeploy(a: DeployArgs): Promise<{ url: string }> {\n const url = deployButtonUrl(a.repo, a.projectName);\n a.log(`opening the Vercel Deploy Button — complete the clone + Postgres setup in your browser:`);\n a.log(url);\n openInBrowser(url);\n\n a.log('waiting for the Vercel project to appear (finish the deploy in the browser)…');\n const stop = Date.now() + 10 * 60_000;\n let project: VercelProjectFull | null = null;\n while (Date.now() < stop) {\n project = await getProject(a.token, a.teamId, a.projectName);\n if (project?.link?.type === 'github' && project.link.repo) break;\n project = null;\n await new Promise((r) => setTimeout(r, 5_000));\n }\n if (!project?.link?.repo) {\n throw new Error(\n `timed out waiting for the Vercel project \"${a.projectName}\". Finish the browser deploy, then re-run, ` +\n `or set the env vars + redeploy in the Vercel dashboard.`,\n );\n }\n\n a.log('setting environment variables + redeploying…');\n await upsertProjectEnv(a.token, a.teamId, project.id, envVars(a.env));\n const dep = await createGitDeployment(a.token, a.teamId, {\n name: a.projectName,\n projectId: project.id,\n owner: project.link.org ?? ownerOf(a.repo),\n repo: project.link.repo,\n ref: a.ref,\n });\n await pollDeployment(a.token, a.teamId, dep.id, a.log);\n const alias = (await getProductionAlias(a.token, a.teamId, project.id)) ?? dep.url ?? null;\n if (!alias) throw new Error('redeploy is ready but no production URL was found');\n return { url: alias.startsWith('http') ? alias : `https://${alias}` };\n}\n\nexport async function deployControlPlaneToVercel(opts: VercelDeployOptions): Promise<{ url: string }> {\n const auth = await resolveVercelApiAuth();\n if (!auth) {\n throw new Error('not logged in to Vercel — run `agentbox vercel login` (or set VERCEL_TOKEN)');\n }\n const { token, teamId } = auth;\n const projectName = opts.project ?? PROJECT_DEFAULT;\n const [owner, repoName] = opts.repo.split('/');\n if (!owner || !repoName) throw new Error(`--repo must be \"owner/name\" (got \"${opts.repo}\")`);\n\n // Resolve the deploy target: if `gh` is available and the deployer doesn't own\n // the repo, fork it to their account (Vercel can only connect a repo whose\n // owner has the Vercel GitHub App). Without `gh`, deploy the repo as-is — the\n // API connect will fail for a non-owned repo and we fall through to the button.\n let target = opts.repo;\n if (await ghAvailable()) {\n const login = await ghLogin();\n if (login && login.toLowerCase() !== owner.toLowerCase()) {\n target = await ensureFork(opts.repo, login, opts.log);\n }\n }\n\n const args: DeployArgs = { token, teamId, repo: target, ref: opts.ref, env: opts.env, projectName, log: opts.log };\n try {\n return await apiDeploy(args);\n } catch (e) {\n if (e instanceof GitConnectError) {\n opts.log(`Vercel can't connect ${target} via the API (GitHub App not installed); using the Deploy Button…`);\n return buttonDeploy(args);\n }\n throw e;\n }\n}\n","import { spawn } from 'node:child_process';\n\n/**\n * Thin `gh` CLI wrappers for the Vercel deploy's auto-fork step. Vercel can only\n * connect a repo whose owner has the Vercel GitHub App, so a deployer who\n * doesn't own the target repo forks it to their own account first. `gh` is a\n * host tool (same as the relay's `gh pr` path) — absent/unauthed routes the\n * caller to the Deploy-Button fallback instead.\n */\nfunction gh(args: string[]): Promise<{ code: number; stdout: string; stderr: string }> {\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n let child;\n try {\n child = spawn('gh', args, { stdio: ['ignore', 'pipe', 'pipe'] });\n } catch {\n resolve({ code: 127, stdout: '', stderr: 'gh not found' });\n return;\n }\n child.stdout.on('data', (c: Buffer) => (stdout += c.toString('utf8')));\n child.stderr.on('data', (c: Buffer) => (stderr += c.toString('utf8')));\n child.on('error', () => resolve({ code: 127, stdout, stderr: stderr || 'gh not found' }));\n child.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));\n });\n}\n\nexport function ownerOf(repo: string): string {\n return repo.split('/')[0] ?? '';\n}\nexport function nameOf(repo: string): string {\n return repo.split('/')[1] ?? '';\n}\n\n/** Whether `gh` is installed AND authenticated. */\nexport async function ghAvailable(): Promise<boolean> {\n return (await gh(['auth', 'status'])).code === 0;\n}\n\n/** The authenticated GitHub login, or null. */\nexport async function ghLogin(): Promise<string | null> {\n const r = await gh(['api', 'user', '-q', '.login']);\n const login = r.stdout.trim();\n return r.code === 0 && login.length > 0 ? login : null;\n}\n\n/**\n * Fork `repo` to the authenticated user (idempotent — tolerates an existing\n * fork) and wait until the GitHub API sees it. Returns `<login>/<name>`.\n */\nexport async function ensureFork(repo: string, login: string, log: (l: string) => void): Promise<string> {\n const fork = `${login}/${nameOf(repo)}`;\n log(`forking ${repo} -> ${fork}…`);\n const f = await gh(['repo', 'fork', repo, '--clone=false']);\n if (f.code !== 0 && !/already exists/i.test(`${f.stderr}${f.stdout}`)) {\n throw new Error(`gh repo fork ${repo} failed: ${(f.stderr || f.stdout).trim()}`);\n }\n // Forks are created asynchronously — poll until the API resolves the fork.\n const stop = Date.now() + 60_000;\n while (Date.now() < stop) {\n const v = await gh(['api', `repos/${fork}`, '-q', '.full_name']);\n if (v.code === 0 && v.stdout.trim().toLowerCase() === fork.toLowerCase()) return fork;\n await new Promise((r) => setTimeout(r, 2_000));\n }\n throw new Error(`fork ${fork} did not become available within 60s`);\n}\n","import { confirm, isCancel, log as clog, note } from '@clack/prompts';\nimport { spawn } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type { GitPushMode, HubGitAuthMode } from '@agentbox/config';\nimport { GitHubAppLeaser, loadGitHubAppConfig, parseGitRemote } from '@agentbox/relay';\nimport { hostOpenCommand } from '@agentbox/sandbox-core';\n\nconst CP_DIR = join(homedir(), '.agentbox', 'control-plane');\nconst ENV_PATH = join(CP_DIR, 'control-plane.env');\nconst META_PATH = join(CP_DIR, 'control-plane.json');\nconst REPOS_STATE = join(CP_DIR, 'repos.json');\n\n/** Best-effort: open a URL in the host browser (never throws). */\nexport function openInBrowser(url: string): void {\n try {\n const child = spawn(hostOpenCommand(), [url], { detached: true, stdio: 'ignore' });\n child.unref();\n } catch {\n /* caller prints the URL to open manually */\n }\n}\n\ninterface ControlPlaneMeta {\n appId?: string;\n slug?: string;\n htmlUrl?: string;\n installUrl?: string;\n}\n\nexport function loadControlPlaneMeta(): ControlPlaneMeta | null {\n try {\n return JSON.parse(readFileSync(META_PATH, 'utf8')) as ControlPlaneMeta;\n } catch {\n return null;\n }\n}\n\n/** Load the setup-written App creds (+ admin token) into the env if not already set. */\nfunction loadLocalControlPlaneEnv(): void {\n if (!existsSync(ENV_PATH)) return;\n for (const line of readFileSync(ENV_PATH, 'utf8').split('\\n')) {\n const m = /^([A-Z_]+)=(.*)$/.exec(line.trim());\n if (m && !process.env[m[1]!]) process.env[m[1]!] = m[2];\n }\n}\n\n/** Resolve the project's origin into `owner/repo`, or null if absent/unparseable. */\nexport async function resolveOwnerRepo(projectRoot: string): Promise<{ owner: string; repo: string } | null> {\n const r = await execa('git', ['-C', projectRoot, 'remote', 'get-url', 'origin'], { reject: false });\n const origin = (r.stdout ?? '').trim();\n if (r.exitCode !== 0 || origin.length === 0) return null;\n try {\n const { path } = parseGitRemote(origin);\n const [owner, repo] = path.replace(/\\.git$/, '').split('/');\n if (!owner || !repo) return null;\n return { owner, repo };\n } catch {\n return null;\n }\n}\n\n/**\n * Whether the GitHub App is installed on owner/repo. Prefers the local App key\n * (works offline); falls back to the plane's admin endpoint; returns 'unknown'\n * when neither credential is available locally.\n */\nexport async function checkRepoInstalled(\n owner: string,\n repo: string,\n controlPlaneUrl: string | undefined,\n): Promise<boolean | 'unknown'> {\n loadLocalControlPlaneEnv();\n const appCfg = loadGitHubAppConfig();\n if (appCfg) {\n try {\n return await new GitHubAppLeaser(appCfg).isRepoInstalled(owner, repo);\n } catch {\n /* fall through to the plane check */\n }\n }\n const adminToken = process.env.AGENTBOX_RELAY_ADMIN_TOKEN;\n if (controlPlaneUrl && adminToken) {\n try {\n const u = `${controlPlaneUrl.replace(/\\/$/, '')}/admin/app/repo-installed?owner=${encodeURIComponent(owner)}&repo=${encodeURIComponent(repo)}`;\n const res = await fetch(u, {\n headers: { Authorization: `Bearer ${adminToken}` },\n signal: AbortSignal.timeout(8000),\n });\n if (res.ok) return Boolean(((await res.json()) as { installed?: boolean }).installed);\n } catch {\n /* unknown */\n }\n }\n return 'unknown';\n}\n\n/** The GitHub page where the user picks repositories for the App installation. */\nexport function addRepoUrl(meta: ControlPlaneMeta | null): string | null {\n return meta?.installUrl ?? (meta?.slug ? `https://github.com/apps/${meta.slug}/installations/new` : null);\n}\n\ntype ReposState = Record<string, { installed?: boolean; promptedAt?: string }>;\n\nfunction readReposState(): ReposState {\n try {\n return JSON.parse(readFileSync(REPOS_STATE, 'utf8')) as ReposState;\n } catch {\n return {};\n }\n}\nfunction writeReposState(state: ReposState): void {\n try {\n mkdirSync(CP_DIR, { recursive: true });\n writeFileSync(REPOS_STATE, JSON.stringify(state, null, 2) + '\\n', { mode: 0o600 });\n } catch {\n /* best-effort cache; never block a launch on it */\n }\n}\n\n/**\n * Before launching an agent against a configured control plane, make sure the\n * project repo is authorized on the GitHub App (else pushes can't lease a\n * token). Checks install status, prompts to open the add-repo page when\n * missing, and remembers the outcome so it never nags again. No-op without a\n * control plane, without an origin, or non-interactively (then it only warns).\n */\nexport async function ensureProjectRepoOnControlPlane(args: {\n controlPlaneUrl: string | undefined;\n gitPushMode?: GitPushMode;\n hubGitAuth?: HubGitAuthMode;\n projectRoot: string;\n yes?: boolean;\n}): Promise<void> {\n const { controlPlaneUrl, projectRoot } = args;\n if (!controlPlaneUrl) return;\n // `relay` and `direct` push modes never lease from the plane, so the repo\n // doesn't need to be authorized on the control plane's GitHub App — skip the\n // check/nag. (`direct` uses credentials copied straight into the box.)\n if (args.gitPushMode === 'relay' || args.gitPushMode === 'direct') return;\n // Same for a `gh`-mode hub: there is no App to authorize a repo on — the hub\n // pushes for the box with its own token. Nagging there sent users to an\n // install page for an App that doesn't exist.\n if ((args.hubGitAuth ?? 'gh') !== 'app') return;\n const ownerRepo = await resolveOwnerRepo(projectRoot);\n if (!ownerRepo) return;\n const { owner, repo } = ownerRepo;\n const key = `${controlPlaneUrl.replace(/\\/$/, '')}|${owner}/${repo}`;\n\n const state = readReposState();\n if (state[key]?.installed) return;\n\n const installed = await checkRepoInstalled(owner, repo, controlPlaneUrl);\n if (installed === true) {\n state[key] = { installed: true };\n writeReposState(state);\n return;\n }\n if (state[key]?.promptedAt) {\n // Already prompted once — don't re-nag with a blocking prompt, but a one-line\n // reminder beats a silent lease failure later. (The live check above still\n // auto-clears this and goes quiet once the repo is actually authorized.)\n clog.warn(\n `${owner}/${repo} isn't authorized on the control plane's GitHub App yet — run \\`agentbox hub add\\`.`,\n );\n return;\n }\n\n const meta = loadControlPlaneMeta();\n const url = addRepoUrl(meta);\n const nonInteractive = args.yes === true || process.env.AGENTBOX_PROMPT === 'off' || !process.stdout.isTTY;\n\n if (nonInteractive) {\n clog.warn(\n `Repo ${owner}/${repo} may not be authorized on the control plane's GitHub App; ` +\n `pushes/PRs will fail to lease until you run \\`agentbox hub add\\`.`,\n );\n state[key] = { promptedAt: new Date().toISOString() };\n writeReposState(state);\n return;\n }\n\n if (!url) {\n clog.warn(\n `Repo ${owner}/${repo} isn't authorized on the GitHub App and no App metadata was found locally. ` +\n `Run \\`agentbox hub add\\` from a machine that ran \\`hub setup\\`.`,\n );\n state[key] = { promptedAt: new Date().toISOString() };\n writeReposState(state);\n return;\n }\n\n const ok = await confirm({\n message: `Authorize ${owner}/${repo} on the GitHub App so this box can push / open PRs?`,\n initialValue: true,\n });\n if (!isCancel(ok) && ok) {\n openInBrowser(url);\n note(`Opened ${url}\\nSelect ${owner}/${repo}, approve, then return here.`, 'GitHub App');\n }\n state[key] = { promptedAt: new Date().toISOString() };\n writeReposState(state);\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n type ControlPlaneDeployRecord,\n type HubDeploySource,\n} from '@agentbox/sandbox-core';\nimport {\n deployControlPlaneToDigitalOcean,\n destroyControlPlaneOnDigitalOcean,\n readDigitalOceanCredStatus,\n updateControlPlaneOnDigitalOcean,\n type ControlPlaneDestroyResult,\n} from '@agentbox/sandbox-digitalocean';\nimport {\n assertReachableRecord,\n persistDeployRecord,\n readDeployRecord,\n} from './deploy-hetzner.js';\n\n/**\n * CLI wrapper for the DigitalOcean control-plane deploy: precheck the token, run\n * the provisioning in `@agentbox/sandbox-digitalocean`, and persist the deploy\n * record so a later command (or the user) can find / tear down the Droplet.\n *\n * The deploy-record + ssh-config bookkeeping (`persistDeployRecord`,\n * `readDeployRecord`, `assertReachableRecord`) is provider-agnostic and shared\n * with the Hetzner wrapper — only the provider-specific provisioning differs.\n */\nexport interface DigitalOceanDeployOptions {\n /** Path to the setup-written control-plane.env (scp'd to the Droplet as `.env`). */\n envPath: string;\n /** Where the Droplet gets the hub from — the npm package, or a cloned ref. */\n source: HubDeploySource;\n /**\n * Serve on a hostname you control instead of the default `<ip>.sslip.io`. Point\n * its DNS at the Droplet first — Caddy proves ownership over HTTP-01, so a name\n * that doesn't resolve to this machine never gets a certificate.\n */\n domain?: string;\n /** DigitalOcean region slug (default nyc3). */\n region?: string;\n /** Droplet size slug (default s-2vcpu-4gb). */\n size?: string;\n log: (line: string) => void;\n /**\n * Fired once the Droplet exists, before the build + healthz poll. Lets the\n * caller report how to reach the machine when a later step fails — the droplet\n * is not torn down, so it is inspectable (and billable) either way.\n */\n onProvisioned?: (info: ControlPlaneDeployRecord) => void;\n}\n\nexport async function runDigitalOceanDeploy(opts: DigitalOceanDeployOptions): Promise<{ url: string }> {\n if (readDigitalOceanCredStatus().source === 'none') {\n throw new Error('no DIGITALOCEAN_TOKEN configured — run `agentbox digitalocean login` first');\n }\n const envContent = await readFile(opts.envPath, 'utf8');\n const result = await deployControlPlaneToDigitalOcean({\n envContent,\n source: opts.source,\n ...(opts.domain ? { domain: opts.domain } : {}),\n ...(opts.region ? { region: opts.region } : {}),\n ...(opts.size ? { size: opts.size } : {}),\n onLog: opts.log,\n onProvisioned: async (info) => {\n const record: ControlPlaneDeployRecord = {\n provider: 'digitalocean',\n source: opts.source,\n ...info,\n };\n opts.onProvisioned?.(record);\n await persistDeployRecord(record);\n },\n });\n await persistDeployRecord({ provider: 'digitalocean', source: opts.source, ...result });\n return { url: result.url };\n}\n\n/** Human-readable recovery steps for a deploy that provisioned but never went healthy. */\nexport function recoveryHint(record: ControlPlaneDeployRecord): string[] {\n const key = record.sshKeyDir ? join(record.sshKeyDir, 'id_ed25519') : undefined;\n // Must match the `-f` list the deploy used: compose keys the project off it, so\n // a pasted command with the wrong list reports \"no such service\".\n const files = [\n '-f docker-compose.yml',\n ...(record.source?.kind === 'package' ? ['-f docker-compose.package.yml'] : []),\n '-f docker-compose.caddy.yml',\n ].join(' ');\n return [\n `The Droplet is still running (droplet ${String(record.serverId ?? '?')}, ${record.ip ?? '?'}) — inspect it:`,\n ` ssh agentbox-hub`,\n ...(key ? [` (or: ssh -i ${key} root@${record.ip ?? '?'})`] : []),\n ` cd /opt/agentbox/apps/hub && docker compose ${files} logs --tail=200 app`,\n `SSH is firewalled to this machine's egress IP, so run it from here.`,\n `Retry the deploy with \\`agentbox hub deploy digitalocean\\` (reuses the same env).`,\n ];\n}\n\nexport interface DigitalOceanUpdateOptions {\n envPath: string;\n /** The build to move to. */\n source: HubDeploySource;\n log: (line: string) => void;\n}\n\n/**\n * Update the control box recorded in `deploy.json` in place, then record the new\n * build. The record is written only on success — a failed update leaves the\n * previous `source` in place, which is what the Droplet is still running.\n */\nexport async function runDigitalOceanUpdate(opts: DigitalOceanUpdateOptions): Promise<{ url: string }> {\n if (readDigitalOceanCredStatus().source === 'none') {\n throw new Error('no DIGITALOCEAN_TOKEN configured — run `agentbox digitalocean login` first');\n }\n const record = await readDeployRecord();\n assertReachableRecord(record);\n const envContent = await readFile(opts.envPath, 'utf8');\n await updateControlPlaneOnDigitalOcean({\n record: {\n ip: record.ip,\n sshKeyDir: record.sshKeyDir,\n url: record.url,\n ...(record.domain ? { domain: record.domain } : {}),\n // DigitalOcean firewall ids are UUID strings; the shared record widened to\n // number|string, so narrow here (a DO record never carries a number).\n ...(typeof record.firewallId === 'string' ? { firewallId: record.firewallId } : {}),\n },\n source: opts.source,\n envContent,\n onLog: opts.log,\n });\n await persistDeployRecord({ ...record, source: opts.source });\n return { url: record.url };\n}\n\n/**\n * Delete the control box's DigitalOcean resources. The local state is purged by\n * the caller afterwards — deliberately separate, so a partial cloud teardown\n * still lets the user clear config that now points at nothing.\n */\nexport async function runDigitalOceanDestroy(opts: {\n record: ControlPlaneDeployRecord;\n log: (line: string) => void;\n}): Promise<ControlPlaneDestroyResult> {\n if (readDigitalOceanCredStatus().source === 'none') {\n throw new Error('no DIGITALOCEAN_TOKEN configured — run `agentbox digitalocean login` first');\n }\n return destroyControlPlaneOnDigitalOcean({\n ...(opts.record.serverId !== undefined ? { serverId: opts.record.serverId } : {}),\n ...(typeof opts.record.firewallId === 'string' ? { firewallId: opts.record.firewallId } : {}),\n ...(opts.record.firewallTag ? { firewallTag: opts.record.firewallTag } : {}),\n onLog: opts.log,\n });\n}\n","/**\n * Daily-throttled update check + \"newer version available\" nudge.\n *\n * Network discipline: normal CLI calls never hit the network. At most once\n * per 24h an eligible interactive command fires ONE background check (npm\n * registry `latest` + the tray zip's ~80-byte sha256 sidecar), un-awaited,\n * short-timeout, all errors swallowed, result cached in\n * `~/.agentbox/update-state.json`. The nudge itself always prints from the\n * cache — typically the previous day's result.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { GLOBAL_CONFIG_FILE, loadEffectiveConfig, parseUserConfig } from '@agentbox/config';\nimport { detectExecutionMethod, type ExecMethod } from '../exec-method.js';\nimport { AGENTBOX_VERSION } from '../version.js';\nimport {\n bestTrayRelease,\n fetchTrayLatestVersion,\n fetchTraySidecarSha,\n trayInstalled,\n} from '../commands/install-app.js';\nimport {\n NPM_PACKAGE,\n bestOf,\n isPrerelease,\n npmDistTags,\n resolveChannel,\n type UpdateChannel,\n} from './channel.js';\nimport { isNewer } from './semver-lite.js';\nimport {\n readUpdateState,\n remoteCheckFresh,\n writeUpdateState,\n type RemoteCheck,\n type UpdateState,\n} from './update-state.js';\n\nconst PKG = NPM_PACKAGE;\nconst registryUrl = (distTag: string) => `https://registry.npmjs.org/${PKG}/${distTag}`;\n\n/**\n * The nudge (and the registry check feeding it) only makes sense when\n * `agentbox self-update` can actually act: an npm/pnpm global install with a\n * real release version. A dev checkout reports `0.0.0-dev`, npx always\n * resolves latest anyway, and `direct` (a checkout run via symlink) has no\n * global install to update — nudging those would point at a self-update that\n * skips. `detectExecutionMethod` resolves the bin symlink, so a global\n * install invoked straight from the shell classifies as npm/pnpm.\n */\nexport function nudgeEligible(method: ExecMethod, version: string): boolean {\n return version !== '0.0.0-dev' && (method === 'npm' || method === 'pnpm');\n}\n\n/**\n * `update.check` config gate. The layered load can throw for reasons\n * unrelated to this key (e.g. a project config carrying keys from a provider\n * plugin the stock registry doesn't know) — that must not override an\n * explicit global opt-out, so fall back to reading the global file alone.\n */\nexport async function updateCheckEnabled(): Promise<boolean> {\n try {\n const cfg = await loadEffectiveConfig(process.cwd());\n return cfg.effective.update.check;\n } catch {\n try {\n const raw = await readFile(GLOBAL_CONFIG_FILE, 'utf8');\n return parseUserConfig(raw, GLOBAL_CONFIG_FILE).update?.check ?? true;\n } catch (err) {\n // No global config at all → the default (enabled). A global file that\n // exists but doesn't parse → stay quiet rather than add noise.\n return (err as NodeJS.ErrnoException).code === 'ENOENT';\n }\n }\n}\n\nasync function fetchDistTag(distTag: string): Promise<string | undefined> {\n try {\n const res = await fetch(registryUrl(distTag), { signal: AbortSignal.timeout(3000) });\n if (!res.ok) return undefined;\n const body = (await res.json()) as { version?: unknown };\n return typeof body.version === 'string' ? body.version : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The newest published CLI on `channel`. Stable probes one dist-tag; nightly\n * probes both and takes the greater, so a shipped release supersedes the\n * nightlies that preceded it without needing a second publish under `nightly`.\n */\nexport async function fetchNpmBest(channel: UpdateChannel): Promise<string | undefined> {\n const tags = npmDistTags(channel);\n const found = await Promise.all(\n tags.map(async (tag) => ({ tag, version: await fetchDistTag(tag) })),\n );\n return bestOf(found)?.version;\n}\n\n/**\n * Same shape for the tray. `bestTrayRelease` returns null for stable (and when\n * nothing comparable came back), in which case this falls back to the stable\n * tag's sha — exactly the behavior that existed before channels.\n */\ninterface TrayProbe {\n sha?: string | undefined;\n version?: string | undefined;\n}\n\nasync function fetchTrayBest(channel: UpdateChannel): Promise<TrayProbe> {\n const winner = await bestTrayRelease(channel);\n if (!winner) {\n const [sha, version] = await Promise.all([fetchTraySidecarSha(), fetchTrayLatestVersion()]);\n return { sha, version };\n }\n return { sha: await fetchTraySidecarSha(winner.tag), version: winner.version };\n}\n\n/**\n * Merge a probe's results over the previous cache, so a partial probe (one\n * fetch failed) doesn't drop what the other cached earlier.\n *\n * The tray sha and the tray version describe the SAME release, so they must\n * travel together. Carrying a stale version forward alongside a fresh sha\n * would name the previous release in the update prompt while installing the\n * new one — so when the sha moves and the manifest didn't come back (a 404 on\n * a release predating the manifest, or a transient failure), the version is\n * dropped rather than inherited. The prompt then just omits the version.\n */\nexport function mergeRemoteCheck(\n fetched: {\n npmLatest?: string | undefined;\n trayLatestSha?: string | undefined;\n trayLatestVersion?: string | undefined;\n },\n prev: RemoteCheck | undefined,\n): Omit<RemoteCheck, 'checkedAt'> {\n const npmLatest = fetched.npmLatest ?? prev?.npmLatest;\n const trayLatestSha = fetched.trayLatestSha ?? prev?.trayLatestSha;\n\n const shaMoved =\n fetched.trayLatestSha !== undefined && fetched.trayLatestSha !== prev?.trayLatestSha;\n const trayLatestVersion =\n fetched.trayLatestVersion ?? (shaMoved ? undefined : prev?.trayLatestVersion);\n\n return {\n ...(npmLatest !== undefined ? { npmLatest } : {}),\n ...(trayLatestSha !== undefined ? { trayLatestSha } : {}),\n ...(trayLatestVersion !== undefined ? { trayLatestVersion } : {}),\n };\n}\n\n/**\n * Kick off the daily remote check if the cache is stale. Returns immediately;\n * the fetches run in the background and persist their result when they land.\n * Callers must NOT await the returned promise on the command's critical path.\n */\nexport function maybeStartRemoteCheck(): Promise<void> | null {\n const state = readUpdateState();\n if (remoteCheckFresh(state)) return null;\n\n const method = detectExecutionMethod({\n userAgent: process.env.npm_config_user_agent,\n argv1: process.argv[1],\n });\n\n const run = async (): Promise<void> => {\n let npmLatest: string | undefined;\n let trayLatestSha: string | undefined;\n let trayLatestVersion: string | undefined;\n if (await updateCheckEnabled()) {\n const channel = await resolveChannel();\n const [npm, tray] = await Promise.all([\n nudgeEligible(method, AGENTBOX_VERSION)\n ? fetchNpmBest(channel)\n : Promise.resolve(undefined),\n trayInstalled() ? fetchTrayBest(channel) : Promise.resolve<TrayProbe>({}),\n ]);\n npmLatest = npm;\n trayLatestSha = tray.sha;\n trayLatestVersion = tray.version;\n }\n // Stamp checkedAt even when disabled or offline — the daily gate must\n // throttle regardless, or every command re-schedules this probe.\n writeUpdateState({\n remoteCheck: {\n checkedAt: new Date().toISOString(),\n ...mergeRemoteCheck(\n { npmLatest, trayLatestSha, trayLatestVersion },\n readUpdateState().remoteCheck,\n ),\n },\n });\n };\n return run().catch(() => undefined);\n}\n\n/**\n * The menu-bar app nudge, or null. Never prompts and never blocks — a stale app\n * is worth one line after the command, not an interruption in the middle of one.\n *\n * `installedVersion` is read off the installed bundle, so this is decided on what\n * is really installed vs what is really published — NOT on the sha stamp, which\n * only exists when this CLI did the install and therefore reported a phantom\n * update forever on a DMG-drag install.\n */\nexport function trayNudgeMessage(\n state: UpdateState,\n installedVersion: string | undefined,\n): string | null {\n const latest = state.remoteCheck?.trayLatestVersion;\n if (!latest || !installedVersion) return null;\n if (!isNewer(latest, installedVersion)) return null;\n return `a newer AgentBox app (${latest}, you have ${installedVersion}) is available — run \\`agentbox install app\\``;\n}\n\n/** The nudge line to print after the command, or null. Reads the cache only. */\nexport function nudgeMessage(\n state: UpdateState,\n method: ExecMethod,\n version: string = AGENTBOX_VERSION,\n): string | null {\n if (!nudgeEligible(method, version)) return null;\n const latest = state.remoteCheck?.npmLatest;\n if (!isNewer(latest, version)) return null;\n // On the nightly channel the newest build is regularly a plain release that\n // supersedes the nightlies before it. `0.28.0` offered to someone running\n // `0.28.0-nightly.5` reads like a downgrade without this hint.\n const crossover = isPrerelease(version) && !isPrerelease(latest as string);\n const what = crossover ? `${latest as string}, the stable release` : (latest as string);\n return `a newer agentbox (${what}) is available — run \\`agentbox self-update\\``;\n}\n","import { realpathSync } from 'node:fs';\n\nexport type ExecMethod = 'npx' | 'pnpm' | 'npm' | 'direct';\n\nexport interface ExecMethodInput {\n /** `process.env.npm_config_user_agent` (or undefined). */\n userAgent?: string | undefined;\n /** `process.argv[1]` — the resolved bin path. */\n argv1?: string | undefined;\n}\n\n/**\n * Classify how this CLI was launched. The signals npm/pnpm/npx leave behind:\n *\n * - npx writes the bin into a `_npx` cache dir and tags the user-agent with\n * `npm/<v> ... npx/<v>` — so the argv path or the user-agent gives it away.\n * - pnpm sets `npm_config_user_agent` starting with `pnpm/` (when invoked\n * through pnpm, e.g. `pnpm exec`).\n * - npm sets it starting with `npm/` (when invoked through npm).\n * - a **global install invoked straight from the shell** — the common case —\n * carries NO user-agent, and argv[1] is the bin *symlink* (e.g.\n * `/usr/local/bin/agentbox`). Resolving the symlink reveals where the\n * package really lives: npm globals under `<prefix>/lib/node_modules/`,\n * pnpm globals inside a `/.pnpm/` store.\n * - anything else (a dev clone run as `node dist/index.js`, a hand-made\n * symlink into a checkout) → `direct`.\n *\n * npx is checked first because its user-agent also contains `npm/`.\n */\nexport function detectExecutionMethod(input: ExecMethodInput): ExecMethod {\n const ua = input.userAgent ?? '';\n const argv1 = input.argv1 ?? '';\n\n if (argv1.includes('/_npx/') || argv1.includes('/.npm/_npx') || /\\bnpx\\//.test(ua)) {\n return 'npx';\n }\n if (/\\bpnpm\\//.test(ua)) {\n return 'pnpm';\n }\n if (/\\bnpm\\//.test(ua)) {\n return 'npm';\n }\n\n let real = argv1;\n try {\n real = realpathSync(argv1);\n } catch {\n // Missing/synthetic path (unit tests, unusual launchers) — classify on\n // the literal path instead.\n }\n // pnpm's global dir is project-shaped (<PNPM_HOME>/global/5/node_modules/\n // .pnpm/...), so its store segment looks exactly like a project-local\n // dependency's — match the global dir itself, not the .pnpm store. A\n // project-local install (node_modules/.bin shim, local .pnpm store, or a\n // custom PNPM_HOME we can't recognize) stays `direct`: self-update must\n // skip the package step there, never run a global add over a local dep.\n if (real.includes('/pnpm/global/')) {\n return 'pnpm';\n }\n if (real.includes('/lib/node_modules/')) {\n return 'npm';\n }\n return 'direct';\n}\n","/**\n * Build-time injected CLI version constants. tsup's `define` (apps/cli/tsup.config.ts)\n * replaces these identifiers at bundle time:\n *\n * __AGENTBOX_VERSION__ ← apps/cli/package.json `version`\n * __AGENTBOX_COMMIT__ ← `git rev-parse --short HEAD` at build time\n *\n * The `declare` lines below are for the typecheck of the unbundled source —\n * tsup substitutes the literals before esbuild ever sees this file. The\n * `?? '...'` fallbacks cover the unbundled dev case (running `tsx src/index.ts`\n * before `pnpm build` populates the defines).\n */\n\ndeclare const __AGENTBOX_VERSION__: string | undefined;\ndeclare const __AGENTBOX_COMMIT__: string | undefined;\n\nexport const AGENTBOX_VERSION: string =\n typeof __AGENTBOX_VERSION__ === 'string' ? __AGENTBOX_VERSION__ : '0.0.0-dev';\n\nexport const AGENTBOX_COMMIT: string =\n typeof __AGENTBOX_COMMIT__ === 'string' ? __AGENTBOX_COMMIT__ : 'dev';\n","/**\n * `agentbox install app` — install the AgentBox macOS menu-bar app.\n *\n * The app is distributed separately (it's macOS-only, and keeps this cross-platform CLI small):\n * a signed+notarized `AgentBox.zip` is published to the public `madarco/agentbox` repo under the\n * moving `tray-latest` release. This command downloads it, verifies its SHA-256, unpacks it into\n * `/Applications` with `ditto` (which preserves the signature + stapled notarization ticket), and\n * launches it. macOS-only; a clean no-op elsewhere.\n *\n * Humans who prefer no CLI can instead download `AgentBox.dmg` from the same release and drag it\n * to Applications.\n */\n\nimport { intro, log, outro } from '@clack/prompts';\nimport { Command } from 'commander';\nimport { execa } from 'execa';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport {\n STABLE_TRAY_TAG,\n bestOf,\n resolveChannel,\n trayReleaseTags,\n type TaggedVersion,\n type UpdateChannel,\n} from '../lib/channel.js';\nimport { isNewer } from '../lib/semver-lite.js';\nimport { writeUpdateState } from '../lib/update-state.js';\n\nexport const APP_NAME = 'AgentBox';\nexport const APP_PATH = `/Applications/${APP_NAME}.app`;\n/** Unified-logging subsystem the app logs under (see the app's `Diagnostics/Log.swift`). */\nexport const APP_BUNDLE_ID = 'com.madarco.agentbox-tray';\n\n// The app was renamed AgentBoxTray.app → AgentBox.app but kept its bundle id. A leftover old bundle\n// would collide (two bundles, one id), so remove it on install/uninstall. `agentbox app` also uses\n// LEGACY_APP_NAME so status/stop/restart still see a stray pre-rename process during migration.\nexport const LEGACY_APP_NAME = 'AgentBoxTray';\nconst LEGACY_APP_PATH = `/Applications/${LEGACY_APP_NAME}.app`;\n\n// Overridable for forks/testing; default is the public agentbox repo's moving tray release.\nconst RELEASE_BASE =\n process.env.AGENTBOX_TRAY_RELEASE_BASE ?? 'https://github.com/madarco/agentbox/releases/download';\nconst DEFAULT_TAG = STABLE_TRAY_TAG;\n\n/**\n * Which tray release to install for `channel`. Stable is the tag itself — no\n * probe, so its behavior is unchanged. Nightly compares the published version of\n * both releases and takes the greater, so a tray-only *stable* release reaches\n * nightly testers without anyone cutting a nightly tray build.\n *\n * Returns null when nothing comparable came back (offline, or a release predating\n * `version.json`); callers fall back to {@link DEFAULT_TAG}.\n */\nexport async function bestTrayRelease(channel: UpdateChannel): Promise<TaggedVersion | null> {\n if (channel === 'stable') return null;\n const found = await Promise.all(\n trayReleaseTags(channel).map(async (tag) => ({\n tag,\n version: await fetchTrayLatestVersion(tag),\n })),\n );\n return bestOf(found);\n}\n\nexport interface InstallTrayResult {\n ran: boolean;\n reason?: string;\n}\n\nexport interface InstallTrayOptions {\n uninstall?: boolean;\n quiet?: boolean;\n /** Install a local zip instead of downloading (dev/offline). */\n zip?: string;\n /** Release tag to download from (default `tray-latest`; e.g. `tray-v0.1.0`). */\n tag?: string;\n}\n\n/** Install (or uninstall) the tray app. Reusable from the setup wizard. */\nexport async function installTray(opts: InstallTrayOptions = {}): Promise<InstallTrayResult> {\n const say = (msg: string) => {\n if (!opts.quiet) log.info(msg);\n };\n\n if (process.platform !== 'darwin') {\n say('The AgentBox menu-bar app is macOS-only — skipping.');\n return { ran: false, reason: 'not-macos' };\n }\n\n // Quit any running instance (new + legacy name) so we can replace the bundle cleanly.\n await execa('pkill', ['-x', APP_NAME]).catch(() => undefined);\n await execa('pkill', ['-x', LEGACY_APP_NAME]).catch(() => undefined);\n\n if (opts.uninstall) {\n if (existsSync(APP_PATH)) rmSync(APP_PATH, { recursive: true, force: true });\n // Also remove a leftover pre-rename bundle.\n if (existsSync(LEGACY_APP_PATH)) rmSync(LEGACY_APP_PATH, { recursive: true, force: true });\n writeUpdateState({ traySha: undefined });\n say(`Removed ${APP_PATH}. (Launch-at-login is unregistered by the app itself.)`);\n return { ran: true };\n }\n\n // Resolve the zip: a local path (--zip) or a fresh download from the release.\n let zip: string;\n let sha: string | undefined;\n let scratch: string | null = null;\n if (opts.zip) {\n if (!existsSync(opts.zip)) {\n say(`No zip at ${opts.zip}.`);\n return { ran: false, reason: 'zip-missing' };\n }\n zip = opts.zip;\n sha = createHash('sha256').update(readFileSync(zip)).digest('hex');\n } else {\n scratch = mkdtempSync(join(tmpdir(), 'agentbox-tray-'));\n const tag = opts.tag ?? (await bestTrayRelease(await resolveChannel()))?.tag ?? DEFAULT_TAG;\n try {\n ({ zipPath: zip, sha } = await downloadAndVerify(tag, scratch, say));\n } catch (err) {\n rmSync(scratch, { recursive: true, force: true });\n say(`Download failed: ${err instanceof Error ? err.message : String(err)}`);\n return { ran: false, reason: 'download-failed' };\n }\n }\n\n try {\n // Replace any existing copy, extract with ditto (preserves signature + notarization ticket).\n if (existsSync(APP_PATH)) rmSync(APP_PATH, { recursive: true, force: true });\n await execa('ditto', ['-x', '-k', zip, '/Applications']);\n // Only now that AgentBox.app is in place, remove a leftover pre-rename bundle so the two never\n // coexist (same id). Doing it here — not earlier — means a failed download/extract can't strand\n // a user who only had the old bundle.\n if (existsSync(LEGACY_APP_PATH)) rmSync(LEGACY_APP_PATH, { recursive: true, force: true });\n // Belt-and-suspenders: clear any quarantine bit so Gatekeeper never blocks the download.\n await execa('xattr', ['-dr', 'com.apple.quarantine', APP_PATH]).catch(() => undefined);\n // Record which zip is now installed so refresh flows can compare the\n // release's ~80-byte .sha256 sidecar instead of re-downloading the app.\n writeUpdateState({ traySha: sha });\n await launchTray(say);\n } finally {\n if (scratch) rmSync(scratch, { recursive: true, force: true });\n }\n\n say(`Installed ${APP_PATH} and launched it (look for the box icon in the menu bar).`);\n return { ran: true };\n}\n\n/** Tray-app presence check shared by the update paths. */\nexport function trayInstalled(): boolean {\n return process.platform === 'darwin' && existsSync(APP_PATH);\n}\n\n/**\n * Fetch only the release's `AgentBox.zip.sha256` sidecar (~80 bytes) and\n * return the hex digest, or undefined on any failure. Short timeout — this\n * runs inside refresh flows and the daily background check, never on a\n * command's critical path.\n */\nexport async function fetchTraySidecarSha(tag: string = DEFAULT_TAG): Promise<string | undefined> {\n try {\n const { stdout } = await execa('curl', [\n '-fsSL',\n '--max-time',\n '5',\n `${RELEASE_BASE}/${tag}/${APP_NAME}.zip.sha256`,\n ]);\n return parseSidecarSha(stdout);\n } catch {\n return undefined;\n }\n}\n\n/** Parse the `shasum` sidecar format: \"<hex> AgentBox.zip\". */\nexport function parseSidecarSha(body: string): string | undefined {\n const first = body.trim().split(/\\s+/)[0]?.toLowerCase();\n return first && /^[0-9a-f]{64}$/.test(first) ? first : undefined;\n}\n\n/**\n * Fetch the release's `version.json` manifest — the published tray version, as\n * data rather than as prose in the release title. Display only: the sha\n * sidecar still decides whether to install. Releases predating the manifest\n * 404 here, so every caller must tolerate `undefined`.\n */\nexport async function fetchTrayLatestVersion(\n tag: string = DEFAULT_TAG,\n): Promise<string | undefined> {\n try {\n const { stdout } = await execa('curl', [\n '-fsSL',\n '--max-time',\n '5',\n `${RELEASE_BASE}/${tag}/version.json`,\n ]);\n return parseVersionManifest(stdout);\n } catch {\n return undefined;\n }\n}\n\n/** Parse `version.json` → the version string, or undefined if malformed. */\nexport function parseVersionManifest(body: string): string | undefined {\n try {\n const parsed = JSON.parse(body) as { version?: unknown };\n return typeof parsed.version === 'string' && parsed.version !== '' ? parsed.version : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface TrayUpdateDecision {\n update: boolean;\n reason:\n | 'not-installed'\n | 'no-latest-sha'\n | 'no-stamp'\n | 'mismatch'\n | 'older-version'\n | 'up-to-date';\n}\n\n/**\n * Pure decision: reinstall only when the published sha differs from the\n * stamped one. A missing stamp with the app installed reads as update-needed\n * once (self-heals installs that predate sha stamping). An unknown latest sha\n * (offline, release missing) never triggers a download.\n */\nexport function decideTrayUpdate(input: {\n installed: boolean;\n stampedSha: string | undefined;\n latestSha: string | undefined;\n /** `CFBundleShortVersionString` of the app on disk — ground truth. */\n installedVersion?: string | undefined;\n /** `version` from the release's version.json. */\n latestVersion?: string | undefined;\n}): TrayUpdateDecision {\n if (!input.installed) return { update: false, reason: 'not-installed' };\n\n // Prefer the ACTUAL versions over the sha stamp. The stamp only exists if *this*\n // CLI did the install, so a DMG-drag install (or one predating stamping) has no\n // stamp and used to read as \"update available\" forever, even on the newest app.\n // Comparing what is really installed against what is really published cannot lie.\n const { installedVersion, latestVersion } = input;\n if (\n installedVersion !== undefined &&\n latestVersion !== undefined &&\n isReleaseVersion(installedVersion) &&\n isReleaseVersion(latestVersion)\n ) {\n return isNewer(latestVersion, installedVersion)\n ? { update: true, reason: 'older-version' }\n : { update: false, reason: 'up-to-date' };\n }\n\n // Fall back to the sha stamp when a version is unreadable (no manifest on the\n // release, unparseable plist).\n if (input.latestSha === undefined) return { update: false, reason: 'no-latest-sha' };\n if (input.stampedSha === undefined) return { update: true, reason: 'no-stamp' };\n if (input.stampedSha !== input.latestSha) return { update: true, reason: 'mismatch' };\n return { update: false, reason: 'up-to-date' };\n}\n\nexport interface TrayBounceDecision {\n bounce: boolean;\n reason: 'not-installed' | 'just-reinstalled' | 'not-running' | 'install-failed' | 'stale-row';\n}\n\n/**\n * Pure decision: should the post-update refresh restart the menu-bar app?\n *\n * It must, because the app reads the installed CLI version **once, at launch** and only\n * re-derives its \"Update available — agentbox X\" row on a 24h-throttled check. After a CLI\n * self-update the running app therefore keeps advertising the version the user just installed,\n * for up to a day. Restarting it is the only way to clear that from this side — the app has no\n * reload signal (no notification, no file watch, no URL scheme).\n */\nexport function decideTrayBounce(input: {\n /** The bundle is on disk. */\n installed: boolean;\n /** The app had a live pid BEFORE the tray-update step — which kills it. */\n running: boolean;\n /** `installTray` was called (it pkills unconditionally, before deciding anything). */\n installAttempted: boolean;\n /** `installTray` succeeded — it relaunches the app itself. */\n reinstalled: boolean;\n}): TrayBounceDecision {\n if (!input.installed) return { bounce: false, reason: 'not-installed' };\n if (input.reinstalled) return { bounce: false, reason: 'just-reinstalled' };\n // `installTray` pkills the app before it knows whether it can install; its\n // zip-missing / download-failed paths then return without relaunching. Bring\n // the app back rather than leaving the user with no menu bar.\n if (input.installAttempted) return { bounce: true, reason: 'install-failed' };\n // Never launch an app the user deliberately quit.\n if (!input.running) return { bounce: false, reason: 'not-running' };\n return { bounce: true, reason: 'stale-row' };\n}\n\n/** A real published version we can compare — excludes `0.0.0`/unparseable. */\nfunction isReleaseVersion(v: string): boolean {\n const core = v.split('-', 1)[0] ?? v;\n const parts = core.split('.');\n return parts.length === 3 && parts.every((p) => /^\\d+$/.test(p)) && core !== '0.0.0';\n}\n\n/**\n * The version of the app actually installed at `/Applications/AgentBox.app`, or\n * undefined when it isn't there / the plist can't be read. `plutil` handles both\n * XML and binary plists; the app is macOS-only, so this is safe to shell.\n */\nexport async function readInstalledTrayVersion(): Promise<string | undefined> {\n if (!trayInstalled()) return undefined;\n try {\n const { stdout } = await execa('plutil', [\n '-extract',\n 'CFBundleShortVersionString',\n 'raw',\n '-o',\n '-',\n join(APP_PATH, 'Contents', 'Info.plist'),\n ]);\n const v = stdout.trim();\n return v.length > 0 ? v : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** PIDs of a process by exact executable name, or [] if none. `pgrep` exits 1 when nothing matches. */\nasync function pidsForName(name: string): Promise<number[]> {\n const res = await execa('pgrep', ['-x', name]).catch(() => null);\n if (!res) return [];\n return res.stdout\n .split('\\n')\n .map((l) => Number(l.trim()))\n .filter((n) => Number.isInteger(n) && n > 0);\n}\n\n/**\n * PIDs of the running app, or [] if none. Covers both the current (`AgentBox`) and the legacy\n * pre-rename (`AgentBoxTray`) executable names, so status/stop/restart still see a stray old process\n * during migration.\n */\nexport async function trayPids(): Promise<number[]> {\n const [current, legacy] = await Promise.all([\n pidsForName(APP_NAME),\n pidsForName(LEGACY_APP_NAME),\n ]);\n return [...current, ...legacy];\n}\n\n/** True while the tray process is running. */\nexport async function trayRunning(): Promise<boolean> {\n return (await trayPids()).length > 0;\n}\n\nexport async function stopTray(): Promise<void> {\n // `pkill` exits 1 when there was nothing to kill — not an error for us. Cover the legacy\n // pre-rename name too so `stop`/`restart` don't leave a stray old process alive.\n await execa('pkill', ['-x', APP_NAME]).catch(() => undefined);\n await execa('pkill', ['-x', LEGACY_APP_NAME]).catch(() => undefined);\n}\n\n/**\n * Launch the app and confirm it actually came up. `open` returns before an\n * `LSUIElement` menu-bar app finishes registering, and right after a `ditto` extract Launch Services\n * can briefly not resolve the new bundle — so poll, then retry `open` once before giving up.\n * (Launch-at-login stays opt-in via the app's Settings; this only covers the post-install start.)\n */\nexport async function launchTray(say: (m: string) => void): Promise<void> {\n await execa('open', [APP_PATH]).catch(() => undefined);\n for (let i = 0; i < 6; i++) {\n if (await trayRunning()) return;\n await delay(500);\n }\n await execa('open', [APP_PATH]).catch(() => undefined);\n if (!(await trayRunning())) {\n say(`The menu-bar app did not start automatically — launch it from ${APP_PATH}.`);\n }\n}\n\n/**\n * Quit the app and bring it back. The wait matters: `open` on a still-quitting instance just\n * foregrounds the dying process, so the \"restart\" silently becomes a no-op.\n */\nexport async function restartTray(say: (m: string) => void): Promise<void> {\n await stopTray();\n for (let i = 0; i < 20 && (await trayPids()).length > 0; i++) await delay(100);\n await launchTray(say);\n}\n\n/** Download `<tag>/AgentBox.zip` + its `.sha256`, verify, and return the local zip path + sha. */\nasync function downloadAndVerify(\n tag: string,\n dir: string,\n say: (m: string) => void,\n): Promise<{ zipPath: string; sha: string }> {\n const base = `${RELEASE_BASE}/${tag}`;\n const zipPath = join(dir, `${APP_NAME}.zip`);\n const shaPath = join(dir, `${APP_NAME}.zip.sha256`);\n\n say(`Downloading ${APP_NAME} (${tag})…`);\n await execa('curl', ['-fSL', '-o', zipPath, `${base}/${APP_NAME}.zip`]);\n await execa('curl', ['-fSL', '-o', shaPath, `${base}/${APP_NAME}.zip.sha256`]);\n\n const expected = parseSidecarSha(readFileSync(shaPath, 'utf8'));\n const actual = createHash('sha256').update(readFileSync(zipPath)).digest('hex');\n if (!expected || expected !== actual) {\n throw new Error(`checksum mismatch (expected ${expected ?? 'none'}, got ${actual})`);\n }\n return { zipPath, sha: actual };\n}\n\nexport const installAppCommand = new Command('app')\n .description('Download and install the AgentBox macOS menu-bar app into /Applications')\n .option('--uninstall', 'quit and remove the menu-bar app')\n .option('--tag <tag>', 'release tag to install from (default: tray-latest)')\n .option('--zip <path>', 'install a local AgentBox.zip instead of downloading')\n .action(async (opts: { uninstall?: boolean; tag?: string; zip?: string }) => {\n intro(opts.uninstall ? 'Removing the AgentBox app…' : 'Installing the AgentBox app…');\n const res = await installTray(opts);\n outro(res.ran ? 'Done' : `Skipped (${res.reason ?? 'nothing to do'})`);\n if (!res.ran && res.reason && res.reason !== 'not-macos') process.exitCode = 1;\n });\n","/**\n * Release channels: `stable` (the default) and `nightly` (pre-release builds cut\n * from the `nightly` branch so testers can exercise a big feature before it\n * ships). Full design in docs/nightly-channel-plan.md.\n *\n * Two rules carry the whole thing:\n *\n * 1. **Nightly means \"the newest build, prerelease or not\"** — a nightly user\n * polls BOTH dist-tags and takes whichever version is greater. Since a\n * nightly is named for the release it precedes (`0.28.0-nightly.<stamp>`),\n * semver hands us the priority for free: `0.28.0` outranks every nightly\n * before it, so a stable release reaches nightly testers with no second\n * publish under the `nightly` tag. Stable users only ever see `latest` and\n * keep paying exactly one probe per component.\n *\n * 2. **Membership is sticky once joined.** Deriving the channel from the running\n * version (a `-nightly.` suffix means nightly) is what makes\n * `npm i -g @madarco/agentbox@nightly` self-sustaining with no config step.\n * But rule 1 eventually hands a tester a *stable* build with no suffix, which\n * would derive `stable` on the next launch and silently undo the opt-in — so\n * the resolved channel gets persisted to `update.channel`.\n */\n\nimport {\n GLOBAL_CONFIG_FILE,\n loadEffectiveConfig,\n parseUserConfig,\n setConfigValue,\n} from '@agentbox/config';\nimport { readFile } from 'node:fs/promises';\nimport { compareSemver } from './semver-lite.js';\nimport { AGENTBOX_VERSION } from '../version.js';\n\nexport type UpdateChannel = 'stable' | 'nightly';\n\n/** What `update.channel` may hold. `auto` defers to the running build. */\nexport type ChannelSetting = 'auto' | UpdateChannel;\n\n/**\n * The prerelease marker that makes a build a nightly. Matched as a substring of\n * the prerelease part rather than parsed, so `0.28.0-nightly.202607251430`\n * classifies without this module needing to know the stamp format.\n */\nconst NIGHTLY_MARKER = '-nightly.';\n\nexport const NPM_PACKAGE = '@madarco/agentbox';\nexport const STABLE_DIST_TAG = 'latest';\nexport const NIGHTLY_DIST_TAG = 'nightly';\nexport const STABLE_TRAY_TAG = 'tray-latest';\nexport const NIGHTLY_TRAY_TAG = 'tray-nightly';\n\n/** The channel a version string belongs to, by its own shape. */\nexport function channelOfVersion(version: string): UpdateChannel {\n return version.includes(NIGHTLY_MARKER) ? 'nightly' : 'stable';\n}\n\n/** True for a version that carries a prerelease suffix of any kind. */\nexport function isPrerelease(version: string): boolean {\n const core = version.split('+', 1)[0] ?? version;\n return core.includes('-');\n}\n\n/**\n * npm dist-tags to poll, most-authoritative last. Nightly includes `latest`\n * because a shipped release outranks the nightlies that preceded it (rule 1).\n */\nexport function npmDistTags(channel: UpdateChannel): string[] {\n return channel === 'nightly' ? [STABLE_DIST_TAG, NIGHTLY_DIST_TAG] : [STABLE_DIST_TAG];\n}\n\n/** Tray release tags to poll. Same rule as {@link npmDistTags}. */\nexport function trayReleaseTags(channel: UpdateChannel): string[] {\n return channel === 'nightly' ? [STABLE_TRAY_TAG, NIGHTLY_TRAY_TAG] : [STABLE_TRAY_TAG];\n}\n\nexport interface TaggedVersion {\n tag: string;\n version: string;\n}\n\n/**\n * The greatest candidate by semver, carrying the tag it came from — callers need\n * to know WHERE the winner lives (`install app` downloads from that tag), not\n * just that one exists.\n *\n * Candidates that failed to fetch (`version: undefined`) or aren't comparable\n * are skipped. Ties keep the earlier candidate, so `npmDistTags`' ordering makes\n * `latest` win a tie against `nightly` — the same version published under both\n * tags should read as stable.\n */\nexport function bestOf(\n candidates: { tag: string; version?: string | undefined }[],\n): TaggedVersion | null {\n let best: TaggedVersion | null = null;\n for (const c of candidates) {\n if (c.version === undefined) continue;\n if (best === null) {\n // Guard the first candidate too: an uncomparable string (a dev sentinel, a\n // proxy's error page) must not become the winner by arriving first.\n if (compareSemver(c.version, c.version) === null) continue;\n best = { tag: c.tag, version: c.version };\n continue;\n }\n if (compareSemver(c.version, best.version) === 1) best = { tag: c.tag, version: c.version };\n }\n return best;\n}\n\n/**\n * The `update.channel` setting, or `auto` when unset/unreadable.\n *\n * Mirrors `updateCheckEnabled()`'s fallback: the layered load throws for reasons\n * unrelated to this key (a project config carrying keys from a provider plugin\n * the stock registry doesn't know), and that must not silently flip a nightly\n * tester back to stable — so fall back to the global file alone.\n */\nexport async function channelSetting(): Promise<ChannelSetting> {\n try {\n const cfg = await loadEffectiveConfig(process.cwd());\n return cfg.effective.update.channel;\n } catch {\n try {\n const raw = await readFile(GLOBAL_CONFIG_FILE, 'utf8');\n return parseUserConfig(raw, GLOBAL_CONFIG_FILE).update?.channel ?? 'auto';\n } catch {\n return 'auto';\n }\n }\n}\n\n/**\n * The channel decision, pure. An explicit setting wins; `auto` falls back to the\n * running build's shape.\n *\n * Split out from {@link resolveChannel} so it can be unit-tested: the config read\n * resolves `GLOBAL_CONFIG_FILE` at import time from the real `$HOME`, and\n * apps/cli tests have no HOME isolation.\n */\nexport function effectiveChannel(setting: ChannelSetting, version: string): UpdateChannel {\n return setting === 'auto' ? channelOfVersion(version) : setting;\n}\n\n/** The effective channel for this process. */\nexport async function resolveChannel(version: string = AGENTBOX_VERSION): Promise<UpdateChannel> {\n return effectiveChannel(await channelSetting(), version);\n}\n\n/**\n * Pin the channel in the global config so it survives a version that no longer\n * carries the marker (rule 2). Best-effort: failing to record membership must\n * never abort an update the user asked for.\n */\nexport async function persistChannel(channel: UpdateChannel): Promise<boolean> {\n try {\n await setConfigValue('global', 'update.channel', channel, process.cwd());\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Minimal semver comparison for the npm update nudge and the tray-app version\n * compare. Dependency-free on purpose — this runs on the CLI's startup path.\n *\n * Prerelease ordering is NOT optional here: the nightly channel publishes\n * `0.28.0-nightly.<stamp>` versions, and the whole channel design rests on two\n * comparisons this file has to get right —\n *\n * 0.28.0-nightly.6 > 0.28.0-nightly.5 (a newer nightly supersedes an older one)\n * 0.28.0 > 0.28.0-nightly.6 (the release supersedes every nightly before it)\n *\n * The second is what lets a stable release reach nightly testers automatically.\n * Get either wrong and nothing errors — testers just silently stop receiving\n * updates. See docs/nightly-channel-plan.md.\n *\n * Build metadata (`+sha`) is ignored, per the spec: it carries no precedence.\n *\n * `0.0.0` is the dev-build sentinel (`0.0.0-dev`, set when the CLI runs from a\n * checkout) and is deliberately treated as UNCOMPARABLE rather than as the\n * lowest version, so a dev build never reads as newer *or* older than a\n * release. `install-app.ts`'s `isReleaseVersion` and the tray's Swift mirror\n * carry the same exclusion.\n */\n\nconst VERSION = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/;\n\ninterface Parsed {\n core: [number, number, number];\n /** Dot-separated prerelease identifiers; empty for a plain release. */\n pre: string[];\n}\n\nfunction parse(v: string): Parsed | null {\n const m = VERSION.exec(v.trim());\n if (!m) return null;\n const core: [number, number, number] = [Number(m[1]), Number(m[2]), Number(m[3])];\n if (core[0] === 0 && core[1] === 0 && core[2] === 0) return null; // dev sentinel\n const raw = m[4];\n const pre = raw === undefined || raw === '' ? [] : raw.split('.');\n if (pre.some((id) => id === '')) return null; // \"1.2.3-a..b\" is not valid semver\n return { core, pre };\n}\n\n/**\n * Semver identifier precedence: numeric identifiers compare numerically,\n * everything else ASCII-lexically, and a numeric identifier always ranks BELOW\n * an alphanumeric one.\n */\nfunction compareIdentifiers(a: string, b: string): -1 | 0 | 1 {\n const aNum = /^\\d+$/.test(a);\n const bNum = /^\\d+$/.test(b);\n if (aNum && bNum) {\n const na = Number(a);\n const nb = Number(b);\n return na < nb ? -1 : na > nb ? 1 : 0;\n }\n if (aNum) return -1;\n if (bNum) return 1;\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** -1 / 0 / 1, or null when either side isn't a comparable version. */\nexport function compareSemver(a: string, b: string): -1 | 0 | 1 | null {\n const pa = parse(a);\n const pb = parse(b);\n if (!pa || !pb) return null;\n\n for (let i = 0; i < 3; i++) {\n const ai = pa.core[i] as number;\n const bi = pb.core[i] as number;\n if (ai < bi) return -1;\n if (ai > bi) return 1;\n }\n\n // Equal cores: a release outranks any prerelease of the same version.\n if (pa.pre.length === 0 && pb.pre.length === 0) return 0;\n if (pa.pre.length === 0) return 1;\n if (pb.pre.length === 0) return -1;\n\n const shared = Math.min(pa.pre.length, pb.pre.length);\n for (let i = 0; i < shared; i++) {\n const c = compareIdentifiers(pa.pre[i] as string, pb.pre[i] as string);\n if (c !== 0) return c;\n }\n // A longer identifier list wins when it shares the shorter one's prefix.\n return pa.pre.length < pb.pre.length ? -1 : pa.pre.length > pb.pre.length ? 1 : 0;\n}\n\n/** True when `latest` is a strictly newer release than `current`. */\nexport function isNewer(latest: string | undefined, current: string): boolean {\n if (latest === undefined) return false;\n return compareSemver(latest, current) === 1;\n}\n","/**\n * `~/.agentbox/update-state.json` — one stamp file for all update machinery:\n * the last CLI version the user acknowledged (drives the \"you updated —\n * refresh now?\" prompt in `index.ts`), the sha256 of the installed tray-app\n * zip (drives the sidecar-compare in `install-app.ts`), and the daily\n * remote-check cache (the ONLY place the CLI touches the network outside an\n * explicit install/update command).\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nconst STATE_VERSION = 1 as const;\n\n/** Result of the daily remote check. `checkedAt` gates re-checking (24h). */\nexport interface RemoteCheck {\n checkedAt: string;\n npmLatest?: string;\n trayLatestSha?: string;\n /** Published tray version, for display only — the sha decides the install. */\n trayLatestVersion?: string;\n}\n\nexport interface UpdateState {\n version: typeof STATE_VERSION;\n /** CLI version last acknowledged (refresh completed or prompt declined). */\n lastRunVersion?: string;\n /** sha256 of the AgentBox.zip the installed tray app came from. */\n traySha?: string;\n remoteCheck?: RemoteCheck;\n}\n\nexport function updateStatePath(): string {\n return join(homedir(), '.agentbox', 'update-state.json');\n}\n\nexport function readUpdateState(): UpdateState {\n const path = updateStatePath();\n if (!existsSync(path)) return { version: STATE_VERSION };\n try {\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<UpdateState>;\n const state: UpdateState = { version: STATE_VERSION };\n if (typeof parsed.lastRunVersion === 'string') state.lastRunVersion = parsed.lastRunVersion;\n if (typeof parsed.traySha === 'string') state.traySha = parsed.traySha;\n if (\n parsed.remoteCheck !== undefined &&\n typeof parsed.remoteCheck === 'object' &&\n typeof parsed.remoteCheck.checkedAt === 'string'\n ) {\n state.remoteCheck = {\n checkedAt: parsed.remoteCheck.checkedAt,\n ...(typeof parsed.remoteCheck.npmLatest === 'string'\n ? { npmLatest: parsed.remoteCheck.npmLatest }\n : {}),\n ...(typeof parsed.remoteCheck.trayLatestSha === 'string'\n ? { trayLatestSha: parsed.remoteCheck.trayLatestSha }\n : {}),\n ...(typeof parsed.remoteCheck.trayLatestVersion === 'string'\n ? { trayLatestVersion: parsed.remoteCheck.trayLatestVersion }\n : {}),\n };\n }\n return state;\n } catch {\n // Corrupt/unreadable — treat as fresh rather than breaking every command.\n return { version: STATE_VERSION };\n }\n}\n\n/**\n * Read-merge-write so concurrent writers (startup hook, tray install,\n * background remote check) don't clobber each other's fields. Pass an\n * explicit `undefined` value to delete a field.\n */\nexport function writeUpdateState(\n patch: Partial<Omit<UpdateState, 'version'>>,\n): UpdateState {\n const state = readUpdateState();\n const merged: UpdateState = { ...state, ...patch, version: STATE_VERSION };\n for (const key of Object.keys(merged) as (keyof UpdateState)[]) {\n if (merged[key] === undefined) delete merged[key];\n }\n const path = updateStatePath();\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(merged, null, 2) + '\\n');\n return merged;\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/** True while the cached remote check is younger than 24h — no network then. */\nexport function remoteCheckFresh(state: UpdateState, now: Date = new Date()): boolean {\n const at = state.remoteCheck?.checkedAt;\n if (at === undefined) return false;\n const t = Date.parse(at);\n if (Number.isNaN(t)) return false;\n // A future timestamp (clock skew, hand-edited file) also reads as fresh\n // until it ages out; treat anything > 24h in the future as stale instead.\n return now.getTime() - t < DAY_MS && t - now.getTime() < DAY_MS;\n}\n","/**\n * `agentbox hub expose` — upgrade the ONE local hub into the control box.\n *\n * The control box is not a second machine: it is the same `apps/hub` process\n * `agentbox hub` already spawns, flipped to the deployed `hetzner` profile\n * (password auth + SQLite store + resident create worker) and made reachable to\n * boxes. This module owns the flip: assemble the deploy record, (optionally)\n * bring up a tunnel, write the record, restart the hub in exposed mode, and\n * point the CLI at it. `ensureHub()` reads the record back on every start, so\n * autostart / restart reconstruct the mode from disk — nothing here has to run\n * again for the hub to come back exposed.\n *\n * Precondition: `~/.agentbox/control-plane/control-plane.env` already carries\n * the admin token, API key, git credential AND the auth block (secret + admin\n * login) — the command layer mints those (`ensureControlPlaneEnv` +\n * `ensureLocalHubAuth`) before calling in here, so this stays UI-free.\n */\nimport { networkInterfaces } from 'node:os';\nimport { setConfigValue, unsetConfigValue } from '@agentbox/config';\nimport {\n buildExposedHubEnv,\n ensureHub,\n getHubStatus,\n relayPort,\n stopHub,\n type ControlPlaneDeployRecord,\n type HubEndpoint,\n} from '@agentbox/sandbox-core';\nimport { detectEgressIp } from '@agentbox/sandbox-hetzner';\nimport { AGENTBOX_VERSION } from '../version.js';\nimport { readControlPlaneEnvMap, setControlPlaneEnvKey } from './env-file.js';\nimport { persistDeployRecord, purgeLocalControlPlaneState } from './deploy-hetzner.js';\nimport { startTunnel, stopTunnel, type TunnelKind } from './tunnel.js';\nimport { installAutostart, removeAutostart, type AutostartResult } from '../lib/autostart.js';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\nconst CP_DIR = join(homedir(), '.agentbox', 'control-plane');\n\nexport interface ExposeOptions {\n /** Bind address: `0.0.0.0` (LAN, default) or `127.0.0.1` (loopback + tunnel only). */\n bind?: string;\n port?: number;\n tunnel?: TunnelKind;\n /** Named Cloudflare tunnel token (stable hostname). Stored in control-plane.env. */\n tunnelToken?: string;\n /** Supply the box-facing URL yourself (own proxy/DNS); skips tunnel URL scraping. */\n publicUrl?: string;\n autostart?: boolean;\n onLog?: (line: string) => void;\n}\n\nexport interface ExposeResult {\n endpoint: HubEndpoint;\n record: ControlPlaneDeployRecord;\n /** The box-facing URL (LAN or tunnel). */\n publicUrl: string;\n /** The CLI-facing loopback URL (the local shortcut). */\n localUrl: string;\n /** False when a cloud box could NOT reach the hub (loopback-only, no tunnel). */\n cloudReachable: boolean;\n autostart: AutostartResult | null;\n}\n\n/** The first non-internal IPv4 address, or `127.0.0.1` when there is none. */\nexport function detectLanIp(\n ifaces: ReturnType<typeof networkInterfaces> = networkInterfaces(),\n): string {\n for (const addrs of Object.values(ifaces)) {\n for (const a of addrs ?? []) {\n if (a.family === 'IPv4' && !a.internal) return a.address;\n }\n }\n return '127.0.0.1';\n}\n\n/**\n * Resolve the box-facing URL for the requested exposure. Impure only for the\n * tunnel, which is injectable so the ordering is testable.\n *\n * `--tunnel` decides whether a tunnel RUNS; `--public-url` only decides what URL\n * is advertised. Those were conflated: an explicit URL returned before the\n * tunnel was started, so the documented named-Cloudflare flow\n * (`--tunnel cloudflare --tunnel-token X --public-url Y`) wrote the record and\n * reported success with **no tunnel process running** — boxes could not reach\n * the hub until the next `hub start` happened to bring it up.\n */\n/**\n * Reject a tunnel request that cannot possibly work, WITHOUT touching anything.\n *\n * Split out of `resolvePublicUrl` so `runExpose` can check it before it stops the\n * previous tunnel: a typo'd flag combination used to tear down a working tunnel\n * on its way to failing. Pure.\n */\nexport function assertTunnelOptions(opts: ExposeOptions): void {\n // A named tunnel's hostname is configured on Cloudflare's side, so nothing\n // here can discover it — it has to be supplied.\n if (opts.tunnel === 'cloudflare' && opts.tunnelToken && !opts.publicUrl) {\n throw new Error(\n 'a named Cloudflare tunnel (--tunnel-token) has a hostname only you know — pass it with --public-url.',\n );\n }\n}\n\nexport async function resolvePublicUrl(\n opts: ExposeOptions,\n port: number,\n log: (l: string) => void,\n deps: { startTunnel: typeof startTunnel } = { startTunnel },\n): Promise<{ publicUrl: string; cloudReachable: boolean }> {\n const explicit = opts.publicUrl?.replace(/\\/$/, '');\n if (opts.tunnel) {\n assertTunnelOptions(opts);\n const handle = await deps.startTunnel({\n kind: opts.tunnel,\n port,\n ...(opts.tunnelToken ? { token: opts.tunnelToken } : {}),\n onLog: log,\n });\n // An explicit URL wins: for a named tunnel it IS the hostname, and there is\n // nothing useful to scrape.\n return { publicUrl: explicit ?? handle.publicUrl.replace(/\\/$/, ''), cloudReachable: true };\n }\n // No tunnel, but a URL you terminate yourself — reachable, nothing to start.\n if (explicit) return { publicUrl: explicit, cloudReachable: true };\n // Neither: the LAN address (or loopback when bound to 127.0.0.1). A cloud box\n // can't reach either, so cloudReachable is false — the caller warns loudly.\n const bind = opts.bind ?? '0.0.0.0';\n const host = bind === '127.0.0.1' ? '127.0.0.1' : detectLanIp();\n return { publicUrl: `http://${host}:${String(port)}`, cloudReachable: false };\n}\n\n/**\n * Flip this machine's hub into the exposed control box. See the module doc for\n * the precondition on `control-plane.env`.\n */\nexport async function runExpose(opts: ExposeOptions): Promise<ExposeResult> {\n const log = opts.onLog ?? (() => {});\n const port = opts.port ?? relayPort();\n const bind = opts.bind ?? '0.0.0.0';\n\n // A named-tunnel token is a secret, so it rides control-plane.env (not the\n // record) — that's also how a restart re-runs the named tunnel unattended.\n //\n // Written as an upsert-or-REMOVE, not an append: the token has to describe the\n // expose that is happening now. Left behind, it survives\n // `unexpose --keep-credentials`, and a later quick-tunnel expose would then\n // find it on the next `hub start` and bring up a NAMED tunnel on a hostname\n // the record knows nothing about.\n setControlPlaneEnvKey('AGENTBOX_TUNNEL_TOKEN', opts.tunnelToken ?? null);\n\n // Validate first: a bad flag combination must not cost you a working tunnel.\n if (opts.tunnel) assertTunnelOptions(opts);\n\n // Tear down whatever tunnel a previous expose left, before starting the new\n // one. Re-running with `--tunnel` otherwise spawns a second cloudflared over\n // the first; re-running WITHOUT it is worse, because dropping `tunnel` from\n // the record means `stopTunnelIfExposed` never looks again and the old process\n // outlives every command that could have cleaned it up. Idempotent.\n await stopTunnel().catch(() => {});\n\n const { publicUrl, cloudReachable } = await resolvePublicUrl(opts, port, log);\n\n // The admin PC's egress CIDR, so a hetzner box this hub creates still admits\n // SSH from here. Best-effort — a failure just omits it (documented).\n let adminCidr: string | undefined;\n try {\n const ip = await detectEgressIp();\n adminCidr = ip.includes('/') ? ip : `${ip}/32`;\n } catch {\n /* omit — a hetzner box's firewall then won't auto-admit this machine */\n }\n\n const record: ControlPlaneDeployRecord = {\n provider: 'local',\n url: publicUrl,\n publicUrl,\n port,\n bind,\n ...(opts.tunnel ? { tunnel: opts.tunnel } : {}),\n autostart: opts.autostart !== false,\n ...(adminCidr ? { adminCidr } : {}),\n // The build this control box runs IS this CLI's, so record it for\n // `describeRemoteHubBuild` / `hub status`.\n source: { kind: 'package', spec: AGENTBOX_VERSION },\n };\n await persistDeployRecord(record);\n // Wire the config alongside the record, BEFORE the restart. Both describe the\n // intent, and `hub start` can finish the job from them — so a restart that\n // fails leaves a machine that is merely stopped, not one that is half-exposed\n // with a record and a tunnel but no config pointing at either.\n //\n // The box-facing URL is what a locally-created cloud box is told to call home\n // on (relay.controlPlaneUrl keeps its box-facing meaning); the CLI reaches the\n // hub via the loopback local shortcut.\n await setConfigValue('global', 'relay.controlPlaneUrl', publicUrl, homedir());\n log('wrote exposed control-box record');\n\n // Restart cleanly into exposed mode: stop any localhost hub, then ensureHub\n // (which self-resolves the exposed env from the record just written).\n await stopHub();\n const endpoint = await ensureHub({ onLog: log });\n\n let autostart: AutostartResult | null = null;\n if (opts.autostart !== false) {\n autostart = await installAutostart(\n { execPath: process.execPath, cliEntry: process.argv[1] ?? 'agentbox' },\n { logFile: join(homedir(), '.agentbox', 'hub.log') },\n );\n }\n\n // Re-read before reporting. Registering the autostart unit runs it (launchd\n // `RunAtLoad`), and that `hub start` re-establishes the tunnel — which for a\n // quick tunnel means a NEW random hostname written to the record and config.\n // Reporting the URL chosen a moment earlier would print one that no longer\n // resolves, which is the first thing a user copies.\n const settled = (await readLocalRecord()) ?? record;\n return {\n endpoint,\n record: settled,\n publicUrl: settled.publicUrl ?? publicUrl,\n localUrl: `http://127.0.0.1:${String(port)}`,\n cloudReachable,\n autostart,\n };\n}\n\n/**\n * (Re)start the tunnel for an exposed record on `hub start` / autostart, and\n * reconcile a changed ephemeral hostname back into the record + config. No-op\n * when the record has no tunnel. Returns the (possibly updated) record.\n */\nexport async function ensureTunnelForRecord(\n record: ControlPlaneDeployRecord,\n log: (l: string) => void = () => {},\n): Promise<ControlPlaneDeployRecord> {\n if (!record.tunnel) return record;\n const kind = record.tunnel as TunnelKind;\n const env = readControlPlaneEnvMap();\n // Stop whatever is recorded first. This runs on every `hub start` / `restart`\n // / local update, and `hub stop` used to leave the tunnel up — so starting\n // unconditionally spawned a second `cloudflared`, overwrote tunnel.pid with\n // the new one, and orphaned the old process where no teardown could reach it.\n // stopTunnel is idempotent and a no-op when nothing is recorded.\n await stopTunnel().catch(() => {});\n const handle = await startTunnel({\n kind,\n port: record.port ?? relayPort(),\n ...(env.AGENTBOX_TUNNEL_TOKEN ? { token: env.AGENTBOX_TUNNEL_TOKEN } : {}),\n onLog: log,\n });\n // A named cloudflare tunnel (token) keeps the record's publicUrl; a quick\n // tunnel / tailscale reports the live URL, which can differ across restarts.\n const fresh = handle.publicUrl ? handle.publicUrl.replace(/\\/$/, '') : record.publicUrl;\n if (fresh && fresh !== record.publicUrl) {\n log(`tunnel URL changed → ${fresh}`);\n const updated: ControlPlaneDeployRecord = { ...record, publicUrl: fresh, url: fresh };\n await persistDeployRecord(updated);\n await setConfigValue('global', 'relay.controlPlaneUrl', fresh, homedir());\n return updated;\n }\n return record;\n}\n\n/**\n * Bring the exposed hub up for `hub start` when the machine is a local control\n * box: (re)establish the tunnel first (so the hub boots knowing its public URL),\n * then ensureHub (which reads the exposed record from disk).\n */\nexport async function bringUpExposedHub(\n record: ControlPlaneDeployRecord,\n log: (l: string) => void = () => {},\n): Promise<HubEndpoint> {\n await ensureTunnelForRecord(record, log);\n return ensureHub({ onLog: log });\n}\n\n/** Restart the exposed hub in place (the `hub update` local path). */\nexport async function runLocalUpdate(log: (l: string) => void = () => {}): Promise<HubEndpoint> {\n await stopHub();\n const record = await readLocalRecord();\n if (record) await ensureTunnelForRecord(record, log);\n return ensureHub({ onLog: log });\n}\n\n/**\n * Tear down the local control box: stop the tunnel, remove the autostart unit,\n * stop the exposed hub, purge the control-plane state, and unset the config —\n * leaving the plain localhost hub available on the next `hub start`. Does NOT\n * touch the shared `~/.agentbox` (store.db / auth.db / custody live there).\n */\nexport async function runLocalDestroy(\n opts: { keepCredentials?: boolean; log?: (l: string) => void } = {},\n): Promise<void> {\n const log = opts.log ?? (() => {});\n await stopTunnel().catch(() => {});\n await removeAutostart().catch(() => {});\n await stopHub();\n log('stopped the exposed hub + tunnel');\n await purgeLocalControlPlaneState({\n dir: CP_DIR,\n keepCredentials: Boolean(opts.keepCredentials),\n });\n await unsetConfigValue('global', 'relay.controlPlaneUrl', process.cwd()).catch(() => {});\n await unsetConfigValue('project', 'relay.controlPlaneUrl', process.cwd()).catch(() => {});\n}\n\n/**\n * On `hub stop`: take the tunnel down with the hub it fronts. No-op when this\n * machine isn't exposed or has no tunnel. Best-effort — failing to stop a tunnel\n * must not make `hub stop` fail.\n */\nexport async function stopTunnelIfExposed(log: (l: string) => void = () => {}): Promise<void> {\n const record = await readLocalRecord();\n if (!record?.tunnel) return;\n log('stopping the tunnel');\n await stopTunnel().catch(() => {});\n}\n\n/**\n * On `hub start` / autostart: if this machine is a local control box with a\n * tunnel, (re)establish it before the hub boots so the hub knows its public URL.\n * No-op otherwise. Best-effort — a tunnel failure must not block the hub.\n */\nexport async function restoreTunnelIfExposed(log: (l: string) => void = () => {}): Promise<void> {\n const record = await readLocalRecord();\n if (!record?.tunnel) return;\n try {\n const updated = await ensureTunnelForRecord(record, log);\n // A quick tunnel's hostname is ephemeral, so a restart can rotate it. The\n // record and config now carry the new URL, but the hub advertises\n // AGENTBOX_HUB_PUBLIC_URL from the env it was SPAWNED with — and ensureHub\n // returns early when a healthy hub of the right profile already holds the\n // port. Without this the running hub keeps telling boxes to call home on a\n // hostname that no longer resolves, while the CLI uses the new one.\n if (updated.publicUrl !== record.publicUrl) {\n log('tunnel URL rotated — restarting the hub so boxes get the new one');\n await stopHub();\n }\n } catch (e: unknown) {\n // The restart is stop-then-start and cannot be made atomic: a tailscale\n // funnel is a daemon toggle rather than a second process, so there is no\n // \"bring the new one up first\" for both kinds. That makes a failure here\n // leave NO tunnel while the record and the hub still advertise the old\n // hostname — boxes silently lose the hub. Say so plainly; a terse log line\n // scrolls past inside a spinner and reads like a warning about nothing.\n // Careful with tense: this runs BEFORE ensureHub on `hub start`, so on a cold\n // start (reboot, autostart) the hub is not up yet — claiming it is sends\n // debugging after the wrong thing.\n const reason = e instanceof Error ? e.message : String(e);\n log(`WARNING: the ${record.tunnel} tunnel did not come back (${reason}).`);\n log(\n `Cloud boxes will not reach the hub at ${record.publicUrl ?? 'its recorded URL'} until it does — ` +\n 're-run `agentbox hub start` to retry, or `agentbox hub expose --tunnel ' +\n `${record.tunnel}\\` to re-establish it.`,\n );\n }\n}\n\n/** The local deploy record if this machine is exposed, else null. */\nasync function readLocalRecord(): Promise<ControlPlaneDeployRecord | null> {\n try {\n const { readFile } = await import('node:fs/promises');\n const { controlPlaneDeployPath } = await import('@agentbox/sandbox-core');\n const rec = JSON.parse(\n await readFile(controlPlaneDeployPath(), 'utf8'),\n ) as ControlPlaneDeployRecord;\n return rec.provider === 'local' ? rec : null;\n } catch {\n return null;\n }\n}\n\n/** Whether a local exposed hub is currently the running mode (for status). */\nexport async function isLocallyExposed(): Promise<boolean> {\n const rec = await readLocalRecord();\n return rec !== null;\n}\n\n/** A hint if a hub is holding the port but not in the exposed profile yet. */\nexport async function exposedHubProfileOk(): Promise<boolean> {\n const s = await getHubStatus();\n return s.profile === 'hetzner';\n}\n\n/** Re-export for callers assembling the exposed env in tests / status. */\nexport { buildExposedHubEnv };\n","/**\n * Tunnels for the exposed hub — the only way a *cloud* box can reach a control\n * box that binds loopback/LAN (a box polls the hub URL for registration,\n * approvals and git-lease, and `http://127.0.0.1:8787` is not reachable from a\n * Firecracker microVM). Opt-in: `agentbox hub expose --tunnel <kind>`.\n *\n * Two kinds:\n * - cloudflare: a `cloudflared` quick tunnel — zero account, an EPHEMERAL\n * `https://<rand>.trycloudflare.com` hostname scraped from its log. A\n * `--tunnel-token` switches to a named tunnel with a stable hostname.\n * - tailscale: `tailscale funnel` — a stable `https://<node>.<tailnet>.ts.net`;\n * needs an authed tailscale daemon and HTTPS enabled on the tailnet.\n *\n * The tunnel runs as a detached process beside the hub (pid/log under the\n * control-plane dir) so `hub stop`/`destroy` reap it and autostart brings it\n * back. The URL-scrape is a pure function so it's unit-testable.\n */\nimport { spawn } from 'node:child_process';\nimport { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { existsSync, openSync } from 'node:fs';\nimport { homedir, tmpdir, arch as osArch, platform } from 'node:os';\nimport { join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { execa } from 'execa';\n\nexport type TunnelKind = 'cloudflare' | 'tailscale';\n\nconst CP_DIR = join(homedir(), '.agentbox', 'control-plane');\nconst TUNNEL_PID_FILE = join(CP_DIR, 'tunnel.pid');\nconst TUNNEL_LOG_FILE = join(CP_DIR, 'tunnel.log');\nconst BIN_DIR = join(homedir(), '.agentbox', 'bin');\n\nexport interface TunnelHandle {\n kind: TunnelKind;\n publicUrl: string;\n pid: number | null;\n logFile: string;\n}\n\nexport interface StartTunnelOptions {\n kind: TunnelKind;\n /** The local hub port to expose. */\n port: number;\n /** Named Cloudflare tunnel token (stable hostname) instead of a quick tunnel. */\n token?: string;\n onLog?: (line: string) => void;\n /** Seconds to wait for the tunnel URL to appear before giving up. */\n timeoutMs?: number;\n}\n\n/**\n * Extract a quick-tunnel hostname from cloudflared's log output. cloudflared\n * prints a boxed banner containing the URL to stderr; we just need the first\n * `https://<sub>.trycloudflare.com`. Pure — unit-tested.\n */\nexport function parseTrycloudflareUrl(logText: string): string | null {\n const m = /https:\\/\\/[a-z0-9-]+\\.trycloudflare\\.com/i.exec(logText);\n return m ? m[0] : null;\n}\n\n/** Map node's os/arch to cloudflared's release asset naming. */\nexport function cloudflaredAsset(\n osName: string = platform(),\n arch: string = osArch(),\n): { file: string; isTgz: boolean } {\n const a = arch === 'x64' ? 'amd64' : arch === 'arm64' ? 'arm64' : arch;\n if (osName === 'darwin') return { file: `cloudflared-darwin-${a}.tgz`, isTgz: true };\n // linux ships a raw binary (also for the box's amd64/arm64).\n return { file: `cloudflared-linux-${a}`, isTgz: false };\n}\n\nasync function onPath(cmd: string): Promise<string | null> {\n try {\n const { stdout } = await execa('command', ['-v', cmd], { shell: true });\n return stdout.trim() || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve a `cloudflared` binary: a system one on PATH, a previously-downloaded\n * copy, else download from GitHub releases (TLS-authenticated; the `latest`\n * download can't be checksum-pinned without knowing the version, so we rely on\n * HTTPS). Returns the executable path.\n */\nexport async function ensureCloudflared(onLog: (l: string) => void = () => {}): Promise<string> {\n const sys = await onPath('cloudflared');\n if (sys) return sys;\n const cached = join(BIN_DIR, 'cloudflared');\n if (existsSync(cached)) return cached;\n\n const { file, isTgz } = cloudflaredAsset();\n const url = `https://github.com/cloudflare/cloudflared/releases/latest/download/${file}`;\n await mkdir(BIN_DIR, { recursive: true });\n onLog(`downloading cloudflared (${file})…`);\n const res = await fetch(url, { redirect: 'follow' });\n if (!res.ok || !res.body) {\n throw new Error(\n `could not download cloudflared from ${url} (HTTP ${String(res.status)}). ` +\n 'Install it manually (e.g. `brew install cloudflared`) and re-run.',\n );\n }\n const buf = Buffer.from(await res.arrayBuffer());\n if (isTgz) {\n const tmp = join(tmpdir(), `cloudflared-${String(process.pid)}.tgz`);\n await writeFile(tmp, buf);\n // macOS ships the binary inside a .tgz; extract just `cloudflared`.\n await execa('tar', ['xzf', tmp, '-C', BIN_DIR, 'cloudflared']);\n await rm(tmp, { force: true });\n } else {\n await writeFile(cached, buf);\n }\n await chmod(cached, 0o755);\n return cached;\n}\n\n/** Spawn cloudflared detached, scrape its URL, and record the pid. */\nasync function startCloudflare(opts: StartTunnelOptions): Promise<TunnelHandle> {\n const log = opts.onLog ?? (() => {});\n const bin = await ensureCloudflared(log);\n await mkdir(CP_DIR, { recursive: true });\n // Fresh log so the URL scrape can't read a stale run's hostname.\n await writeFile(TUNNEL_LOG_FILE, '');\n const args = opts.token\n ? ['tunnel', '--no-autoupdate', 'run', '--token', opts.token]\n : // http2, not the default QUIC — UDP/7844 out of a nested/NAT'd box is unreliable.\n ['tunnel', '--no-autoupdate', '--protocol', 'http2', '--url', `http://127.0.0.1:${String(opts.port)}`];\n const fd = openSync(TUNNEL_LOG_FILE, 'a');\n const child = spawn(bin, args, { detached: true, stdio: ['ignore', fd, fd] });\n child.unref();\n if (typeof child.pid === 'number') await writeFile(TUNNEL_PID_FILE, String(child.pid));\n log(`spawned cloudflared (pid ${String(child.pid ?? '?')})`);\n\n // A named tunnel's hostname is not in the log — the caller supplies it via\n // --public-url; a quick tunnel prints its trycloudflare URL, which we scrape.\n if (opts.token) {\n return { kind: 'cloudflare', publicUrl: '', pid: child.pid ?? null, logFile: TUNNEL_LOG_FILE };\n }\n const deadline = Date.now() + (opts.timeoutMs ?? 30_000);\n while (Date.now() < deadline) {\n const url = parseTrycloudflareUrl(await readFile(TUNNEL_LOG_FILE, 'utf8').catch(() => ''));\n if (url) {\n log(`tunnel URL: ${url}`);\n return { kind: 'cloudflare', publicUrl: url, pid: child.pid ?? null, logFile: TUNNEL_LOG_FILE };\n }\n await delay(500);\n }\n await stopTunnel().catch(() => {});\n throw new Error(\n `cloudflared did not report a tunnel URL within ${String((opts.timeoutMs ?? 30_000) / 1000)}s — see ${TUNNEL_LOG_FILE}`,\n );\n}\n\n/** Turn on a tailscale funnel and resolve the node's public HTTPS name. */\nasync function startTailscale(opts: StartTunnelOptions): Promise<TunnelHandle> {\n const log = opts.onLog ?? (() => {});\n const ts = (await onPath('tailscale')) ?? 'tailscale';\n if (!(await onPath('tailscale'))) {\n throw new Error('tailscale is not installed — install it and `tailscale up` first, then re-run.');\n }\n // Funnel the port on 443 (background). Best-effort: a tailnet without HTTPS /\n // Funnel enabled errors here with an actionable message from tailscale itself.\n log('enabling tailscale funnel…');\n await execa(ts, ['funnel', '--bg', '--https=443', String(opts.port)]).catch((e: unknown) => {\n throw new Error(\n `tailscale funnel failed: ${e instanceof Error ? e.message : String(e)}. ` +\n 'Enable HTTPS + Funnel for your tailnet in the admin console.',\n );\n });\n const { stdout } = await execa(ts, ['status', '--json']);\n const status = JSON.parse(stdout) as { Self?: { DNSName?: string } };\n const dns = (status.Self?.DNSName ?? '').replace(/\\.$/, '');\n if (!dns) throw new Error('could not resolve this node\\'s tailscale DNS name from `tailscale status`.');\n const url = `https://${dns}`;\n log(`tunnel URL: ${url}`);\n // The funnel is served by the tailscaled daemon, not a child we own — record\n // no pid; teardown runs `tailscale funnel <port> off`.\n await writeFile(TUNNEL_PID_FILE, JSON.stringify({ tailscalePort: opts.port })).catch(() => {});\n return { kind: 'tailscale', publicUrl: url, pid: null, logFile: TUNNEL_LOG_FILE };\n}\n\nexport async function startTunnel(opts: StartTunnelOptions): Promise<TunnelHandle> {\n return opts.kind === 'tailscale' ? startTailscale(opts) : startCloudflare(opts);\n}\n\n/** Stop whatever tunnel is recorded and clear its state. Idempotent. */\nexport async function stopTunnel(): Promise<void> {\n let raw = '';\n try {\n raw = await readFile(TUNNEL_PID_FILE, 'utf8');\n } catch {\n return; // no tunnel recorded\n }\n // A tailscale funnel is a daemon setting, not a child pid — turn it off.\n const asTs = safeJson(raw) as { tailscalePort?: number } | null;\n if (asTs && typeof asTs.tailscalePort === 'number') {\n const ts = (await onPath('tailscale')) ?? 'tailscale';\n await execa(ts, ['funnel', String(asTs.tailscalePort), 'off']).catch(() => {});\n } else {\n const pid = Number.parseInt(raw.trim(), 10);\n if (Number.isFinite(pid) && pid > 0) {\n try {\n process.kill(pid, 'SIGTERM');\n } catch {\n /* already gone */\n }\n }\n }\n await rm(TUNNEL_PID_FILE, { force: true });\n}\n\n/** True when a tunnel pid file exists (used by status). */\nexport function tunnelStateFile(): string {\n return TUNNEL_PID_FILE;\n}\n\nfunction safeJson(s: string): unknown {\n try {\n return JSON.parse(s);\n } catch {\n return null;\n }\n}\n","/**\n * Autostart for the exposed hub — bring the control box back after a reboot or\n * logout, so an always-on machine (a Mac mini, a NAS, a desktop) keeps serving\n * the hub without anyone logging in and re-running it.\n *\n * A launchd LaunchAgent on macOS, a systemd user unit on Linux. Both just run\n * `agentbox hub start`, which reads the exposed block from\n * `~/.agentbox/control-plane/deploy.json` and brings the hub up in the same mode\n * — so the unit carries no secrets and never drifts from the expose flags.\n *\n * The unit-body builders are pure (host + paths in, string out) so they're\n * unit-testable; the install/remove wrappers write the file and best-effort\n * register it with the platform's service manager.\n */\nimport { spawn } from 'node:child_process';\nimport { mkdir, rm, writeFile } from 'node:fs/promises';\nimport { homedir, platform } from 'node:os';\nimport { dirname, join } from 'node:path';\n\n/** Reverse-DNS-ish label / unit name — matches the app's `sh.agent-box.*` id. */\nexport const LAUNCHD_LABEL = 'sh.agent-box.hub';\nexport const SYSTEMD_UNIT = 'agentbox-hub.service';\n\nexport function launchdPlistPath(home: string = homedir()): string {\n return join(home, 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`);\n}\n\nexport function systemdUnitPath(home: string = homedir()): string {\n return join(home, '.config', 'systemd', 'user', SYSTEMD_UNIT);\n}\n\n/** Where the autostart unit lives on this platform, or null when unsupported. */\nexport function autostartUnitPath(home: string = homedir()): string | null {\n if (platform() === 'darwin') return launchdPlistPath(home);\n if (platform() === 'linux') return systemdUnitPath(home);\n return null;\n}\n\n/** The command the unit runs: `<node> <cliEntry> hub start --no-open`. Pure. */\nexport interface AutostartInvocation {\n execPath: string;\n cliEntry: string;\n}\n\n/** launchd LaunchAgent plist. `RunAtLoad` + `KeepAlive` = start on login, restart on crash. */\nexport function launchdPlist(inv: AutostartInvocation, logFile: string): string {\n const args = [inv.execPath, inv.cliEntry, 'hub', 'start', '--no-open'];\n const argXml = args.map((a) => ` <string>${escapeXml(a)}</string>`).join('\\n');\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\">',\n '<dict>',\n ` <key>Label</key>`,\n ` <string>${LAUNCHD_LABEL}</string>`,\n ' <key>ProgramArguments</key>',\n ' <array>',\n argXml,\n ' </array>',\n ' <key>RunAtLoad</key>',\n ' <true/>',\n ' <key>KeepAlive</key>',\n ' <false/>',\n ' <key>StandardOutPath</key>',\n ` <string>${escapeXml(logFile)}</string>`,\n ' <key>StandardErrorPath</key>',\n ` <string>${escapeXml(logFile)}</string>`,\n '</dict>',\n '</plist>',\n '',\n ].join('\\n');\n}\n\n/** systemd user unit. `WantedBy=default.target` = start on (lingering) login. */\nexport function systemdUnit(inv: AutostartInvocation): string {\n const exec = [inv.execPath, inv.cliEntry, 'hub', 'start', '--no-open']\n .map((a) => (/\\s/.test(a) ? JSON.stringify(a) : a))\n .join(' ');\n return [\n '[Unit]',\n 'Description=AgentBox hub (control box)',\n 'After=network-online.target docker.service',\n 'Wants=network-online.target',\n '',\n '[Service]',\n 'Type=simple',\n `ExecStart=${exec}`,\n 'Restart=on-failure',\n 'RestartSec=5',\n '',\n '[Install]',\n 'WantedBy=default.target',\n '',\n ].join('\\n');\n}\n\nfunction escapeXml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\n}\n\n/** Run a command detached, ignoring failures (the service manager is a nicety). */\nfunction runQuiet(cmd: string, args: string[]): Promise<void> {\n return new Promise((resolveP) => {\n try {\n const child = spawn(cmd, args, { stdio: 'ignore' });\n child.on('error', () => resolveP());\n child.on('exit', () => resolveP());\n } catch {\n resolveP();\n }\n });\n}\n\nexport interface AutostartResult {\n /** Where the unit was written, or null on an unsupported platform. */\n path: string | null;\n /** A one-line note for the user (e.g. the systemd linger hint), or null. */\n note: string | null;\n}\n\n/**\n * Install the autostart unit for `hub start` and register it with launchd /\n * systemd (best-effort). Returns the path written and any follow-up note.\n */\nexport async function installAutostart(\n inv: AutostartInvocation,\n opts: { logFile: string; home?: string } = { logFile: join(homedir(), '.agentbox', 'hub.log') },\n): Promise<AutostartResult> {\n const home = opts.home ?? homedir();\n const os = platform();\n if (os === 'darwin') {\n const path = launchdPlistPath(home);\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, launchdPlist(inv, opts.logFile));\n // Reload so it takes effect now, not just next login. bootout is a no-op the\n // first time; bootstrap (re)loads the fresh plist.\n const domain = `gui/${process.getuid?.() ?? ''}`;\n await runQuiet('launchctl', ['bootout', domain, path]);\n await runQuiet('launchctl', ['bootstrap', domain, path]);\n return { path, note: null };\n }\n if (os === 'linux') {\n const path = systemdUnitPath(home);\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, systemdUnit(inv));\n await runQuiet('systemctl', ['--user', 'daemon-reload']);\n await runQuiet('systemctl', ['--user', 'enable', '--now', SYSTEMD_UNIT]);\n return {\n path,\n // A user unit only survives logout if lingering is on for the user.\n note: `To keep the hub running after you log out: sudo loginctl enable-linger ${process.env.USER ?? '$USER'}`,\n };\n }\n return { path: null, note: `autostart is not supported on ${os} — start the hub manually after a reboot` };\n}\n\n/** Remove the autostart unit and deregister it (best-effort, idempotent). */\nexport async function removeAutostart(home: string = homedir()): Promise<void> {\n const os = platform();\n if (os === 'darwin') {\n const path = launchdPlistPath(home);\n const domain = `gui/${process.getuid?.() ?? ''}`;\n await runQuiet('launchctl', ['bootout', domain, path]);\n await rm(path, { force: true });\n return;\n }\n if (os === 'linux') {\n await runQuiet('systemctl', ['--user', 'disable', '--now', SYSTEMD_UNIT]);\n await rm(systemdUnitPath(home), { force: true });\n await runQuiet('systemctl', ['--user', 'daemon-reload']);\n return;\n }\n}\n","import type { HubDeploySource } from '@agentbox/sandbox-core';\nimport { channelOfVersion } from '../lib/channel.js';\nimport { AGENTBOX_VERSION } from '../version.js';\n\n/** The repo a source-mode deploy clones when the caller names no other. */\nexport const DEFAULT_DEPLOY_REPO_URL = 'https://github.com/madarco/agentbox.git';\n\n/**\n * The git ref a control-box deploy should clone, derived from the CLI running it.\n *\n * The deploy is a two-sided contract: the VPS builds `apps/hub` from the cloned\n * ref, while the HOST generates the pieces that wrap it (the Caddyfile's upstream\n * port, the `.env` keys the compose consumes, the `/root/.agentbox` bind mount).\n * Those only line up when both sides come from the same code — so the ref has to\n * follow the CLI, not a constant.\n *\n * It used to be a hardcoded `main`, which silently broke every deploy from a\n * nightly CLI: `main`'s hub listened on :3000 behind a Postgres compose while the\n * nightly CLI wrote `reverse_proxy app:8787`, so Caddy 502'd against a perfectly\n * healthy hub for the full healthz window.\n *\n * - nightly build → the `nightly` branch (nightlies are published from it, and\n * are not tagged, so there is no exact ref to pin).\n * - released build → its own `v<version>` tag, exactly reproducing this CLI.\n * - dev build (`0.0.0-dev`, no version injected at bundle time) → `nightly`,\n * the branch dev builds are cut from.\n */\nexport function deployRefForVersion(version: string): string {\n if (channelOfVersion(version) === 'nightly') return 'nightly';\n if (version.startsWith('0.0.0')) return 'nightly';\n return `v${version}`;\n}\n\n/** The deploy ref for this process. */\nexport function defaultDeployRef(): string {\n return deployRefForVersion(AGENTBOX_VERSION);\n}\n\nexport interface HubDeploySourceOptions {\n /** `--ref` — build from source at this ref instead of installing the package. */\n ref?: string;\n /** `--repo` — clone this repo instead of the public one. Implies source mode. */\n repoUrl?: string;\n /** `--package` — install this npm spec instead of this CLI's own version. */\n packageSpec?: string;\n}\n\n/**\n * Where a control-box deploy gets the hub from.\n *\n * The default is the published npm package pinned to this CLI's exact version:\n * `@madarco/agentbox` already ships the standalone hub the local `agentbox hub`\n * spawns, so the VPS installs in seconds instead of building 14 workspace\n * packages, and the two sides of the deploy contract (the image, and the host-\n * generated Caddyfile / `.env` around it) come from one artifact rather than\n * from a branch name that happens to match.\n *\n * Source mode is the escape hatch, and is chosen automatically for a dev build\n * whose version was never published.\n */\nexport function resolveHubDeploySource(\n version: string,\n opts: HubDeploySourceOptions = {},\n): HubDeploySource {\n const repoUrl = opts.repoUrl ?? DEFAULT_DEPLOY_REPO_URL;\n if (opts.packageSpec) return { kind: 'package', spec: opts.packageSpec };\n if (opts.ref !== undefined || opts.repoUrl !== undefined) {\n return { kind: 'source', repoUrl, repoRef: opts.ref ?? deployRefForVersion(version) };\n }\n // A dev build has no counterpart on npm to install — fall back to building the\n // branch dev builds are cut from.\n if (version.startsWith('0.0.0')) {\n return { kind: 'source', repoUrl, repoRef: deployRefForVersion(version) };\n }\n return { kind: 'package', spec: version };\n}\n\n/** One line naming what a deploy is about to install, for the progress log. */\nexport function describeHubDeploySource(source: HubDeploySource): string {\n return source.kind === 'package'\n ? `npm @madarco/agentbox@${source.spec}`\n : `git ${source.repoUrl}@${source.repoRef} (built on the VPS)`;\n}\n","import { execa } from 'execa';\nimport { resolveOriginGitHost } from '../lib/git-host.js';\n\n/**\n * Find a GitHub token on THIS machine to hand to a control box (`hub.gitAuth=gh`).\n *\n * The control box does the git work on a box's behalf — clone for the create\n * worker, the real `git push` at the end of the relay's bundle path — so it\n * needs a credential of its own. The point of this mode is that the credential\n * is one you already have and can create yourself: no GitHub App to install, no\n * org admin to ask.\n *\n * Order, most-specific first:\n * 1. `gh auth token` — the common case, and the one that needs no prompting.\n * 2. git's credential helper (osxkeychain / store / manager) via\n * `git credential fill`, which is how a user who authenticates git without\n * `gh` still has a usable token.\n *\n * Deliberately NOT consulted: an ambient `GH_TOKEN`/`GITHUB_TOKEN` in the\n * environment. A developer exporting one for a shell session would otherwise\n * have it silently promoted to a long-lived server credential without ever being\n * shown what was taken.\n *\n * Both sources are asked about the host the project's `origin` actually points\n * at, so a GitHub Enterprise Server repo gets its enterprise credential rather\n * than whichever host `gh` happens to default to.\n */\nexport interface HostGitToken {\n token: string;\n /** Where it came from — shown to the user before it leaves the machine. */\n source: 'gh' | 'git-credential';\n /** The GitHub host it authenticates against (github.com, or a GHES instance). */\n host: string;\n /** GitHub login the token resolves to, when we can cheaply determine it. */\n login?: string;\n}\n\nasync function fromGhCli(host: string): Promise<HostGitToken | null> {\n try {\n const r = await execa('gh', ['auth', 'token', '--hostname', host], {\n reject: false,\n timeout: 15_000,\n });\n const token = (r.stdout ?? '').trim();\n if (r.exitCode !== 0 || token.length === 0) return null;\n return { token, source: 'gh', host };\n } catch {\n return null;\n }\n}\n\nasync function fromGitCredentialHelper(cwd: string, host: string): Promise<HostGitToken | null> {\n try {\n const r = await execa('git', ['credential', 'fill'], {\n cwd,\n input: `protocol=https\\nhost=${host}\\n\\n`,\n reject: false,\n timeout: 15_000,\n });\n if (r.exitCode !== 0) return null;\n const password = /^password=(.*)$/m.exec(r.stdout ?? '')?.[1]?.trim() ?? '';\n if (password.length === 0) return null;\n return { token: password, source: 'git-credential', host };\n } catch {\n return null;\n }\n}\n\n/**\n * REST base for a GitHub host: github.com and Enterprise Cloud tenancy hosts\n * answer on `api.<host>`, self-hosted GHES on `<host>/api/v3`.\n */\nexport function githubApiBase(host: string): string {\n const h = host.toLowerCase();\n if (h === 'github.com' || h.endsWith('.ghe.com')) return `https://api.${h}`;\n return `https://${h}/api/v3`;\n}\n\n/** Which GitHub account a token belongs to; undefined when it can't be checked. */\nexport async function resolveTokenLogin(\n token: string,\n host = 'github.com',\n): Promise<string | undefined> {\n try {\n const res = await fetch(`${githubApiBase(host)}/user`, {\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/vnd.github+json',\n 'User-Agent': 'agentbox',\n },\n signal: AbortSignal.timeout(10_000),\n });\n if (!res.ok) return undefined;\n const body = (await res.json()) as { login?: unknown };\n return typeof body.login === 'string' ? body.login : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The GitHub host a checkout's `origin` points at — github.com unless the repo\n * lives on a GitHub Enterprise Server instance. ssh aliases are expanded (see\n * `resolveOriginGitHost`), so `git@github.com-work:o/r` asks github.com for its\n * credential rather than a host that doesn't exist. Falls back to github.com\n * when there is no origin to read (a fresh dir, a non-git cwd).\n */\nexport async function originGitHost(cwd: string): Promise<string> {\n try {\n const r = await execa('git', ['-C', cwd, 'remote', 'get-url', 'origin'], {\n reject: false,\n timeout: 15_000,\n });\n if (r.exitCode !== 0) return 'github.com';\n return await resolveOriginGitHost((r.stdout ?? '').trim());\n } catch {\n return 'github.com';\n }\n}\n\n/** The first token this machine can offer for `cwd`'s origin host, or null. */\nexport async function findHostGitToken(cwd: string = process.cwd()): Promise<HostGitToken | null> {\n const host = await originGitHost(cwd);\n return (await fromGhCli(host)) ?? (await fromGitCredentialHelper(cwd, host));\n}\n\n/**\n * Scopes a classic token carries, read from the `x-oauth-scopes` response\n * header. Fine-grained PATs and App tokens report none, which is not an error —\n * it just means there is nothing to warn about.\n */\nexport async function resolveTokenScopes(token: string, host = 'github.com'): Promise<string[]> {\n try {\n const res = await fetch(`${githubApiBase(host)}/user`, {\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/vnd.github+json',\n 'User-Agent': 'agentbox',\n },\n signal: AbortSignal.timeout(10_000),\n });\n const raw = res.headers.get('x-oauth-scopes') ?? '';\n return raw\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n } catch {\n return [];\n }\n}\n\n/** Scopes worth flagging: far beyond what the hub needs to clone and push. */\nexport const OVERBROAD_SCOPES = ['admin:org', 'delete_repo', 'admin:enterprise'] as const;\n\nexport function overbroadScopes(scopes: readonly string[]): string[] {\n return scopes.filter((s) => (OVERBROAD_SCOPES as readonly string[]).includes(s));\n}\n","/**\n * Which GitHub host a remote authenticates against.\n *\n * The hostname in a remote URL is not always the host that answers: an\n * `~/.ssh/config` alias (`git@github.com-work:owner/repo`, the usual\n * multiple-accounts setup) names a config entry, not a server. ssh, git and\n * `gh` all resolve it through `ssh -G` before doing anything with it, so\n * anything asking \"which host do I need a credential for\" has to do the same —\n * otherwise an alias user gets asked for a credential for a host that does not\n * exist, where a plain `gh auth token` used to hand back the right one.\n *\n * The relay does the same expansion for the `gh` proxy (`resolveGhTarget` in\n * `@agentbox/relay`); this is the host-CLI side of it.\n */\n\nimport { ghHostFromRemote } from '@agentbox/relay';\nimport { resolveSshConfigTarget } from '@agentbox/sandbox-core';\n\n/**\n * The GitHub host `origin` really points at, with ssh aliases expanded.\n * Defaults to github.com for a missing, unparseable or non-GitHub remote —\n * the same assumption every caller made before there was a choice.\n */\nexport async function resolveOriginGitHost(origin: string | undefined): Promise<string> {\n const derived = ghHostFromRemote(origin);\n // null means github.com (or nothing usable) — no expansion to do either way.\n if (!derived) return 'github.com';\n // An https URL has no aliasing layer between it and the request it makes.\n if (!derived.aliasable) return derived.host;\n const expanded = await resolveSshConfigTarget(derived.host).catch(() => null);\n const host = expanded?.host.trim().toLowerCase() ?? '';\n return host.length > 0 ? host : derived.host;\n}\n","import {\n closeSync,\n mkdirSync,\n openSync,\n renameSync,\n symlinkSync,\n unlinkSync,\n writeFileSync,\n writeSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface CommandLog {\n /** Absolute path agents can tail. */\n path: string;\n /** Append a line with an ISO timestamp prefix; a trailing newline is added if missing. */\n write(line: string): void;\n /** Append raw bytes verbatim — for subprocess streams that already carry their own newlines. */\n raw(chunk: string): void;\n /** Time a step; emits BEGIN/END markers and elapsed ms. On throw, emits FAIL and rethrows. */\n step<T>(name: string, fn: () => Promise<T>): Promise<T>;\n /** Idempotent. */\n close(): void;\n}\n\nfunction stateDir(): string {\n return process.env.AGENTBOX_HOME ?? join(homedir(), '.agentbox');\n}\n\nfunction logsDir(): string {\n return join(stateDir(), 'logs');\n}\n\n/**\n * Open a fresh, tee'd log file for a CLI command. Rotates one generation:\n * any prior `<command>.log` becomes `<command>.log.prev`, replacing an\n * older prev. Also updates `<logsDir>/latest.log` to point at the active\n * file so an agent can tail one stable path without knowing the command.\n *\n * Writes are synchronous; callers can fire-and-forget from spinner\n * callbacks. The fd is closed on `close()` and on `process.exit` so a\n * crash still flushes everything that was written.\n */\n/**\n * The log for the command currently running, when one opened a log at all.\n *\n * Exists so deep layers can record a decision without every caller threading a\n * logger down to them. The concrete case: `ensureImage`'s pull-vs-build progress\n * is wired only to a @clack spinner, which overwrites itself — so the single\n * most expensive branch in a create (pull a published image, or rebuild it for\n * ten minutes) left NO trace on disk, and a silently rate-limited pull was\n * indistinguishable from an unpublished tag when reading the logs afterwards.\n */\nlet activeCommandLog: CommandLog | null = null;\n\n/**\n * Append to the active command log, if any. A no-op when nothing opened one\n * (a short command, or a unit test), so callers never need to check.\n */\nexport function logToActiveCommand(line: string): void {\n activeCommandLog?.write(line);\n}\n\nexport function openCommandLog(command: string): CommandLog {\n const dir = logsDir();\n mkdirSync(dir, { recursive: true });\n\n const path = join(dir, `${command}.log`);\n const prev = join(dir, `${command}.log.prev`);\n try {\n // Move the previous run aside. EEXIST on rename is the typical case\n // (a `.prev` from the run before that) — overwrite it.\n renameSync(path, prev);\n } catch {\n /* nothing to rotate */\n }\n\n const fd = openSync(path, 'a');\n const startedAt = new Date().toISOString();\n writeSync(fd, `${startedAt} --- BEGIN ${command} (pid ${String(process.pid)}) ---\\n`);\n\n updateLatestSymlink(dir, path);\n\n let closed = false;\n const closeOnce = (): void => {\n if (closed) return;\n closed = true;\n if (activeCommandLog === log) activeCommandLog = null;\n try {\n writeSync(fd, `${new Date().toISOString()} --- END ${command} ---\\n`);\n } catch {\n /* fd already gone */\n }\n try {\n closeSync(fd);\n } catch {\n /* already closed */\n }\n };\n // Last-resort flush. Don't unhook anything else; this is purely additive.\n process.on('exit', closeOnce);\n\n const log: CommandLog = {\n path,\n write(line: string): void {\n if (closed) return;\n const ts = new Date().toISOString();\n const body = line.endsWith('\\n') ? line : line + '\\n';\n try {\n writeSync(fd, `${ts} ${body}`);\n } catch {\n /* swallow — never break the command on log write failure */\n }\n },\n raw(chunk: string): void {\n if (closed) return;\n try {\n writeSync(fd, chunk);\n } catch {\n /* swallow */\n }\n },\n async step<T>(name: string, fn: () => Promise<T>): Promise<T> {\n const t0 = Date.now();\n this.write(`--- BEGIN ${name} ---`);\n try {\n const out = await fn();\n this.write(`--- END ${name} (${String(Date.now() - t0)}ms) ---`);\n return out;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.write(`--- FAIL ${name} (${String(Date.now() - t0)}ms): ${msg} ---`);\n throw err;\n }\n },\n close: closeOnce,\n };\n activeCommandLog = log;\n return log;\n}\n\nfunction updateLatestSymlink(dir: string, target: string): void {\n const link = join(dir, 'latest.log');\n try {\n unlinkSync(link);\n } catch {\n /* not present */\n }\n try {\n symlinkSync(target, link);\n } catch {\n // Windows or restricted FS: leave a text pointer instead. Best-effort.\n try {\n writeFileSync(link, target + '\\n');\n } catch {\n /* give up — symlink is a convenience, not a contract */\n }\n }\n}\n","import { randomBytes } from 'node:crypto';\nimport { isCancel, password, text } from '@clack/prompts';\n\n/** Env the deployed hub needs to enforce login + seed its first admin. */\nexport interface HubAuthEnv {\n AGENTBOX_HUB_AUTH: string;\n BETTER_AUTH_SECRET: string;\n AGENTBOX_HUB_ADMIN_EMAIL: string;\n AGENTBOX_HUB_ADMIN_PASSWORD: string;\n}\n\n/**\n * Collect the hub auth env for a deployed profile, prompting for anything not\n * already in the environment. Setting these turns login on (auth is secret-gated\n * on the hub), so a deployed hub is never left loginless. Returns null if the\n * operator cancels a prompt (deploy proceeds without login, as before).\n */\nexport async function resolveHubAuthEnv(): Promise<HubAuthEnv | null> {\n let email = process.env.AGENTBOX_HUB_ADMIN_EMAIL;\n let pass = process.env.AGENTBOX_HUB_ADMIN_PASSWORD;\n const secret = process.env.BETTER_AUTH_SECRET || randomBytes(32).toString('base64');\n\n if (!email) {\n const v = await text({\n message: 'Hub admin email (used to log in to the deployed hub UI)',\n validate: (s) => (/^.+@.+\\..+$/.test(s.trim()) ? undefined : 'enter a valid email'),\n });\n if (isCancel(v)) return null;\n email = v.trim();\n }\n if (!pass) {\n const v = await password({\n message: 'Hub admin password (min 8 characters)',\n validate: (s) => (s.length >= 8 ? undefined : 'at least 8 characters'),\n });\n if (isCancel(v)) return null;\n pass = v;\n }\n\n return {\n AGENTBOX_HUB_AUTH: 'on',\n BETTER_AUTH_SECRET: secret,\n AGENTBOX_HUB_ADMIN_EMAIL: email,\n AGENTBOX_HUB_ADMIN_PASSWORD: pass,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAAA,UAAS,YAAAC,WAAU,OAAAC,MAAK,QAAAC,OAAM,QAAQ,eAAe;AAC9D,SAAS,WAAAC,UAAS,cAAc;AAChC,SAAS,SAAAC,cAAa;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;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":["confirm","isCancel","log","note","Command","spawn","execa","existsSync","readFileSync","chmod","mkdir","readFile","rm","writeFile","homedir","tmpdir","dirname","join","delay","randomBytes","cliNativeFingerprint","log","spawn","join","log","spawn","spawn","log","join","spawn","join","recoveryHint","join","readFile","execa","existsSync","mkdtempSync","readFileSync","rmSync","tmpdir","join","readFile","readFile","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","join","execa","existsSync","rmSync","readFileSync","mkdtempSync","join","tmpdir","readFile","spawn","readFile","existsSync","homedir","tmpdir","join","delay","execa","CP_DIR","log","spawn","mkdir","rm","writeFile","homedir","platform","dirname","join","spawn","join","homedir","platform","mkdir","dirname","writeFile","rm","join","homedir","CP_DIR","log","log","CP_DIR","readFile","execa","execa","password","mkdirSync","openSync","writeFileSync","homedir","join","log","randomBytes","isCancel","CP_DIR","join","homedir","ENV_PATH","META_PATH","delay","existsSync","readFileSync","writeFile","chmod","onPath","execa","log","note","confirm","isCancel","Command","randomBytes","mkdir","recoveryHint","spawn","tmpdir","rm","ensureHub","stopHub","getHubStatus","dirname","readFile","adopted"]}