@madarco/agentbox 0.29.1 → 0.29.2

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 (108) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/{_cloud-attach-EUO2OL7W.js → _cloud-attach-7WVNYNJI.js} +6 -6
  3. package/dist/{chunk-2JHPGPLE.js → chunk-5I7IFACI.js} +2 -2
  4. package/dist/{chunk-AC3HU25W.js → chunk-5NVHJS7D.js} +2 -2
  5. package/dist/{chunk-PFEBKXFD.js → chunk-6UCHNX75.js} +19 -12
  6. package/dist/{chunk-PFEBKXFD.js.map → chunk-6UCHNX75.js.map} +1 -1
  7. package/dist/{chunk-UEEW5TW7.js → chunk-F77AZT2M.js} +2 -2
  8. package/dist/{chunk-UTOC2NHC.js → chunk-FCMBVJFQ.js} +2 -2
  9. package/dist/{chunk-73D2HKA3.js → chunk-HLBK5ZR6.js} +5 -5
  10. package/dist/{chunk-4KYP775X.js → chunk-JLVUNDUB.js} +26 -7
  11. package/dist/chunk-JLVUNDUB.js.map +1 -0
  12. package/dist/{chunk-BIKWXLX7.js → chunk-JTYWZJIU.js} +3 -3
  13. package/dist/{chunk-7LC5IG5K.js → chunk-LEVYTABB.js} +3 -3
  14. package/dist/{chunk-FEFLAITR.js → chunk-MS4NWRXN.js} +2 -2
  15. package/dist/{chunk-WJUKN4L4.js → chunk-N6EBPKTJ.js} +45 -3
  16. package/dist/chunk-N6EBPKTJ.js.map +1 -0
  17. package/dist/{chunk-4NUETVTR.js → chunk-OUOV4OM2.js} +7 -7
  18. package/dist/{chunk-I7BSBUPC.js → chunk-P5A6MT75.js} +7 -7
  19. package/dist/{chunk-FELVUIIM.js → chunk-RXH634SC.js} +2 -2
  20. package/dist/{chunk-QDU7YDME.js → chunk-SXXN7JOC.js} +18 -18
  21. package/dist/{chunk-B4YFG5TB.js → chunk-TDW2T3HR.js} +4 -4
  22. package/dist/{chunk-S32GHLVU.js → chunk-TPHSVKMX.js} +2 -2
  23. package/dist/{chunk-53OTEDBS.js → chunk-ZCHWZYIN.js} +3 -3
  24. package/dist/cloud-backends.js +3 -3
  25. package/dist/{control-plane-YQFX2ILX.js → control-plane-TOFT56CT.js} +10 -10
  26. package/dist/{cp-hub-upload-RMJ3XJ65.js → cp-hub-upload-OTBR5SL3.js} +2 -2
  27. package/dist/{deploy-hetzner-EECQ4JCM.js → deploy-hetzner-EE5CYX4N.js} +4 -4
  28. package/dist/{dist-Q4UDCSZQ.js → dist-7HSAWFRN.js} +3 -3
  29. package/dist/{dist-XUOHE22G.js → dist-BVZBXQ2Y.js} +4 -4
  30. package/dist/{dist-NFF2KEMB.js → dist-GMIBT6IK.js} +43 -19
  31. package/dist/{dist-NFF2KEMB.js.map → dist-GMIBT6IK.js.map} +1 -1
  32. package/dist/{dist-NTUHJOK3.js → dist-JSEXGLYK.js} +3 -3
  33. package/dist/{dist-TXFTYNNE.js → dist-RWFKW4IU.js} +2 -2
  34. package/dist/{dist-Z2TPC3EN.js → dist-XV77P3RW.js} +3 -3
  35. package/dist/{dist-E5EXDZG4.js → dist-Y2GCMA6N.js} +2 -2
  36. package/dist/{hub-3HPYOV5O.js → hub-53E6EFZB.js} +11 -11
  37. package/dist/{hub-docker-target-ZKAWXVPH.js → hub-docker-target-CS5XHSSA.js} +7 -7
  38. package/dist/index.js +47 -39
  39. package/dist/index.js.map +1 -1
  40. package/dist/{prepare-KIVDQRMN.js → prepare-VTLE7RCJ.js} +15 -15
  41. package/dist/{prepared-custody-EFSOOAIQ.js → prepared-custody-ATP6GQGW.js} +11 -11
  42. package/dist/{publish-credentials-F2A5OVCO.js → publish-credentials-NAWOHOLK.js} +3 -3
  43. package/dist/{registry-O3X2CDDU.js → registry-5CPAQ2KN.js} +3 -3
  44. package/dist/{remote-docker-share-QDCBM5UM.js → remote-docker-share-XBV76ZAZ.js} +4 -4
  45. package/dist/{tool-grant-push-6ISDIJKH.js → tool-grant-push-5GJYMC7C.js} +2 -2
  46. package/package.json +1 -1
  47. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  48. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  49. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  50. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  51. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  52. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  53. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  54. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  55. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  56. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  57. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  58. package/runtime/hub/apps/hub/{chunk-BI4MPGQT.js → chunk-CTNPQ75B.js} +7 -7
  59. package/runtime/hub/apps/hub/{chunk-2WB3A5IN.js → chunk-DJPQLZ5Y.js} +1 -1
  60. package/runtime/hub/apps/hub/{chunk-RPPOFMPA.js → chunk-GUKVXSIY.js} +25 -6
  61. package/runtime/hub/apps/hub/{dist-F547YSBE.js → dist-2G5INR3G.js} +2 -2
  62. package/runtime/hub/apps/hub/{dist-YB3Y2XDK.js → dist-CIB4ZPJW.js} +85 -19
  63. package/runtime/hub/apps/hub/{dist-W5SGEJLA.js → dist-PI5ZAQGG.js} +1 -1
  64. package/runtime/hub/apps/hub/{dist-4F6XEJHK.js → dist-VDPNQEZ7.js} +2 -2
  65. package/runtime/hub/apps/hub/{dist-FEHV4PC7.js → dist-VZM32WR4.js} +1 -1
  66. package/runtime/hub/apps/hub/{dist-P7NT6VLK.js → dist-Y3LGOZ56.js} +1 -1
  67. package/runtime/hub/apps/hub/{dist-A3JOKKYG.js → dist-ZOJYJJ26.js} +1 -1
  68. package/runtime/hub/apps/hub/{hub-worker-I5QBLSRU.js → hub-worker-YQCQKCXS.js} +3 -3
  69. package/runtime/hub/apps/hub/server.js +8 -8
  70. package/runtime/hub/apps/hub/tsconfig.tsbuildinfo +1 -1
  71. package/dist/chunk-4KYP775X.js.map +0 -1
  72. package/dist/chunk-WJUKN4L4.js.map +0 -1
  73. /package/dist/{_cloud-attach-EUO2OL7W.js.map → _cloud-attach-7WVNYNJI.js.map} +0 -0
  74. /package/dist/{chunk-2JHPGPLE.js.map → chunk-5I7IFACI.js.map} +0 -0
  75. /package/dist/{chunk-AC3HU25W.js.map → chunk-5NVHJS7D.js.map} +0 -0
  76. /package/dist/{chunk-UEEW5TW7.js.map → chunk-F77AZT2M.js.map} +0 -0
  77. /package/dist/{chunk-UTOC2NHC.js.map → chunk-FCMBVJFQ.js.map} +0 -0
  78. /package/dist/{chunk-73D2HKA3.js.map → chunk-HLBK5ZR6.js.map} +0 -0
  79. /package/dist/{chunk-BIKWXLX7.js.map → chunk-JTYWZJIU.js.map} +0 -0
  80. /package/dist/{chunk-7LC5IG5K.js.map → chunk-LEVYTABB.js.map} +0 -0
  81. /package/dist/{chunk-FEFLAITR.js.map → chunk-MS4NWRXN.js.map} +0 -0
  82. /package/dist/{chunk-4NUETVTR.js.map → chunk-OUOV4OM2.js.map} +0 -0
  83. /package/dist/{chunk-I7BSBUPC.js.map → chunk-P5A6MT75.js.map} +0 -0
  84. /package/dist/{chunk-FELVUIIM.js.map → chunk-RXH634SC.js.map} +0 -0
  85. /package/dist/{chunk-QDU7YDME.js.map → chunk-SXXN7JOC.js.map} +0 -0
  86. /package/dist/{chunk-B4YFG5TB.js.map → chunk-TDW2T3HR.js.map} +0 -0
  87. /package/dist/{chunk-S32GHLVU.js.map → chunk-TPHSVKMX.js.map} +0 -0
  88. /package/dist/{chunk-53OTEDBS.js.map → chunk-ZCHWZYIN.js.map} +0 -0
  89. /package/dist/{control-plane-YQFX2ILX.js.map → control-plane-TOFT56CT.js.map} +0 -0
  90. /package/dist/{cp-hub-upload-RMJ3XJ65.js.map → cp-hub-upload-OTBR5SL3.js.map} +0 -0
  91. /package/dist/{deploy-hetzner-EECQ4JCM.js.map → deploy-hetzner-EE5CYX4N.js.map} +0 -0
  92. /package/dist/{dist-NTUHJOK3.js.map → dist-7HSAWFRN.js.map} +0 -0
  93. /package/dist/{dist-Q4UDCSZQ.js.map → dist-BVZBXQ2Y.js.map} +0 -0
  94. /package/dist/{dist-TXFTYNNE.js.map → dist-JSEXGLYK.js.map} +0 -0
  95. /package/dist/{dist-XUOHE22G.js.map → dist-RWFKW4IU.js.map} +0 -0
  96. /package/dist/{dist-Z2TPC3EN.js.map → dist-XV77P3RW.js.map} +0 -0
  97. /package/dist/{dist-E5EXDZG4.js.map → dist-Y2GCMA6N.js.map} +0 -0
  98. /package/dist/{hub-3HPYOV5O.js.map → hub-53E6EFZB.js.map} +0 -0
  99. /package/dist/{hub-docker-target-ZKAWXVPH.js.map → hub-docker-target-CS5XHSSA.js.map} +0 -0
  100. /package/dist/{prepare-KIVDQRMN.js.map → prepare-VTLE7RCJ.js.map} +0 -0
  101. /package/dist/{prepared-custody-EFSOOAIQ.js.map → prepared-custody-ATP6GQGW.js.map} +0 -0
  102. /package/dist/{publish-credentials-F2A5OVCO.js.map → publish-credentials-NAWOHOLK.js.map} +0 -0
  103. /package/dist/{registry-O3X2CDDU.js.map → registry-5CPAQ2KN.js.map} +0 -0
  104. /package/dist/{remote-docker-share-QDCBM5UM.js.map → remote-docker-share-XBV76ZAZ.js.map} +0 -0
  105. /package/dist/{tool-grant-push-6ISDIJKH.js.map → tool-grant-push-5GJYMC7C.js.map} +0 -0
  106. /package/runtime/hub/apps/hub/.next/static/{nDHi_1342DzyGDC14ocQo → 2P6VYtaUNxtdBvOVMolM-}/_buildManifest.js +0 -0
  107. /package/runtime/hub/apps/hub/.next/static/{nDHi_1342DzyGDC14ocQo → 2P6VYtaUNxtdBvOVMolM-}/_clientMiddlewareManifest.js +0 -0
  108. /package/runtime/hub/apps/hub/.next/static/{nDHi_1342DzyGDC14ocQo → 2P6VYtaUNxtdBvOVMolM-}/_ssgManifest.js +0 -0
package/CHANGELOG.md CHANGED
@@ -9,6 +9,30 @@ Entries are generated from the commit history with `/release-notes` and then
9
9
  hand-reviewed — they describe what changed for someone using the `agentbox`
10
10
  CLI, not the raw commits.
11
11
 
12
+ ## [0.29.2] - 2026-08-30
13
+
14
+ ### Added
15
+
16
+ - Provider SDK 2.10.0: `CloudBackend.attachRunAs?(handle)` lets a provider drop
17
+ its attach session to the box user when the transport lands as root. Optional
18
+ and additive — existing plugins are unaffected.
19
+
20
+ ### Fixed
21
+
22
+ - **Daytona `linux-vm` boxes ran as `root`**, so the agent never saw the
23
+ credentials seeded into `/home/vscode` and started at a login prompt on a box
24
+ that reported healthy. Boxes now run as `vscode` throughout — exec, attach,
25
+ tmux and the in-box daemons. **Re-bake with `agentbox prepare --provider
26
+ daytona --force`, and destroy and recreate existing `linux-vm` boxes.**
27
+ - Daytona now explains when your organization has no VM region — a *dedicated*
28
+ region that Daytona must enable, which neither a new org nor added credit
29
+ grants — instead of failing the bake with a raw SDK stack trace. The docs page
30
+ leads with the requirement.
31
+ - A failed `agentbox prepare` now reports why it failed, instead of only
32
+ `bake job <id> ended failed` with the real cause left in the job log.
33
+ - `agentbox self-update` could skip a menu-bar app update for up to 24 hours by
34
+ answering from the daily check's cache; it now re-resolves the release.
35
+
12
36
  ## [0.29.1] - 2026-08-30
13
37
 
14
38
  ### Fixed
@@ -2,18 +2,18 @@
2
2
  import {
3
3
  cloudAgentAttach,
4
4
  cloudAgentStartDetached
5
- } from "./chunk-73D2HKA3.js";
5
+ } from "./chunk-HLBK5ZR6.js";
6
6
  import "./chunk-F4PPZ4SI.js";
7
- import "./chunk-53OTEDBS.js";
8
- import "./chunk-2JHPGPLE.js";
7
+ import "./chunk-ZCHWZYIN.js";
8
+ import "./chunk-5I7IFACI.js";
9
9
  import "./chunk-WHFCJBMO.js";
10
10
  import {
11
11
  buildCloudAttachInnerCommand,
12
12
  verifyDetachedSession
13
- } from "./chunk-4KYP775X.js";
13
+ } from "./chunk-JLVUNDUB.js";
14
14
  import "./chunk-I2DEYQLZ.js";
15
15
  import "./chunk-THKVKVRF.js";
16
- import "./chunk-I7BSBUPC.js";
16
+ import "./chunk-P5A6MT75.js";
17
17
  import "./chunk-CZPVVFCF.js";
18
18
  import "./chunk-XENTK32L.js";
19
19
  import "./chunk-7LNXTPEE.js";
@@ -27,4 +27,4 @@ export {
27
27
  cloudAgentStartDetached,
28
28
  verifyDetachedSession
29
29
  };
30
- //# sourceMappingURL=_cloud-attach-EUO2OL7W.js.map
30
+ //# sourceMappingURL=_cloud-attach-7WVNYNJI.js.map
@@ -3,7 +3,7 @@ import {
3
3
  getRuntimeProviderNames,
4
4
  isRuntimeProvider,
5
5
  loadProviderModule
6
- } from "./chunk-I7BSBUPC.js";
6
+ } from "./chunk-P5A6MT75.js";
7
7
  import {
8
8
  REMOTE_DOCKER,
9
9
  parseProviderSpec
@@ -68,4 +68,4 @@ export {
68
68
  providerForBox,
69
69
  providerForCreate
70
70
  };
71
- //# sourceMappingURL=chunk-2JHPGPLE.js.map
71
+ //# sourceMappingURL=chunk-5I7IFACI.js.map
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  createCloudProvider
4
- } from "./chunk-4KYP775X.js";
4
+ } from "./chunk-JLVUNDUB.js";
5
5
  import {
6
6
  detectPortless,
7
7
  portlessDoctorRow,
@@ -2585,4 +2585,4 @@ export {
2585
2585
  hetznerProvider,
2586
2586
  providerModule
2587
2587
  };
2588
- //# sourceMappingURL=chunk-AC3HU25W.js.map
2588
+ //# sourceMappingURL=chunk-5NVHJS7D.js.map
@@ -1,23 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  pinAdoptedBase
4
- } from "./chunk-B4YFG5TB.js";
4
+ } from "./chunk-TDW2T3HR.js";
5
5
  import {
6
6
  localExposedLoopbackUrl,
7
7
  resolveCustodyTarget,
8
8
  resolveHubApiClient,
9
9
  resolveHubApiTarget
10
- } from "./chunk-QDU7YDME.js";
10
+ } from "./chunk-SXXN7JOC.js";
11
11
  import {
12
12
  getProvider,
13
13
  isKnownProvider
14
- } from "./chunk-2JHPGPLE.js";
14
+ } from "./chunk-5I7IFACI.js";
15
15
  import {
16
16
  dockerProviderRefusal
17
- } from "./chunk-UTOC2NHC.js";
17
+ } from "./chunk-FCMBVJFQ.js";
18
18
  import {
19
19
  controlBoxKnowsHost
20
- } from "./chunk-4NUETVTR.js";
20
+ } from "./chunk-OUOV4OM2.js";
21
21
  import {
22
22
  HubApiClient,
23
23
  HubApiError
@@ -26,7 +26,7 @@ import {
26
26
  deadlineFetch,
27
27
  hostReachable,
28
28
  pullPreparedFromCustody
29
- } from "./chunk-4KYP775X.js";
29
+ } from "./chunk-JLVUNDUB.js";
30
30
  import {
31
31
  SHARED_CLAUDE_VOLUME,
32
32
  SHARED_CODEX_VOLUME,
@@ -35,7 +35,7 @@ import {
35
35
  } from "./chunk-I2DEYQLZ.js";
36
36
  import {
37
37
  getRuntimeProviderNames
38
- } from "./chunk-I7BSBUPC.js";
38
+ } from "./chunk-P5A6MT75.js";
39
39
  import {
40
40
  DEFAULT_BOX_IMAGE,
41
41
  imageInfo
@@ -78,6 +78,7 @@ async function bakeViaHub(args) {
78
78
  const streaming = args.client.streamJobLog(jobId, args.onLog, abort.signal).catch(() => void 0);
79
79
  const deadline = Date.now() + BAKE_TIMEOUT_MS;
80
80
  let status = "queued";
81
+ let jobError;
81
82
  try {
82
83
  for (; ; ) {
83
84
  await delay(JOB_POLL_MS);
@@ -87,6 +88,7 @@ async function bakeViaHub(args) {
87
88
  break;
88
89
  }
89
90
  status = job.status;
91
+ jobError = job.error;
90
92
  if (status === "done" || status === "failed" || status === "cancelled") break;
91
93
  if (Date.now() > deadline) {
92
94
  return {
@@ -100,7 +102,12 @@ async function bakeViaHub(args) {
100
102
  await streaming;
101
103
  }
102
104
  if (status !== "done") {
103
- return { status: "failed", detail: `the control box's bake job ${jobId} ended ${status}` };
105
+ const reason = jobError?.trim();
106
+ return {
107
+ status: "failed",
108
+ detail: reason ? `${reason}
109
+ (control box bake job ${jobId} ended ${status})` : `the control box's bake job ${jobId} ended ${status}`
110
+ };
104
111
  }
105
112
  if (args.remoteHost) return { status: "adopted" };
106
113
  if (args.coLocated) return { status: "adopted" };
@@ -190,7 +197,7 @@ async function renderDocker(status) {
190
197
  }
191
198
  async function daytonaStatus() {
192
199
  try {
193
- const mod = await import("./dist-NFF2KEMB.js");
200
+ const mod = await import("./dist-GMIBT6IK.js");
194
201
  return await mod.getDaytonaStatus();
195
202
  } catch (err) {
196
203
  return {
@@ -201,7 +208,7 @@ async function daytonaStatus() {
201
208
  }
202
209
  async function e2bStatus() {
203
210
  try {
204
- const mod = await import("./dist-E5EXDZG4.js");
211
+ const mod = await import("./dist-Y2GCMA6N.js");
205
212
  const cred = mod.readE2bCredStatus();
206
213
  if (cred.auth === "none") {
207
214
  return { configured: false, reason: "not configured \u2014 run `agentbox e2b login`" };
@@ -324,7 +331,7 @@ async function showStatus(opts) {
324
331
  process.stdout.write(lines.join("\n") + "\n");
325
332
  }
326
333
  async function hubIsCoLocated() {
327
- const { resolveHubTarget } = await import("./hub-3HPYOV5O.js");
334
+ const { resolveHubTarget } = await import("./hub-53E6EFZB.js");
328
335
  const target = await resolveHubTarget(void 0).catch(() => null);
329
336
  if (target?.mode === "local") return true;
330
337
  return await localExposedLoopbackUrl().catch(() => null) !== null;
@@ -505,4 +512,4 @@ export {
505
512
  runPrepare,
506
513
  prepareCommand
507
514
  };
508
- //# sourceMappingURL=chunk-PFEBKXFD.js.map
515
+ //# sourceMappingURL=chunk-6UCHNX75.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/prepare.ts","../src/control-plane/hub-prepare.ts"],"sourcesContent":["/**\n * `agentbox prepare` — provider-neutral \"build the base image\" command.\n *\n * Three modes:\n *\n * - `agentbox prepare` → status only: show the inventory of\n * prepared base images / shared\n * volumes across all providers, plus\n * the project's pinned `box.image`.\n * - `agentbox prepare --provider X` → run prepare for X, then re-print\n * the relevant status section.\n * - `agentbox prepare --status` → status only (explicit; same as\n * no-args, but useful when scripted).\n *\n * Docker `prepare` builds `agentbox/box:dev` locally. Daytona `prepare`\n * builds a layered `Image` (Dockerfile.box + the three agent static tarballs)\n * and registers it via `daytona.snapshot.create({ name, image })`, then pins\n * `box.image: <name>` into the project config.\n *\n * Replaces the old `agentbox daytona publish-snapshot` (which used the\n * broken `_experimental_createSnapshot` API).\n */\n\nimport { intro, log, spinner } from '@clack/prompts';\nimport { loadEffectiveConfig, unsetConfigValue } from '@agentbox/config';\nimport {\n DEFAULT_BOX_IMAGE,\n SHARED_CLAUDE_VOLUME,\n SHARED_CODEX_VOLUME,\n SHARED_OPENCODE_VOLUME,\n imageInfo,\n volumeExists,\n type ImageInfo,\n} from '@agentbox/sandbox-docker';\nimport { Command } from 'commander';\nimport { UserFacingError } from '@agentbox/core';\nimport type { Provider } from '@agentbox/core';\nimport { getProvider, isKnownProvider } from '../provider/registry.js';\nimport { getRuntimeProviderNames } from '../provider/loaders.js';\nimport { parseProviderSpec } from '../provider/spec.js';\nimport { deadlineFetch, hostReachable } from '@agentbox/sandbox-cloud';\nimport { controlBoxKnowsHost } from '../control-plane/remote-docker-share.js';\nimport { bakeViaHub } from '../control-plane/hub-prepare.js';\nimport { dockerProviderRefusal } from '../control-plane/remote-hub.js';\nimport { HubApiClient } from '../control-plane/hub-api-client.js';\nimport {\n localExposedLoopbackUrl,\n resolveCustodyTarget,\n resolveHubApiClient,\n resolveHubApiTarget,\n} from './control-plane.js';\n\ninterface PrepareOptions {\n provider?: string;\n force?: boolean;\n yes?: boolean;\n status?: boolean;\n claudeInstall?: string;\n build?: boolean;\n name?: string;\n location?: string;\n size?: string;\n}\n\ninterface DockerStatus {\n daemon: 'reachable' | 'unreachable';\n image?: ImageInfo;\n volumes: Array<{ name: string; exists: boolean }>;\n}\n\nasync function dockerStatus(): Promise<DockerStatus> {\n let img: ImageInfo;\n try {\n img = await imageInfo(DEFAULT_BOX_IMAGE);\n } catch {\n return { daemon: 'unreachable', volumes: [] };\n }\n const names = [SHARED_CLAUDE_VOLUME, SHARED_CODEX_VOLUME, SHARED_OPENCODE_VOLUME];\n const volumes = await Promise.all(\n names.map(async (name) => ({ name, exists: await volumeExists(name).catch(() => false) })),\n );\n return { daemon: 'reachable', image: img, volumes };\n}\n\nfunction humanBytes(n?: number): string {\n if (n === undefined || !Number.isFinite(n)) return '—';\n if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`;\n if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`;\n if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`;\n return `${String(n)} B`;\n}\n\nfunction humanAge(iso?: string): string {\n if (!iso) return '—';\n const t = Date.parse(iso);\n if (!Number.isFinite(t)) return iso;\n const ageSec = Math.max(0, (Date.now() - t) / 1000);\n if (ageSec < 60) return `${ageSec.toFixed(0)}s ago`;\n if (ageSec < 3600) return `${(ageSec / 60).toFixed(0)}m ago`;\n if (ageSec < 86400) return `${(ageSec / 3600).toFixed(1)}h ago`;\n return `${(ageSec / 86400).toFixed(1)}d ago`;\n}\n\nfunction pad(s: string, width: number): string {\n return s.length >= width ? s : s + ' '.repeat(width - s.length);\n}\n\nasync function renderDocker(status: DockerStatus): Promise<string[]> {\n const out: string[] = ['docker:'];\n if (status.daemon === 'unreachable') {\n out.push(' docker daemon unreachable (is Docker running?)');\n return out;\n }\n if (!status.image?.exists) {\n out.push(\n ` image ${DEFAULT_BOX_IMAGE} (not built — run \\`agentbox prepare --provider docker\\`)`,\n );\n } else {\n out.push(\n ` image ${pad(DEFAULT_BOX_IMAGE, 30)} ${pad(humanBytes(status.image.sizeBytes), 10)} built ${humanAge(status.image.createdAt)}`,\n );\n }\n for (const v of status.volumes) {\n if (v.exists) {\n out.push(` vol ${pad(v.name, 30)} present`);\n } else {\n out.push(\n ` vol ${pad(v.name, 30)} (none — seeded lazily on first \\`agentbox claude/codex/opencode\\`)`,\n );\n }\n }\n return out;\n}\n\ninterface DaytonaStatusUnknown {\n configured: false;\n reason?: string;\n}\ninterface DaytonaStatusOk {\n configured: true;\n snapshots: Array<{\n name: string;\n state?: string;\n sizeGb?: number;\n createdAt?: string;\n errorReason?: string;\n }>;\n volumes: Array<{ name: string; state?: string; lastUsedAt?: string }>;\n reason?: string;\n}\ntype DaytonaStatusResult = DaytonaStatusUnknown | DaytonaStatusOk;\n\nasync function daytonaStatus(): Promise<DaytonaStatusResult> {\n try {\n const mod = await import('@agentbox/sandbox-daytona');\n return (await mod.getDaytonaStatus()) as DaytonaStatusResult;\n } catch (err) {\n return {\n configured: false,\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n}\n\ninterface E2bStatusUnknown {\n configured: false;\n reason?: string;\n}\ninterface E2bStatusOk {\n configured: true;\n templateId?: string;\n templateName?: string;\n createdAt?: string;\n cliVersion?: string;\n contextSha256?: string;\n}\ntype E2bStatusResult = E2bStatusUnknown | E2bStatusOk;\n\nasync function e2bStatus(): Promise<E2bStatusResult> {\n try {\n const mod = await import('@agentbox/sandbox-e2b');\n const cred = mod.readE2bCredStatus();\n if (cred.auth === 'none') {\n return { configured: false, reason: 'not configured — run `agentbox e2b login`' };\n }\n const prepared = mod.readPreparedState();\n if (!prepared.base) return { configured: true };\n return {\n configured: true,\n templateId: prepared.base.templateId,\n templateName: prepared.base.templateName,\n createdAt: prepared.base.createdAt,\n cliVersion: prepared.base.cliVersion,\n contextSha256: prepared.base.contextSha256,\n };\n } catch (err) {\n return {\n configured: false,\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n}\n\nfunction renderE2b(status: E2bStatusResult, pinnedImage?: string): string[] {\n const out: string[] = ['e2b:'];\n if (!status.configured) {\n out.push(` ${status.reason ?? '(not configured)'}`);\n return out;\n }\n if (!status.templateId) {\n out.push(' no agentbox template — run `agentbox prepare --provider e2b`');\n return out;\n }\n const pinned = pinnedImage && pinnedImage === status.templateId ? ' (pinned in project)' : '';\n out.push(\n ` tmpl ${pad(status.templateName ?? status.templateId, 40)} ${pad(status.cliVersion ?? '—', 10)} ${humanAge(status.createdAt)}${pinned}`,\n );\n return out;\n}\n\nfunction renderDaytona(status: DaytonaStatusResult, pinnedImage?: string): string[] {\n const out: string[] = ['daytona:'];\n if (!status.configured) {\n out.push(\n ` (not configured — \\`agentbox daytona login\\` to set up${status.reason ? `; ${status.reason}` : ''})`,\n );\n return out;\n }\n if (status.reason) out.push(` warn: ${status.reason}`);\n if (status.snapshots.length === 0) {\n out.push(' no agentbox snapshots — run `agentbox prepare --provider daytona`');\n } else {\n for (const s of status.snapshots) {\n const sizeStr = s.sizeGb !== undefined ? `${s.sizeGb.toFixed(2)} GB` : '—';\n const pinned = pinnedImage && pinnedImage === s.name ? ' (pinned in project)' : '';\n const tail =\n s.state === 'error' && s.errorReason\n ? ` error: ${s.errorReason.slice(0, 80)}`\n : ` ${humanAge(s.createdAt)}`;\n out.push(\n ` snap ${pad(s.name, 40)} ${pad(s.state ?? '—', 10)} ${pad(sizeStr, 10)}${tail}${pinned}`,\n );\n }\n }\n if (status.volumes.length === 0) {\n out.push(' no agentbox volumes — created lazily on first cloud `agentbox create`');\n } else {\n for (const v of status.volumes) {\n const last = v.lastUsedAt ? ` last used ${humanAge(v.lastUsedAt)}` : '';\n out.push(` vol ${pad(v.name, 40)} ${pad(v.state ?? '—', 10)}${last}`);\n }\n }\n return out;\n}\n\n/**\n * Bound on the control-box status read. `?freshness=1` makes the hub hash its\n * own build context, so it is not instant — but this is an interactive status\n * command, and an unreachable box must cost a fixed, small amount of time.\n */\nconst CONTROL_BOX_STATUS_MS = 5000;\n\n/**\n * The control box's own provider inventory, or nothing when none is configured\n * (or it can't be reached — a status command must never hang or fail on it).\n *\n * Only shown for a GENUINELY remote control box: a co-located hub (a local hub,\n * or `hub expose` on this machine) bakes on this same machine, so the local\n * provider rows already describe it and a second \"control box\" section would just\n * mislabel it. Exported so `agentbox doctor` shows the same section.\n */\nexport async function renderControlBoxProviders(): Promise<string[]> {\n if (await hubIsCoLocated().catch(() => true)) return [];\n const target = await resolveHubApiTarget(undefined, { quiet: true }).catch(() => null);\n if (!target) return [];\n // Probe with a socket we own before spending the budget: a fetch to an\n // unreachable host can't be cancelled, and this is a status command.\n if (!(await hostReachable(target.url, CONTROL_BOX_STATUS_MS))) {\n return ['', 'control box: unreachable — could not read its baked providers'];\n }\n const client = new HubApiClient({\n ...target,\n fetchImpl: deadlineFetch(AbortSignal.timeout(CONTROL_BOX_STATUS_MS)),\n });\n const providers = await client.listProviders({ freshness: true }).catch(() => null);\n if (!providers) return ['', 'control box: unreachable — could not read its baked providers'];\n const cloud = providers.filter((p) => p.id !== 'docker' && p.id !== 'remote-docker');\n if (cloud.length === 0) return [];\n const out = ['', 'control box (where cloud boxes are built):'];\n for (const p of cloud) {\n const state = !p.hasCredentials\n ? 'no credentials'\n : !p.configured\n ? 'not baked'\n : (p.baseStatus ?? 'baked');\n out.push(` ${pad(p.id, 16)} ${state}`);\n }\n return out;\n}\n\nasync function showStatus(opts: { onlyProvider?: string }): Promise<void> {\n const cfg = await loadEffectiveConfig(process.cwd()).catch(() => null);\n const pinnedRaw = cfg?.effective.box.image;\n // Only treat as \"user-pinned\" if it differs from the docker default tag\n // — that one is just the fallback ref the docker provider builds locally.\n const pinned =\n typeof pinnedRaw === 'string' && pinnedRaw.length > 0 && pinnedRaw !== DEFAULT_BOX_IMAGE\n ? pinnedRaw\n : undefined;\n const lines: string[] = [];\n\n const wantDocker = !opts.onlyProvider || opts.onlyProvider === 'docker';\n const wantDaytona = !opts.onlyProvider || opts.onlyProvider === 'daytona';\n const wantE2b = !opts.onlyProvider || opts.onlyProvider === 'e2b';\n\n if (wantDocker) {\n const status = await dockerStatus();\n lines.push(...(await renderDocker(status)));\n }\n if (wantDaytona) {\n if (lines.length > 0) lines.push('');\n const status = await daytonaStatus();\n lines.push(...renderDaytona(status, pinned));\n }\n if (wantE2b) {\n if (lines.length > 0) lines.push('');\n const status = await e2bStatus();\n // Use the per-provider pin (box.imageE2b) so the marker tracks the right key.\n const e2bPinned =\n typeof cfg?.effective.box.imageE2b === 'string' && cfg.effective.box.imageE2b.length > 0\n ? cfg.effective.box.imageE2b\n : undefined;\n lines.push(...renderE2b(status, e2bPinned));\n }\n if (pinned) {\n lines.push('');\n lines.push(`project pin: box.image = ${pinned}`);\n }\n // With a control box configured, ITS bakes are the ones a cloud create boots —\n // so an inventory that only ever showed this machine's was describing the\n // wrong host. Appended, never substituted: the local rows still matter for\n // docker (always built on this machine) and for the co-located-hub case.\n if (!opts.onlyProvider) lines.push(...(await renderControlBoxProviders()));\n process.stdout.write(lines.join('\\n') + '\\n');\n}\n\nexport interface RunPrepareOptions {\n /** Rebuild even if the image / snapshot already exists. */\n force?: boolean;\n /** Skip the Daytona cost-notice. */\n yes?: boolean;\n /** Host workspace dir (defaults to `process.cwd()`). */\n cwd?: string;\n /** Suppress the post-prepare status block. */\n suppressStatus?: boolean;\n /**\n * How the bake installs Claude Code (`native` | `npm`). CLI override of the\n * `box.claudeInstall` config key; falls back to the effective config.\n */\n claudeInstall?: 'native' | 'npm';\n /**\n * Bake INPUTS (not routing) threaded to the hub bake. Each is a per-invocation\n * override; when absent the hub worker fills it from its effective config.\n * - `build`: force a local docker build instead of pulling the registry base.\n * - `size`: bake-time VM size (daytona `cpu-mem-disk`, e2b `cpu-mem`).\n * - `location`: bake datacenter / region (hetzner / digitalocean / daytona).\n * - `name`: snapshot name (daytona).\n */\n build?: boolean;\n size?: string;\n location?: string;\n name?: string;\n}\n\n/**\n * Whether the hub the bake will run on is THIS machine (a local hub, or a control\n * box exposed on loopback via `hub expose`). Decides whether the prepared-state\n * the worker writes is already here (co-located → nothing to adopt) or on a remote\n * control box's disk (adopt the record back from custody).\n */\nasync function hubIsCoLocated(): Promise<boolean> {\n // Lazy import mirrors resolveHubApiTarget's cycle-avoidance (hub.ts <->\n // control-plane.ts). `hub expose` on this machine reports mode 'remote' but is\n // still co-located, so the loopback check is the second half of the answer.\n const { resolveHubTarget } = await import('./hub.js');\n const target = await resolveHubTarget(undefined).catch(() => null);\n if (target?.mode === 'local') return true;\n return (await localExposedLoopbackUrl().catch(() => null)) !== null;\n}\n\n/**\n * Pure decision: does a bake target the LOCAL hub (`local: true`) or the remote\n * control box (`false`)? This is target selection only — the bake always runs\n * through the same `POST /api/v1/providers/:id/prepare` (or `/hosts/:alias/bake`)\n * route; there is NO inline `provider.prepare` path, which is exactly the second\n * implementation this consolidation exists to delete. The choice is only ever\n * WHICH base URL the one client points at.\n *\n * Extracted pure (IO done by {@link shouldPreferLocalHub}) so the routing is\n * unit-testable — the deleted `resolvePrepareRouting` had this same shape, and\n * dropping it is what regressed the `cloud.viaHub` and remote-docker fallbacks.\n *\n * Local wins when:\n * - the hub is already co-located (no control box, or `hub expose` here);\n * - `cloud.viaHub=false` — the user keeps builds on their own machine even with\n * a control plane configured (the config KEY survives; only the `--local` /\n * `--via-hub` flags were dropped);\n * - `docker`, whose base is an image on THIS machine — baking it on the control\n * box would produce an image on the wrong host;\n * - `remote-docker` whose host alias the control box doesn't know, but the local\n * hub (this machine's `~/.ssh`) does.\n * Otherwise the control box is the target (the default for cloud bakes).\n */\nexport function resolvePrepareTargetKind(input: {\n /** The default hub is already on this machine (local, or `hub expose` here). */\n coLocated: boolean;\n /** `relay.controlPlaneUrl` — a genuine remote control box is configured. */\n controlPlaneUrl: string | undefined;\n /** `cloud.viaHub` — build cloud boxes / bases on the control box by default. */\n viaHub: boolean;\n providerName: string;\n remoteHost?: string;\n /** remote-docker only: whether the control box has the host alias registered. */\n controlBoxKnowsHost?: boolean;\n}): { local: boolean; reason?: string } {\n if (input.coLocated) return { local: true };\n if (!input.controlPlaneUrl) return { local: true };\n if (!input.viaHub) return { local: true, reason: 'cloud.viaHub is off — baking on this machine' };\n if (input.providerName === 'docker') return { local: true };\n if (input.providerName === 'remote-docker' && input.remoteHost && !input.controlBoxKnowsHost) {\n return {\n local: true,\n reason: `the control box has no \\`${input.remoteHost}\\` host registered — baking on this machine's hub`,\n };\n }\n return { local: false };\n}\n\n/**\n * IO wrapper around {@link resolvePrepareTargetKind}: resolves co-location, the\n * effective config, and — only for a remote-docker host that could actually\n * target the control box — the alias check.\n */\nasync function shouldPreferLocalHub(\n providerName: string,\n remoteHost: string | undefined,\n): Promise<{ local: boolean; reason?: string }> {\n const coLocated = await hubIsCoLocated();\n const cfg = await loadEffectiveConfig(process.cwd()).catch(() => null);\n const eff = cfg?.effective;\n const controlPlaneUrl = eff?.relay.controlPlaneUrl;\n const viaHub = eff?.cloud.viaHub ?? true;\n // The alias check is the only networked input, and only remote-docker needs it.\n // Skip it whenever an earlier rule already forces local (no control box,\n // co-located, or cloud.viaHub off) so a normal bake makes no extra round-trip.\n const knowsHost =\n providerName === 'remote-docker' && remoteHost && controlPlaneUrl && viaHub && !coLocated && eff\n ? await controlBoxKnowsHost(remoteHost, eff)\n : undefined;\n return resolvePrepareTargetKind({\n coLocated,\n controlPlaneUrl,\n viaHub,\n providerName,\n remoteHost,\n controlBoxKnowsHost: knowsHost,\n });\n}\n\n/**\n * Bake `providerName` THROUGH the hub — the one prepare path (local hub or remote\n * control box). Throws on failure so internal callers (`install`, the create\n * wizard's stale-base rebuild) can catch it; the top-level command surfaces it.\n * The failure path deliberately does NOT fall back to a local bake: a hub bake\n * that failed for a real reason (no credentials there, a broken build context)\n * would fail the same way here.\n */\nasync function runPrepareViaHub(args: {\n providerName: string;\n provider: Provider;\n force?: boolean;\n claudeInstall: 'native' | 'npm';\n build?: boolean;\n size?: string;\n location?: string;\n name?: string;\n remoteHost?: string;\n suppressStatus?: boolean;\n}): Promise<void> {\n // WHICH hub: the local hub on this machine, or the remote control box. Same\n // route either way — target selection, never an inline bake.\n const target = await shouldPreferLocalHub(args.providerName, args.remoteHost);\n if (target.reason) log.info(target.reason);\n // Auto-starts a local hub when that is the target (Step 0). A remote control\n // box with no API key returns null after printing why.\n const client = await resolveHubApiClient(undefined, { preferLocal: target.local });\n // resolveHubApiClient already printed why (no API key, hub wouldn't start).\n if (!client) throw new UserFacingError('could not reach a hub to run the bake');\n // The local hub's worker writes the prepared-state straight to this machine, so\n // choosing local IS the co-located signal — no custody round-trip to adopt.\n const coLocated = target.local;\n // Custody is only the remote-adopt channel; a co-located hub wrote the record\n // straight to this machine, so skip resolving it (and its error path) there.\n const custody = coLocated ? null : await resolveCustodyTarget(undefined, { quiet: true });\n const where = coLocated ? 'hub' : 'control box';\n const what = args.remoteHost ? `${args.providerName} host ${args.remoteHost}` : args.providerName;\n const sp = spinner();\n sp.start(`preparing ${what} on the ${where}…`);\n const outcome = await bakeViaHub({\n client,\n providerName: args.providerName,\n provider: args.provider,\n force: args.force,\n claudeInstall: args.claudeInstall,\n build: args.build,\n size: args.size,\n location: args.location,\n name: args.name,\n custody,\n coLocated,\n remoteHost: args.remoteHost,\n onLog: (line) => sp.message(line.slice(0, 80)),\n });\n if (outcome.status === 'failed') {\n sp.stop(`prepare failed on the ${where}: ${outcome.detail}`);\n throw new Error(outcome.detail);\n }\n sp.stop(`prepared ${what} on the ${where}`);\n if (outcome.status === 'baked-not-adopted') {\n // The hub can now create with it; this machine just can't verify it locally.\n log.warn(`${outcome.detail} — cloud creates route to the control box, so this is not fatal`);\n } else if (coLocated) {\n log.success(`prepared ${args.providerName}`);\n } else {\n log.success(\n args.remoteHost\n ? `baked ${args.remoteHost} from the control box — the image is on that host, so this machine sees it too`\n : `adopted the control box's ${args.providerName} base — this machine is current too`,\n );\n }\n // One-shot migration of a stale generic `box.image`. Pre-fix builds wrote every\n // cloud prepare's snapshot id into the shared key, so any non-default value\n // still there poisons every provider that doesn't recognize it. Best-effort —\n // never fail the command on it.\n try {\n const projectCfg = await loadEffectiveConfig(process.cwd()).catch(() => null);\n const projectImage = projectCfg?.layers.project.values.box?.image;\n if (\n typeof projectImage === 'string' &&\n projectImage.length > 0 &&\n projectImage !== DEFAULT_BOX_IMAGE\n ) {\n const cleared = await unsetConfigValue('project', 'box.image', process.cwd());\n if (cleared.existed) {\n log.warn(\n `migrated stale \\`box.image\\` from a previous prepare (was \\`${projectImage}\\`); ` +\n `re-set manually if you actually meant it: \\`agentbox config set --project box.image <ref>\\``,\n );\n }\n }\n } catch (err) {\n log.warn(\n `could not migrate stale box.image (continuing): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (!args.suppressStatus) {\n process.stdout.write('\\n');\n await showStatus({ onlyProvider: args.providerName });\n }\n}\n\n/**\n * Prepare `providerName`'s base — the single entry point the `prepare` command,\n * the install wizard, and the create-time stale-base rebuild all share. The bake\n * ALWAYS runs on the hub (Step 1 of the `/api/v1` consolidation): a local hub is\n * co-located so the artifact lands here, a remote control box is where cloud boxes\n * are built and the record is adopted back. Caller owns any `intro(...)` framing;\n * this manages its own spinner.\n */\nexport async function runPrepare(\n providerSpec: string,\n opts: RunPrepareOptions = {},\n): Promise<void> {\n // Throw, never exit: `runPrepare` is called from the install wizard, the\n // create-time stale-base rebuild and `remote-docker add` — a bare exit would\n // kill those mid-flow instead of letting them report. The `prepare` command\n // itself is unchanged: printCliError renders a UserFacingError's message bare\n // and exits 1, exactly what these did.\n if (!isKnownProvider(providerSpec)) {\n throw new UserFacingError(\n `error: --provider must be one of: ${getRuntimeProviderNames().join(', ')}`,\n );\n }\n // `--provider docker:<host>` bakes the image on that machine's engine. Split\n // the spec: the bare name drives every provider lookup, the host is baked via\n // the hub's per-host endpoint.\n const { name: providerName, remoteHost } = parseProviderSpec(providerSpec);\n\n if (providerName === 'daytona' && !opts.yes && process.stdin.isTTY) {\n process.stdout.write(\n 'This will trigger a Daytona image build (~7 min cold, ~seconds with cache) and ' +\n 'register a named snapshot in your org.\\n' +\n 'Re-run with --yes to skip this notice.\\n',\n );\n }\n\n const provider = await getProvider(providerName);\n if (typeof provider.prepare !== 'function') {\n throw new UserFacingError(`provider '${providerName}' does not implement prepare`);\n }\n\n const cwd = opts.cwd ?? process.cwd();\n const cfg = await loadEffectiveConfig(cwd).catch(() => null);\n // Docker off under a remote hub (Step 12): don't bake a local docker/remote-docker\n // image when a control box owns the fleet. `local` mode (or no cfg) keeps it on.\n if (cfg) {\n const refusal = await dockerProviderRefusal(cfg.effective, providerName, remoteHost, 'prepare');\n if (refusal) throw new UserFacingError(refusal);\n }\n // Bake-time Claude install method: CLI flag wins over the config key. The\n // remaining bake INPUTS (`build` / `size` / `location` / `name`) are passed\n // through only when the user set the corresponding flag; the hub worker fills\n // any that are absent from ITS effective config (size/region/sandbox class),\n // so one route body serves every bake shape (plan Step 1).\n const claudeInstall = opts.claudeInstall ?? cfg?.effective.box.claudeInstall ?? 'native';\n // remote-docker: the `docker:<host>` spec first, else the configured default.\n const host =\n providerName === 'remote-docker'\n ? remoteHost || cfg?.effective.box.remoteDockerHost || undefined\n : undefined;\n\n await runPrepareViaHub({\n providerName,\n provider,\n force: opts.force,\n claudeInstall,\n build: opts.build,\n size: opts.size,\n location: opts.location,\n name: opts.name,\n remoteHost: host,\n suppressStatus: opts.suppressStatus,\n });\n}\n\nexport const prepareCommand = new Command('prepare')\n .description(\n 'Build base sandbox images / snapshots, or show what is already prepared across providers. ' +\n 'The bake always runs on the hub — a local hub is this machine; with a control box configured, ' +\n 'it runs there (where cloud boxes are built) and the record is adopted back.',\n )\n .option(\n '-p, --provider <name>',\n 'provider to prepare (docker | daytona | hetzner | vercel | e2b | digitalocean). Omit for status-only.',\n )\n .option('-n, --name <name>', 'snapshot name (Daytona only; default: agentbox-base-<timestamp>)')\n .option('-f, --force', 'rebuild even if the image / snapshot already exists')\n .option(\n '--build',\n 'docker: build the base image locally instead of pulling the prebuilt one from the registry',\n )\n .option('-y, --yes', 'skip confirmation prompts (cost / time warnings)')\n .option('--status', 'show status without preparing anything')\n .option(\n '--claude-install <mode>',\n 'install Claude Code into the base image via the native installer (default) or npm (native | npm)',\n )\n .option(\n '--location <name>',\n 'Datacenter/region the bake VPS runs in. Hetzner: nbg1, fsn1, hel1, ash (overrides box.hetznerLocation). DigitalOcean: nyc3, sfo3, ams3, fra1 (overrides box.digitaloceanRegion). Hetzner/DigitalOcean-only.',\n )\n .option(\n '--size <spec>',\n 'bake-time VM size. daytona: cpu-memory-disk GB (e.g. 4-8-20). e2b: cpu-memory GB (e.g. 4-8). Overrides box.size / box.size<Provider>. Ignored by docker/hetzner/vercel.',\n )\n .action(async (opts: PrepareOptions) => {\n // Status-only path: no provider, or explicit --status.\n if (!opts.provider || opts.status) {\n await showStatus({});\n return;\n }\n\n let claudeInstall: 'native' | 'npm' | undefined;\n if (opts.claudeInstall !== undefined) {\n if (opts.claudeInstall !== 'native' && opts.claudeInstall !== 'npm') {\n process.stderr.write('error: --claude-install must be one of: native, npm\\n');\n process.exit(1);\n }\n claudeInstall = opts.claudeInstall;\n }\n\n const providerName = opts.provider.trim();\n intro(`preparing ${providerName} base image`);\n // Errors propagate to `program.parseAsync().catch` so they reach the user\n // via `console.error` — a bare `catch { process.exit(1) }` here would\n // silently swallow getProvider() failures (e.g. an ensureCredentials cancel)\n // that fall outside runPrepare's inner spinner error handler.\n await runPrepare(providerName, {\n force: opts.force,\n yes: opts.yes,\n claudeInstall,\n build: opts.build,\n size: opts.size,\n location: opts.location,\n name: opts.name,\n });\n });\n","/**\n * Bake a provider's base THROUGH the hub, from this machine — the one prepare\n * path, local hub or remote control box alike (`docs/hub-api-single-path-plan.md`\n * Step 1). The hub runs the bake in its own queue worker; this drives it and\n * reports the verdict.\n *\n * Two shapes, decided by whether the hub is co-located with this CLI:\n * - **Co-located** (a local hub, or `hub expose` on this machine): the worker\n * writes the prepared-state to THIS machine's `~/.agentbox` directly, so\n * there is nothing to adopt — a `done` job is the whole story.\n * - **Remote control box**: the worker wrote the record to ITS disk + custody;\n * we pull it back so both machines end up current from one bake. (With\n * `cloud.viaHub`, a cloud box is also built there, so baking there is where\n * the snapshot needs to live anyway.)\n *\n * The hub already exposes everything this needs (`POST /api/v1/providers/:id/prepare`,\n * `GET /api/v1/jobs/:id`, `GET /api/v1/jobs/:id/logs`); nothing new on that side.\n */\nimport { pullPreparedFromCustody } from '@agentbox/sandbox-cloud';\nimport type { Provider } from '@agentbox/core';\nimport { HubApiError, type HubApiClient } from './hub-api-client.js';\nimport { pinAdoptedBase } from './prepared-custody.js';\n\n/** How often the job's terminal status is re-checked while the log streams. */\nconst JOB_POLL_MS = 3000;\n/**\n * Cap on a single bake. Generous: a cold daytona/e2b image build is genuinely\n * ~10 minutes, and a bake that outlives this is still running on the hub — the\n * user is told where to watch it rather than left with a hung terminal.\n */\nconst BAKE_TIMEOUT_MS = 45 * 60_000;\n\nexport type HubBakeOutcome =\n /**\n * The hub baked it and the result is current on THIS machine — either a\n * co-located hub wrote the prepared-state here directly, or we adopted a remote\n * control box's record. Nothing left to do.\n */\n | { status: 'adopted' }\n /** The hub baked it, but its record didn't reach our prepared-state. */\n | { status: 'baked-not-adopted'; detail: string }\n | { status: 'failed'; detail: string };\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Run a bake on the control box and adopt the resulting record.\n *\n * The log stream is advisory — a dropped connection must never read as a\n * successful bake — so the verdict always comes from polling the job itself.\n */\nexport async function bakeViaHub(args: {\n client: HubApiClient;\n providerName: string;\n provider: Provider;\n force?: boolean;\n claudeInstall: 'native' | 'npm';\n /**\n * Bake INPUTS threaded from the CLI's flags (`--build` / `--size` / `--location`\n * / `--name`). They ride the same route body; the hub worker fills any that are\n * absent from its own effective config. Not routing — see the plan's Step 1.\n */\n build?: boolean;\n size?: string;\n location?: string;\n name?: string;\n custody: { url: string; adminToken: string } | null;\n /**\n * Whether the hub runs on THIS machine (a local hub, or `hub expose`). When\n * true, the worker's prepared-state write already lands in this machine's\n * `~/.agentbox`, so there is no custody round-trip to adopt.\n */\n coLocated: boolean;\n /**\n * remote-docker only: the host alias to bake. It goes to a different endpoint\n * (`/hosts/:alias/bake`), because the unit of a remote-docker base is a host,\n * not the provider — there is no single `remote-docker` base to prepare.\n */\n remoteHost?: string;\n onLog: (line: string) => void;\n}): Promise<HubBakeOutcome> {\n let jobId: string;\n try {\n jobId = args.remoteHost\n ? await args.client.bakeHost(args.remoteHost)\n : await args.client.prepareProvider(args.providerName, {\n force: args.force,\n claudeInstall: args.claudeInstall,\n build: args.build,\n size: args.size,\n location: args.location,\n name: args.name,\n });\n } catch (err) {\n // A precheck failure on the hub (no credentials there, docker down) is a\n // 409 with a real message — surface it verbatim rather than as \"failed\".\n const detail =\n err instanceof HubApiError ? err.message : err instanceof Error ? err.message : String(err);\n return { status: 'failed', detail };\n }\n\n const abort = new AbortController();\n // Fire-and-forget: the stream ends when the hub closes it. Errors are ignored\n // on purpose — losing the log must not lose the bake.\n const streaming = args.client\n .streamJobLog(jobId, args.onLog, abort.signal)\n .catch(() => undefined);\n\n const deadline = Date.now() + BAKE_TIMEOUT_MS;\n let status = 'queued';\n try {\n for (;;) {\n await delay(JOB_POLL_MS);\n const job = await args.client.getJob(jobId).catch(() => null);\n // A job that vanished (hub restarted mid-bake) is not a success.\n if (!job) {\n status = 'gone';\n break;\n }\n status = job.status;\n if (status === 'done' || status === 'failed' || status === 'cancelled') break;\n if (Date.now() > deadline) {\n return {\n status: 'failed',\n detail: `the bake is still running on the control box after ${String(Math.round(BAKE_TIMEOUT_MS / 60_000))} minutes — watch job ${jobId} there`,\n };\n }\n }\n } finally {\n abort.abort();\n await streaming;\n }\n\n if (status !== 'done') {\n return { status: 'failed', detail: `the control box's bake job ${jobId} ended ${status}` };\n }\n\n // A remote-docker bake put the image on the REMOTE HOST, which this machine\n // reaches too, and \"is that host baked?\" is answered by asking its engine —\n // never by a local file. So there is nothing to adopt, and nothing to pin.\n // (The local `remote-docker-prepared.json` history stays silent about a bake\n // this machine didn't run; that file is explicitly a log for `prepare\n // --status` / `doctor`, not the readiness check.)\n if (args.remoteHost) return { status: 'adopted' };\n\n // Co-located hub (local, or `hub expose`): the worker wrote the prepared-state\n // straight into this machine's `~/.agentbox` and pinned the config, so a `done`\n // job means the base is already current here. No custody round-trip.\n if (args.coLocated) return { status: 'adopted' };\n\n // The hub's bake wrote its record into custody (`sharePreparedBase` →\n // `writePreparedToCustodyStore`), so adopting is a plain custody read.\n if (!args.custody) {\n return {\n status: 'baked-not-adopted',\n detail: 'no control-box admin token, so its bake record could not be read back',\n };\n }\n const fingerprint = await Promise.resolve(args.provider.baseFingerprint?.('native')).catch(\n () => undefined,\n );\n const res = await pullPreparedFromCustody(args.providerName, fingerprint, {\n controlPlaneUrl: args.custody.url,\n adminToken: args.custody.adminToken,\n log: args.onLog,\n }).catch(() => ({ adopted: false, record: undefined }));\n if (!res.adopted) {\n return {\n status: 'baked-not-adopted',\n detail: `the control box baked ${args.providerName}, but its record does not match this machine's build context`,\n };\n }\n // Same pin a local bake writes: some providers (daytona) resolve their base\n // from `box.image<Provider>`, not from prepared-state.\n await pinAdoptedBase(args.providerName, res.record, args.onLog);\n return { status: 'adopted' };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAS,OAAO,KAAK,eAAe;AAWpC,SAAS,eAAe;;;ACVxB,IAAM,cAAc;AAMpB,IAAM,kBAAkB,KAAK;AAa7B,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAQA,eAAsB,WAAW,MA6BL;AAC1B,MAAI;AACJ,MAAI;AACF,YAAQ,KAAK,aACT,MAAM,KAAK,OAAO,SAAS,KAAK,UAAU,IAC1C,MAAM,KAAK,OAAO,gBAAgB,KAAK,cAAc;AAAA,MACnD,OAAO,KAAK;AAAA,MACZ,eAAe,KAAK;AAAA,MACpB,OAAO,KAAK;AAAA,MACZ,MAAM,KAAK;AAAA,MACX,UAAU,KAAK;AAAA,MACf,MAAM,KAAK;AAAA,IACb,CAAC;AAAA,EACP,SAAS,KAAK;AAGZ,UAAM,SACJ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IACA,OAAO,KAAK;AAAA,IACZ;AAAA,IACA,OAAO,KAAK;AAAA,IACZ,MAAM,KAAK;AAAA,IACX,UAAU,KAAK;AAAA,IACf,MAAM,KAAK;AAAA,IACX,YAAY;AAAA,IACZ,gBAAgB,KAAK;AAAA,EACvB,CAAC;AACH;AAEO,IAAM,iBAAiB,IAAI,QAAQ,SAAS,EAChD;AAAA,EACC;AAGF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC,OAAO,qBAAqB,kEAAkE,EAC9F,OAAO,eAAe,qDAAqD,EAC3E;AAAA,EACC;AAAA,EACA;AACF,EACC,OAAO,aAAa,kDAAkD,EACtE,OAAO,YAAY,wCAAwC,EAC3D;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC,OAAO,OAAO,SAAyB;AAEtC,MAAI,CAAC,KAAK,YAAY,KAAK,QAAQ;AACjC,UAAM,WAAW,CAAC,CAAC;AACnB;AAAA,EACF;AAEA,MAAI;AACJ,MAAI,KAAK,kBAAkB,QAAW;AACpC,QAAI,KAAK,kBAAkB,YAAY,KAAK,kBAAkB,OAAO;AACnE,cAAQ,OAAO,MAAM,uDAAuD;AAC5E,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,oBAAgB,KAAK;AAAA,EACvB;AAEA,QAAM,eAAe,KAAK,SAAS,KAAK;AACxC,QAAM,aAAa,YAAY,aAAa;AAK5C,QAAM,WAAW,cAAc;AAAA,IAC7B,OAAO,KAAK;AAAA,IACZ,KAAK,KAAK;AAAA,IACV;AAAA,IACA,OAAO,KAAK;AAAA,IACZ,MAAM,KAAK;AAAA,IACX,UAAU,KAAK;AAAA,IACf,MAAM,KAAK;AAAA,EACb,CAAC;AACH,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/commands/prepare.ts","../src/control-plane/hub-prepare.ts"],"sourcesContent":["/**\n * `agentbox prepare` — provider-neutral \"build the base image\" command.\n *\n * Three modes:\n *\n * - `agentbox prepare` → status only: show the inventory of\n * prepared base images / shared\n * volumes across all providers, plus\n * the project's pinned `box.image`.\n * - `agentbox prepare --provider X` → run prepare for X, then re-print\n * the relevant status section.\n * - `agentbox prepare --status` → status only (explicit; same as\n * no-args, but useful when scripted).\n *\n * Docker `prepare` builds `agentbox/box:dev` locally. Daytona `prepare`\n * builds a layered `Image` (Dockerfile.box + the three agent static tarballs)\n * and registers it via `daytona.snapshot.create({ name, image })`, then pins\n * `box.image: <name>` into the project config.\n *\n * Replaces the old `agentbox daytona publish-snapshot` (which used the\n * broken `_experimental_createSnapshot` API).\n */\n\nimport { intro, log, spinner } from '@clack/prompts';\nimport { loadEffectiveConfig, unsetConfigValue } from '@agentbox/config';\nimport {\n DEFAULT_BOX_IMAGE,\n SHARED_CLAUDE_VOLUME,\n SHARED_CODEX_VOLUME,\n SHARED_OPENCODE_VOLUME,\n imageInfo,\n volumeExists,\n type ImageInfo,\n} from '@agentbox/sandbox-docker';\nimport { Command } from 'commander';\nimport { UserFacingError } from '@agentbox/core';\nimport type { Provider } from '@agentbox/core';\nimport { getProvider, isKnownProvider } from '../provider/registry.js';\nimport { getRuntimeProviderNames } from '../provider/loaders.js';\nimport { parseProviderSpec } from '../provider/spec.js';\nimport { deadlineFetch, hostReachable } from '@agentbox/sandbox-cloud';\nimport { controlBoxKnowsHost } from '../control-plane/remote-docker-share.js';\nimport { bakeViaHub } from '../control-plane/hub-prepare.js';\nimport { dockerProviderRefusal } from '../control-plane/remote-hub.js';\nimport { HubApiClient } from '../control-plane/hub-api-client.js';\nimport {\n localExposedLoopbackUrl,\n resolveCustodyTarget,\n resolveHubApiClient,\n resolveHubApiTarget,\n} from './control-plane.js';\n\ninterface PrepareOptions {\n provider?: string;\n force?: boolean;\n yes?: boolean;\n status?: boolean;\n claudeInstall?: string;\n build?: boolean;\n name?: string;\n location?: string;\n size?: string;\n}\n\ninterface DockerStatus {\n daemon: 'reachable' | 'unreachable';\n image?: ImageInfo;\n volumes: Array<{ name: string; exists: boolean }>;\n}\n\nasync function dockerStatus(): Promise<DockerStatus> {\n let img: ImageInfo;\n try {\n img = await imageInfo(DEFAULT_BOX_IMAGE);\n } catch {\n return { daemon: 'unreachable', volumes: [] };\n }\n const names = [SHARED_CLAUDE_VOLUME, SHARED_CODEX_VOLUME, SHARED_OPENCODE_VOLUME];\n const volumes = await Promise.all(\n names.map(async (name) => ({ name, exists: await volumeExists(name).catch(() => false) })),\n );\n return { daemon: 'reachable', image: img, volumes };\n}\n\nfunction humanBytes(n?: number): string {\n if (n === undefined || !Number.isFinite(n)) return '—';\n if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`;\n if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`;\n if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`;\n return `${String(n)} B`;\n}\n\nfunction humanAge(iso?: string): string {\n if (!iso) return '—';\n const t = Date.parse(iso);\n if (!Number.isFinite(t)) return iso;\n const ageSec = Math.max(0, (Date.now() - t) / 1000);\n if (ageSec < 60) return `${ageSec.toFixed(0)}s ago`;\n if (ageSec < 3600) return `${(ageSec / 60).toFixed(0)}m ago`;\n if (ageSec < 86400) return `${(ageSec / 3600).toFixed(1)}h ago`;\n return `${(ageSec / 86400).toFixed(1)}d ago`;\n}\n\nfunction pad(s: string, width: number): string {\n return s.length >= width ? s : s + ' '.repeat(width - s.length);\n}\n\nasync function renderDocker(status: DockerStatus): Promise<string[]> {\n const out: string[] = ['docker:'];\n if (status.daemon === 'unreachable') {\n out.push(' docker daemon unreachable (is Docker running?)');\n return out;\n }\n if (!status.image?.exists) {\n out.push(\n ` image ${DEFAULT_BOX_IMAGE} (not built — run \\`agentbox prepare --provider docker\\`)`,\n );\n } else {\n out.push(\n ` image ${pad(DEFAULT_BOX_IMAGE, 30)} ${pad(humanBytes(status.image.sizeBytes), 10)} built ${humanAge(status.image.createdAt)}`,\n );\n }\n for (const v of status.volumes) {\n if (v.exists) {\n out.push(` vol ${pad(v.name, 30)} present`);\n } else {\n out.push(\n ` vol ${pad(v.name, 30)} (none — seeded lazily on first \\`agentbox claude/codex/opencode\\`)`,\n );\n }\n }\n return out;\n}\n\ninterface DaytonaStatusUnknown {\n configured: false;\n reason?: string;\n}\ninterface DaytonaStatusOk {\n configured: true;\n snapshots: Array<{\n name: string;\n state?: string;\n sizeGb?: number;\n createdAt?: string;\n errorReason?: string;\n }>;\n volumes: Array<{ name: string; state?: string; lastUsedAt?: string }>;\n reason?: string;\n}\ntype DaytonaStatusResult = DaytonaStatusUnknown | DaytonaStatusOk;\n\nasync function daytonaStatus(): Promise<DaytonaStatusResult> {\n try {\n const mod = await import('@agentbox/sandbox-daytona');\n return (await mod.getDaytonaStatus()) as DaytonaStatusResult;\n } catch (err) {\n return {\n configured: false,\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n}\n\ninterface E2bStatusUnknown {\n configured: false;\n reason?: string;\n}\ninterface E2bStatusOk {\n configured: true;\n templateId?: string;\n templateName?: string;\n createdAt?: string;\n cliVersion?: string;\n contextSha256?: string;\n}\ntype E2bStatusResult = E2bStatusUnknown | E2bStatusOk;\n\nasync function e2bStatus(): Promise<E2bStatusResult> {\n try {\n const mod = await import('@agentbox/sandbox-e2b');\n const cred = mod.readE2bCredStatus();\n if (cred.auth === 'none') {\n return { configured: false, reason: 'not configured — run `agentbox e2b login`' };\n }\n const prepared = mod.readPreparedState();\n if (!prepared.base) return { configured: true };\n return {\n configured: true,\n templateId: prepared.base.templateId,\n templateName: prepared.base.templateName,\n createdAt: prepared.base.createdAt,\n cliVersion: prepared.base.cliVersion,\n contextSha256: prepared.base.contextSha256,\n };\n } catch (err) {\n return {\n configured: false,\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n}\n\nfunction renderE2b(status: E2bStatusResult, pinnedImage?: string): string[] {\n const out: string[] = ['e2b:'];\n if (!status.configured) {\n out.push(` ${status.reason ?? '(not configured)'}`);\n return out;\n }\n if (!status.templateId) {\n out.push(' no agentbox template — run `agentbox prepare --provider e2b`');\n return out;\n }\n const pinned = pinnedImage && pinnedImage === status.templateId ? ' (pinned in project)' : '';\n out.push(\n ` tmpl ${pad(status.templateName ?? status.templateId, 40)} ${pad(status.cliVersion ?? '—', 10)} ${humanAge(status.createdAt)}${pinned}`,\n );\n return out;\n}\n\nfunction renderDaytona(status: DaytonaStatusResult, pinnedImage?: string): string[] {\n const out: string[] = ['daytona:'];\n if (!status.configured) {\n out.push(\n ` (not configured — \\`agentbox daytona login\\` to set up${status.reason ? `; ${status.reason}` : ''})`,\n );\n return out;\n }\n if (status.reason) out.push(` warn: ${status.reason}`);\n if (status.snapshots.length === 0) {\n out.push(' no agentbox snapshots — run `agentbox prepare --provider daytona`');\n } else {\n for (const s of status.snapshots) {\n const sizeStr = s.sizeGb !== undefined ? `${s.sizeGb.toFixed(2)} GB` : '—';\n const pinned = pinnedImage && pinnedImage === s.name ? ' (pinned in project)' : '';\n const tail =\n s.state === 'error' && s.errorReason\n ? ` error: ${s.errorReason.slice(0, 80)}`\n : ` ${humanAge(s.createdAt)}`;\n out.push(\n ` snap ${pad(s.name, 40)} ${pad(s.state ?? '—', 10)} ${pad(sizeStr, 10)}${tail}${pinned}`,\n );\n }\n }\n if (status.volumes.length === 0) {\n out.push(' no agentbox volumes — created lazily on first cloud `agentbox create`');\n } else {\n for (const v of status.volumes) {\n const last = v.lastUsedAt ? ` last used ${humanAge(v.lastUsedAt)}` : '';\n out.push(` vol ${pad(v.name, 40)} ${pad(v.state ?? '—', 10)}${last}`);\n }\n }\n return out;\n}\n\n/**\n * Bound on the control-box status read. `?freshness=1` makes the hub hash its\n * own build context, so it is not instant — but this is an interactive status\n * command, and an unreachable box must cost a fixed, small amount of time.\n */\nconst CONTROL_BOX_STATUS_MS = 5000;\n\n/**\n * The control box's own provider inventory, or nothing when none is configured\n * (or it can't be reached — a status command must never hang or fail on it).\n *\n * Only shown for a GENUINELY remote control box: a co-located hub (a local hub,\n * or `hub expose` on this machine) bakes on this same machine, so the local\n * provider rows already describe it and a second \"control box\" section would just\n * mislabel it. Exported so `agentbox doctor` shows the same section.\n */\nexport async function renderControlBoxProviders(): Promise<string[]> {\n if (await hubIsCoLocated().catch(() => true)) return [];\n const target = await resolveHubApiTarget(undefined, { quiet: true }).catch(() => null);\n if (!target) return [];\n // Probe with a socket we own before spending the budget: a fetch to an\n // unreachable host can't be cancelled, and this is a status command.\n if (!(await hostReachable(target.url, CONTROL_BOX_STATUS_MS))) {\n return ['', 'control box: unreachable — could not read its baked providers'];\n }\n const client = new HubApiClient({\n ...target,\n fetchImpl: deadlineFetch(AbortSignal.timeout(CONTROL_BOX_STATUS_MS)),\n });\n const providers = await client.listProviders({ freshness: true }).catch(() => null);\n if (!providers) return ['', 'control box: unreachable — could not read its baked providers'];\n const cloud = providers.filter((p) => p.id !== 'docker' && p.id !== 'remote-docker');\n if (cloud.length === 0) return [];\n const out = ['', 'control box (where cloud boxes are built):'];\n for (const p of cloud) {\n const state = !p.hasCredentials\n ? 'no credentials'\n : !p.configured\n ? 'not baked'\n : (p.baseStatus ?? 'baked');\n out.push(` ${pad(p.id, 16)} ${state}`);\n }\n return out;\n}\n\nasync function showStatus(opts: { onlyProvider?: string }): Promise<void> {\n const cfg = await loadEffectiveConfig(process.cwd()).catch(() => null);\n const pinnedRaw = cfg?.effective.box.image;\n // Only treat as \"user-pinned\" if it differs from the docker default tag\n // — that one is just the fallback ref the docker provider builds locally.\n const pinned =\n typeof pinnedRaw === 'string' && pinnedRaw.length > 0 && pinnedRaw !== DEFAULT_BOX_IMAGE\n ? pinnedRaw\n : undefined;\n const lines: string[] = [];\n\n const wantDocker = !opts.onlyProvider || opts.onlyProvider === 'docker';\n const wantDaytona = !opts.onlyProvider || opts.onlyProvider === 'daytona';\n const wantE2b = !opts.onlyProvider || opts.onlyProvider === 'e2b';\n\n if (wantDocker) {\n const status = await dockerStatus();\n lines.push(...(await renderDocker(status)));\n }\n if (wantDaytona) {\n if (lines.length > 0) lines.push('');\n const status = await daytonaStatus();\n lines.push(...renderDaytona(status, pinned));\n }\n if (wantE2b) {\n if (lines.length > 0) lines.push('');\n const status = await e2bStatus();\n // Use the per-provider pin (box.imageE2b) so the marker tracks the right key.\n const e2bPinned =\n typeof cfg?.effective.box.imageE2b === 'string' && cfg.effective.box.imageE2b.length > 0\n ? cfg.effective.box.imageE2b\n : undefined;\n lines.push(...renderE2b(status, e2bPinned));\n }\n if (pinned) {\n lines.push('');\n lines.push(`project pin: box.image = ${pinned}`);\n }\n // With a control box configured, ITS bakes are the ones a cloud create boots —\n // so an inventory that only ever showed this machine's was describing the\n // wrong host. Appended, never substituted: the local rows still matter for\n // docker (always built on this machine) and for the co-located-hub case.\n if (!opts.onlyProvider) lines.push(...(await renderControlBoxProviders()));\n process.stdout.write(lines.join('\\n') + '\\n');\n}\n\nexport interface RunPrepareOptions {\n /** Rebuild even if the image / snapshot already exists. */\n force?: boolean;\n /** Skip the Daytona cost-notice. */\n yes?: boolean;\n /** Host workspace dir (defaults to `process.cwd()`). */\n cwd?: string;\n /** Suppress the post-prepare status block. */\n suppressStatus?: boolean;\n /**\n * How the bake installs Claude Code (`native` | `npm`). CLI override of the\n * `box.claudeInstall` config key; falls back to the effective config.\n */\n claudeInstall?: 'native' | 'npm';\n /**\n * Bake INPUTS (not routing) threaded to the hub bake. Each is a per-invocation\n * override; when absent the hub worker fills it from its effective config.\n * - `build`: force a local docker build instead of pulling the registry base.\n * - `size`: bake-time VM size (daytona `cpu-mem-disk`, e2b `cpu-mem`).\n * - `location`: bake datacenter / region (hetzner / digitalocean / daytona).\n * - `name`: snapshot name (daytona).\n */\n build?: boolean;\n size?: string;\n location?: string;\n name?: string;\n}\n\n/**\n * Whether the hub the bake will run on is THIS machine (a local hub, or a control\n * box exposed on loopback via `hub expose`). Decides whether the prepared-state\n * the worker writes is already here (co-located → nothing to adopt) or on a remote\n * control box's disk (adopt the record back from custody).\n */\nasync function hubIsCoLocated(): Promise<boolean> {\n // Lazy import mirrors resolveHubApiTarget's cycle-avoidance (hub.ts <->\n // control-plane.ts). `hub expose` on this machine reports mode 'remote' but is\n // still co-located, so the loopback check is the second half of the answer.\n const { resolveHubTarget } = await import('./hub.js');\n const target = await resolveHubTarget(undefined).catch(() => null);\n if (target?.mode === 'local') return true;\n return (await localExposedLoopbackUrl().catch(() => null)) !== null;\n}\n\n/**\n * Pure decision: does a bake target the LOCAL hub (`local: true`) or the remote\n * control box (`false`)? This is target selection only — the bake always runs\n * through the same `POST /api/v1/providers/:id/prepare` (or `/hosts/:alias/bake`)\n * route; there is NO inline `provider.prepare` path, which is exactly the second\n * implementation this consolidation exists to delete. The choice is only ever\n * WHICH base URL the one client points at.\n *\n * Extracted pure (IO done by {@link shouldPreferLocalHub}) so the routing is\n * unit-testable — the deleted `resolvePrepareRouting` had this same shape, and\n * dropping it is what regressed the `cloud.viaHub` and remote-docker fallbacks.\n *\n * Local wins when:\n * - the hub is already co-located (no control box, or `hub expose` here);\n * - `cloud.viaHub=false` — the user keeps builds on their own machine even with\n * a control plane configured (the config KEY survives; only the `--local` /\n * `--via-hub` flags were dropped);\n * - `docker`, whose base is an image on THIS machine — baking it on the control\n * box would produce an image on the wrong host;\n * - `remote-docker` whose host alias the control box doesn't know, but the local\n * hub (this machine's `~/.ssh`) does.\n * Otherwise the control box is the target (the default for cloud bakes).\n */\nexport function resolvePrepareTargetKind(input: {\n /** The default hub is already on this machine (local, or `hub expose` here). */\n coLocated: boolean;\n /** `relay.controlPlaneUrl` — a genuine remote control box is configured. */\n controlPlaneUrl: string | undefined;\n /** `cloud.viaHub` — build cloud boxes / bases on the control box by default. */\n viaHub: boolean;\n providerName: string;\n remoteHost?: string;\n /** remote-docker only: whether the control box has the host alias registered. */\n controlBoxKnowsHost?: boolean;\n}): { local: boolean; reason?: string } {\n if (input.coLocated) return { local: true };\n if (!input.controlPlaneUrl) return { local: true };\n if (!input.viaHub) return { local: true, reason: 'cloud.viaHub is off — baking on this machine' };\n if (input.providerName === 'docker') return { local: true };\n if (input.providerName === 'remote-docker' && input.remoteHost && !input.controlBoxKnowsHost) {\n return {\n local: true,\n reason: `the control box has no \\`${input.remoteHost}\\` host registered — baking on this machine's hub`,\n };\n }\n return { local: false };\n}\n\n/**\n * IO wrapper around {@link resolvePrepareTargetKind}: resolves co-location, the\n * effective config, and — only for a remote-docker host that could actually\n * target the control box — the alias check.\n */\nasync function shouldPreferLocalHub(\n providerName: string,\n remoteHost: string | undefined,\n): Promise<{ local: boolean; reason?: string }> {\n const coLocated = await hubIsCoLocated();\n const cfg = await loadEffectiveConfig(process.cwd()).catch(() => null);\n const eff = cfg?.effective;\n const controlPlaneUrl = eff?.relay.controlPlaneUrl;\n const viaHub = eff?.cloud.viaHub ?? true;\n // The alias check is the only networked input, and only remote-docker needs it.\n // Skip it whenever an earlier rule already forces local (no control box,\n // co-located, or cloud.viaHub off) so a normal bake makes no extra round-trip.\n const knowsHost =\n providerName === 'remote-docker' && remoteHost && controlPlaneUrl && viaHub && !coLocated && eff\n ? await controlBoxKnowsHost(remoteHost, eff)\n : undefined;\n return resolvePrepareTargetKind({\n coLocated,\n controlPlaneUrl,\n viaHub,\n providerName,\n remoteHost,\n controlBoxKnowsHost: knowsHost,\n });\n}\n\n/**\n * Bake `providerName` THROUGH the hub — the one prepare path (local hub or remote\n * control box). Throws on failure so internal callers (`install`, the create\n * wizard's stale-base rebuild) can catch it; the top-level command surfaces it.\n * The failure path deliberately does NOT fall back to a local bake: a hub bake\n * that failed for a real reason (no credentials there, a broken build context)\n * would fail the same way here.\n */\nasync function runPrepareViaHub(args: {\n providerName: string;\n provider: Provider;\n force?: boolean;\n claudeInstall: 'native' | 'npm';\n build?: boolean;\n size?: string;\n location?: string;\n name?: string;\n remoteHost?: string;\n suppressStatus?: boolean;\n}): Promise<void> {\n // WHICH hub: the local hub on this machine, or the remote control box. Same\n // route either way — target selection, never an inline bake.\n const target = await shouldPreferLocalHub(args.providerName, args.remoteHost);\n if (target.reason) log.info(target.reason);\n // Auto-starts a local hub when that is the target (Step 0). A remote control\n // box with no API key returns null after printing why.\n const client = await resolveHubApiClient(undefined, { preferLocal: target.local });\n // resolveHubApiClient already printed why (no API key, hub wouldn't start).\n if (!client) throw new UserFacingError('could not reach a hub to run the bake');\n // The local hub's worker writes the prepared-state straight to this machine, so\n // choosing local IS the co-located signal — no custody round-trip to adopt.\n const coLocated = target.local;\n // Custody is only the remote-adopt channel; a co-located hub wrote the record\n // straight to this machine, so skip resolving it (and its error path) there.\n const custody = coLocated ? null : await resolveCustodyTarget(undefined, { quiet: true });\n const where = coLocated ? 'hub' : 'control box';\n const what = args.remoteHost ? `${args.providerName} host ${args.remoteHost}` : args.providerName;\n const sp = spinner();\n sp.start(`preparing ${what} on the ${where}…`);\n const outcome = await bakeViaHub({\n client,\n providerName: args.providerName,\n provider: args.provider,\n force: args.force,\n claudeInstall: args.claudeInstall,\n build: args.build,\n size: args.size,\n location: args.location,\n name: args.name,\n custody,\n coLocated,\n remoteHost: args.remoteHost,\n onLog: (line) => sp.message(line.slice(0, 80)),\n });\n if (outcome.status === 'failed') {\n sp.stop(`prepare failed on the ${where}: ${outcome.detail}`);\n throw new Error(outcome.detail);\n }\n sp.stop(`prepared ${what} on the ${where}`);\n if (outcome.status === 'baked-not-adopted') {\n // The hub can now create with it; this machine just can't verify it locally.\n log.warn(`${outcome.detail} — cloud creates route to the control box, so this is not fatal`);\n } else if (coLocated) {\n log.success(`prepared ${args.providerName}`);\n } else {\n log.success(\n args.remoteHost\n ? `baked ${args.remoteHost} from the control box — the image is on that host, so this machine sees it too`\n : `adopted the control box's ${args.providerName} base — this machine is current too`,\n );\n }\n // One-shot migration of a stale generic `box.image`. Pre-fix builds wrote every\n // cloud prepare's snapshot id into the shared key, so any non-default value\n // still there poisons every provider that doesn't recognize it. Best-effort —\n // never fail the command on it.\n try {\n const projectCfg = await loadEffectiveConfig(process.cwd()).catch(() => null);\n const projectImage = projectCfg?.layers.project.values.box?.image;\n if (\n typeof projectImage === 'string' &&\n projectImage.length > 0 &&\n projectImage !== DEFAULT_BOX_IMAGE\n ) {\n const cleared = await unsetConfigValue('project', 'box.image', process.cwd());\n if (cleared.existed) {\n log.warn(\n `migrated stale \\`box.image\\` from a previous prepare (was \\`${projectImage}\\`); ` +\n `re-set manually if you actually meant it: \\`agentbox config set --project box.image <ref>\\``,\n );\n }\n }\n } catch (err) {\n log.warn(\n `could not migrate stale box.image (continuing): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (!args.suppressStatus) {\n process.stdout.write('\\n');\n await showStatus({ onlyProvider: args.providerName });\n }\n}\n\n/**\n * Prepare `providerName`'s base — the single entry point the `prepare` command,\n * the install wizard, and the create-time stale-base rebuild all share. The bake\n * ALWAYS runs on the hub (Step 1 of the `/api/v1` consolidation): a local hub is\n * co-located so the artifact lands here, a remote control box is where cloud boxes\n * are built and the record is adopted back. Caller owns any `intro(...)` framing;\n * this manages its own spinner.\n */\nexport async function runPrepare(\n providerSpec: string,\n opts: RunPrepareOptions = {},\n): Promise<void> {\n // Throw, never exit: `runPrepare` is called from the install wizard, the\n // create-time stale-base rebuild and `remote-docker add` — a bare exit would\n // kill those mid-flow instead of letting them report. The `prepare` command\n // itself is unchanged: printCliError renders a UserFacingError's message bare\n // and exits 1, exactly what these did.\n if (!isKnownProvider(providerSpec)) {\n throw new UserFacingError(\n `error: --provider must be one of: ${getRuntimeProviderNames().join(', ')}`,\n );\n }\n // `--provider docker:<host>` bakes the image on that machine's engine. Split\n // the spec: the bare name drives every provider lookup, the host is baked via\n // the hub's per-host endpoint.\n const { name: providerName, remoteHost } = parseProviderSpec(providerSpec);\n\n if (providerName === 'daytona' && !opts.yes && process.stdin.isTTY) {\n process.stdout.write(\n 'This will trigger a Daytona image build (~7 min cold, ~seconds with cache) and ' +\n 'register a named snapshot in your org.\\n' +\n 'Re-run with --yes to skip this notice.\\n',\n );\n }\n\n const provider = await getProvider(providerName);\n if (typeof provider.prepare !== 'function') {\n throw new UserFacingError(`provider '${providerName}' does not implement prepare`);\n }\n\n const cwd = opts.cwd ?? process.cwd();\n const cfg = await loadEffectiveConfig(cwd).catch(() => null);\n // Docker off under a remote hub (Step 12): don't bake a local docker/remote-docker\n // image when a control box owns the fleet. `local` mode (or no cfg) keeps it on.\n if (cfg) {\n const refusal = await dockerProviderRefusal(cfg.effective, providerName, remoteHost, 'prepare');\n if (refusal) throw new UserFacingError(refusal);\n }\n // Bake-time Claude install method: CLI flag wins over the config key. The\n // remaining bake INPUTS (`build` / `size` / `location` / `name`) are passed\n // through only when the user set the corresponding flag; the hub worker fills\n // any that are absent from ITS effective config (size/region/sandbox class),\n // so one route body serves every bake shape (plan Step 1).\n const claudeInstall = opts.claudeInstall ?? cfg?.effective.box.claudeInstall ?? 'native';\n // remote-docker: the `docker:<host>` spec first, else the configured default.\n const host =\n providerName === 'remote-docker'\n ? remoteHost || cfg?.effective.box.remoteDockerHost || undefined\n : undefined;\n\n await runPrepareViaHub({\n providerName,\n provider,\n force: opts.force,\n claudeInstall,\n build: opts.build,\n size: opts.size,\n location: opts.location,\n name: opts.name,\n remoteHost: host,\n suppressStatus: opts.suppressStatus,\n });\n}\n\nexport const prepareCommand = new Command('prepare')\n .description(\n 'Build base sandbox images / snapshots, or show what is already prepared across providers. ' +\n 'The bake always runs on the hub — a local hub is this machine; with a control box configured, ' +\n 'it runs there (where cloud boxes are built) and the record is adopted back.',\n )\n .option(\n '-p, --provider <name>',\n 'provider to prepare (docker | daytona | hetzner | vercel | e2b | digitalocean). Omit for status-only.',\n )\n .option('-n, --name <name>', 'snapshot name (Daytona only; default: agentbox-base-<timestamp>)')\n .option('-f, --force', 'rebuild even if the image / snapshot already exists')\n .option(\n '--build',\n 'docker: build the base image locally instead of pulling the prebuilt one from the registry',\n )\n .option('-y, --yes', 'skip confirmation prompts (cost / time warnings)')\n .option('--status', 'show status without preparing anything')\n .option(\n '--claude-install <mode>',\n 'install Claude Code into the base image via the native installer (default) or npm (native | npm)',\n )\n .option(\n '--location <name>',\n 'Datacenter/region the bake VPS runs in. Hetzner: nbg1, fsn1, hel1, ash (overrides box.hetznerLocation). DigitalOcean: nyc3, sfo3, ams3, fra1 (overrides box.digitaloceanRegion). Hetzner/DigitalOcean-only.',\n )\n .option(\n '--size <spec>',\n 'bake-time VM size. daytona: cpu-memory-disk GB (e.g. 4-8-20). e2b: cpu-memory GB (e.g. 4-8). Overrides box.size / box.size<Provider>. Ignored by docker/hetzner/vercel.',\n )\n .action(async (opts: PrepareOptions) => {\n // Status-only path: no provider, or explicit --status.\n if (!opts.provider || opts.status) {\n await showStatus({});\n return;\n }\n\n let claudeInstall: 'native' | 'npm' | undefined;\n if (opts.claudeInstall !== undefined) {\n if (opts.claudeInstall !== 'native' && opts.claudeInstall !== 'npm') {\n process.stderr.write('error: --claude-install must be one of: native, npm\\n');\n process.exit(1);\n }\n claudeInstall = opts.claudeInstall;\n }\n\n const providerName = opts.provider.trim();\n intro(`preparing ${providerName} base image`);\n // Errors propagate to `program.parseAsync().catch` so they reach the user\n // via `console.error` — a bare `catch { process.exit(1) }` here would\n // silently swallow getProvider() failures (e.g. an ensureCredentials cancel)\n // that fall outside runPrepare's inner spinner error handler.\n await runPrepare(providerName, {\n force: opts.force,\n yes: opts.yes,\n claudeInstall,\n build: opts.build,\n size: opts.size,\n location: opts.location,\n name: opts.name,\n });\n });\n","/**\n * Bake a provider's base THROUGH the hub, from this machine — the one prepare\n * path, local hub or remote control box alike (`docs/hub-api-single-path-plan.md`\n * Step 1). The hub runs the bake in its own queue worker; this drives it and\n * reports the verdict.\n *\n * Two shapes, decided by whether the hub is co-located with this CLI:\n * - **Co-located** (a local hub, or `hub expose` on this machine): the worker\n * writes the prepared-state to THIS machine's `~/.agentbox` directly, so\n * there is nothing to adopt — a `done` job is the whole story.\n * - **Remote control box**: the worker wrote the record to ITS disk + custody;\n * we pull it back so both machines end up current from one bake. (With\n * `cloud.viaHub`, a cloud box is also built there, so baking there is where\n * the snapshot needs to live anyway.)\n *\n * The hub already exposes everything this needs (`POST /api/v1/providers/:id/prepare`,\n * `GET /api/v1/jobs/:id`, `GET /api/v1/jobs/:id/logs`); nothing new on that side.\n */\nimport { pullPreparedFromCustody } from '@agentbox/sandbox-cloud';\nimport type { Provider } from '@agentbox/core';\nimport { HubApiError, type HubApiClient } from './hub-api-client.js';\nimport { pinAdoptedBase } from './prepared-custody.js';\n\n/** How often the job's terminal status is re-checked while the log streams. */\nconst JOB_POLL_MS = 3000;\n/**\n * Cap on a single bake. Generous: a cold daytona/e2b image build is genuinely\n * ~10 minutes, and a bake that outlives this is still running on the hub — the\n * user is told where to watch it rather than left with a hung terminal.\n */\nconst BAKE_TIMEOUT_MS = 45 * 60_000;\n\nexport type HubBakeOutcome =\n /**\n * The hub baked it and the result is current on THIS machine — either a\n * co-located hub wrote the prepared-state here directly, or we adopted a remote\n * control box's record. Nothing left to do.\n */\n | { status: 'adopted' }\n /** The hub baked it, but its record didn't reach our prepared-state. */\n | { status: 'baked-not-adopted'; detail: string }\n | { status: 'failed'; detail: string };\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Run a bake on the control box and adopt the resulting record.\n *\n * The log stream is advisory — a dropped connection must never read as a\n * successful bake — so the verdict always comes from polling the job itself.\n */\nexport async function bakeViaHub(args: {\n client: HubApiClient;\n providerName: string;\n provider: Provider;\n force?: boolean;\n claudeInstall: 'native' | 'npm';\n /**\n * Bake INPUTS threaded from the CLI's flags (`--build` / `--size` / `--location`\n * / `--name`). They ride the same route body; the hub worker fills any that are\n * absent from its own effective config. Not routing — see the plan's Step 1.\n */\n build?: boolean;\n size?: string;\n location?: string;\n name?: string;\n custody: { url: string; adminToken: string } | null;\n /**\n * Whether the hub runs on THIS machine (a local hub, or `hub expose`). When\n * true, the worker's prepared-state write already lands in this machine's\n * `~/.agentbox`, so there is no custody round-trip to adopt.\n */\n coLocated: boolean;\n /**\n * remote-docker only: the host alias to bake. It goes to a different endpoint\n * (`/hosts/:alias/bake`), because the unit of a remote-docker base is a host,\n * not the provider — there is no single `remote-docker` base to prepare.\n */\n remoteHost?: string;\n onLog: (line: string) => void;\n}): Promise<HubBakeOutcome> {\n let jobId: string;\n try {\n jobId = args.remoteHost\n ? await args.client.bakeHost(args.remoteHost)\n : await args.client.prepareProvider(args.providerName, {\n force: args.force,\n claudeInstall: args.claudeInstall,\n build: args.build,\n size: args.size,\n location: args.location,\n name: args.name,\n });\n } catch (err) {\n // A precheck failure on the hub (no credentials there, docker down) is a\n // 409 with a real message — surface it verbatim rather than as \"failed\".\n const detail =\n err instanceof HubApiError ? err.message : err instanceof Error ? err.message : String(err);\n return { status: 'failed', detail };\n }\n\n const abort = new AbortController();\n // Fire-and-forget: the stream ends when the hub closes it. Errors are ignored\n // on purpose — losing the log must not lose the bake.\n const streaming = args.client\n .streamJobLog(jobId, args.onLog, abort.signal)\n .catch(() => undefined);\n\n const deadline = Date.now() + BAKE_TIMEOUT_MS;\n let status = 'queued';\n // The failed job's own reason. Without it the caller only ever learned that a\n // job \"ended failed\" and had to go read the hub's log to find out why — so\n // every bake failure, however precisely diagnosed on the hub side, reached the\n // user as an opaque line plus a stack trace. `create` already surfaces this\n // field; `prepare` was throwing it away.\n let jobError: string | undefined;\n try {\n for (;;) {\n await delay(JOB_POLL_MS);\n const job = await args.client.getJob(jobId).catch(() => null);\n // A job that vanished (hub restarted mid-bake) is not a success.\n if (!job) {\n status = 'gone';\n break;\n }\n status = job.status;\n jobError = job.error;\n if (status === 'done' || status === 'failed' || status === 'cancelled') break;\n if (Date.now() > deadline) {\n return {\n status: 'failed',\n detail: `the bake is still running on the control box after ${String(Math.round(BAKE_TIMEOUT_MS / 60_000))} minutes — watch job ${jobId} there`,\n };\n }\n }\n } finally {\n abort.abort();\n await streaming;\n }\n\n if (status !== 'done') {\n const reason = jobError?.trim();\n return {\n status: 'failed',\n detail: reason\n ? `${reason}\\n (control box bake job ${jobId} ended ${status})`\n : `the control box's bake job ${jobId} ended ${status}`,\n };\n }\n\n // A remote-docker bake put the image on the REMOTE HOST, which this machine\n // reaches too, and \"is that host baked?\" is answered by asking its engine —\n // never by a local file. So there is nothing to adopt, and nothing to pin.\n // (The local `remote-docker-prepared.json` history stays silent about a bake\n // this machine didn't run; that file is explicitly a log for `prepare\n // --status` / `doctor`, not the readiness check.)\n if (args.remoteHost) return { status: 'adopted' };\n\n // Co-located hub (local, or `hub expose`): the worker wrote the prepared-state\n // straight into this machine's `~/.agentbox` and pinned the config, so a `done`\n // job means the base is already current here. No custody round-trip.\n if (args.coLocated) return { status: 'adopted' };\n\n // The hub's bake wrote its record into custody (`sharePreparedBase` →\n // `writePreparedToCustodyStore`), so adopting is a plain custody read.\n if (!args.custody) {\n return {\n status: 'baked-not-adopted',\n detail: 'no control-box admin token, so its bake record could not be read back',\n };\n }\n const fingerprint = await Promise.resolve(args.provider.baseFingerprint?.('native')).catch(\n () => undefined,\n );\n const res = await pullPreparedFromCustody(args.providerName, fingerprint, {\n controlPlaneUrl: args.custody.url,\n adminToken: args.custody.adminToken,\n log: args.onLog,\n }).catch(() => ({ adopted: false, record: undefined }));\n if (!res.adopted) {\n return {\n status: 'baked-not-adopted',\n detail: `the control box baked ${args.providerName}, but its record does not match this machine's build context`,\n };\n }\n // Same pin a local bake writes: some providers (daytona) resolve their base\n // from `box.image<Provider>`, not from prepared-state.\n await pinAdoptedBase(args.providerName, res.record, args.onLog);\n return { status: 'adopted' };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAS,OAAO,KAAK,eAAe;AAWpC,SAAS,eAAe;;;ACVxB,IAAM,cAAc;AAMpB,IAAM,kBAAkB,KAAK;AAa7B,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAQA,eAAsB,WAAW,MA6BL;AAC1B,MAAI;AACJ,MAAI;AACF,YAAQ,KAAK,aACT,MAAM,K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AAA,EACvB;AAEA,QAAM,eAAe,KAAK,SAAS,KAAK;AACxC,QAAM,aAAa,YAAY,aAAa;AAK5C,QAAM,WAAW,cAAc;AAAA,IAC7B,OAAO,KAAK;AAAA,IACZ,KAAK,KAAK;AAAA,IACV;AAAA,IACA,OAAO,KAAK;AAAA,IACZ,MAAM,KAAK;AAAA,IACX,UAAU,KAAK;AAAA,IACf,MAAM,KAAK;AAAA,EACb,CAAC;AACH,CAAC;","names":[]}
@@ -14,7 +14,7 @@ import {
14
14
  resolveHubApiTarget,
15
15
  restoreTunnelIfExposed,
16
16
  stopTunnelIfExposed
17
- } from "./chunk-QDU7YDME.js";
17
+ } from "./chunk-SXXN7JOC.js";
18
18
  import {
19
19
  CustodyClient
20
20
  } from "./chunk-PAWAGULH.js";
@@ -633,4 +633,4 @@ export {
633
633
  describeRemoteHubBuild,
634
634
  hubCommand
635
635
  };
636
- //# sourceMappingURL=chunk-UEEW5TW7.js.map
636
+ //# sourceMappingURL=chunk-F77AZT2M.js.map
@@ -39,7 +39,7 @@ async function dockerProviderRefusal(effective, providerName, remoteHost, contex
39
39
  if (!dockerProvidersHidden(effective)) return null;
40
40
  if (await controlBoxIsThisMachine()) return null;
41
41
  if (providerName === "remote-docker") {
42
- const { hubCanRunEngine } = await import("./remote-docker-share-QDCBM5UM.js");
42
+ const { hubCanRunEngine } = await import("./remote-docker-share-XBV76ZAZ.js");
43
43
  if (await hubCanRunEngine(providerName, remoteHost, effective)) return null;
44
44
  }
45
45
  return dockerHiddenMessage(effective, context, remoteHost);
@@ -54,4 +54,4 @@ export {
54
54
  controlBoxIsThisMachine,
55
55
  dockerProviderRefusal
56
56
  };
57
- //# sourceMappingURL=chunk-UTOC2NHC.js.map
57
+ //# sourceMappingURL=chunk-FCMBVJFQ.js.map
@@ -4,10 +4,10 @@ import {
4
4
  } from "./chunk-F4PPZ4SI.js";
5
5
  import {
6
6
  boxOwningHubIsLocal
7
- } from "./chunk-53OTEDBS.js";
7
+ } from "./chunk-ZCHWZYIN.js";
8
8
  import {
9
9
  providerForBox
10
- } from "./chunk-2JHPGPLE.js";
10
+ } from "./chunk-5I7IFACI.js";
11
11
  import {
12
12
  HubApiClient
13
13
  } from "./chunk-WHFCJBMO.js";
@@ -15,7 +15,7 @@ import {
15
15
  buildCloudAttachInnerCommand,
16
16
  startDetachedCloudAgent,
17
17
  startDetachedSession
18
- } from "./chunk-4KYP775X.js";
18
+ } from "./chunk-JLVUNDUB.js";
19
19
  import {
20
20
  readBoxStatus,
21
21
  startClaudeSession,
@@ -2669,7 +2669,7 @@ async function resolveBoxHubTarget(box) {
2669
2669
  async function resolveBoxPromptSource(box, opts = {}) {
2670
2670
  const target = await resolveBoxHubTarget(box).catch(() => "none");
2671
2671
  if (target === "none" || target === "no-token") {
2672
- const { resolveHubApiTarget } = await import("./control-plane-YQFX2ILX.js");
2672
+ const { resolveHubApiTarget } = await import("./control-plane-TOFT56CT.js");
2673
2673
  const local = await resolveHubApiTarget(void 0, { preferLocal: true, quiet: opts.quiet });
2674
2674
  if (!local) return null;
2675
2675
  return {
@@ -2876,4 +2876,4 @@ export {
2876
2876
  agentResumeArgs,
2877
2877
  restoreAgentSessions
2878
2878
  };
2879
- //# sourceMappingURL=chunk-73D2HKA3.js.map
2879
+ //# sourceMappingURL=chunk-HLBK5ZR6.js.map
@@ -432,6 +432,9 @@ var AGENT_SPECS = [
432
432
  stageCredentials: () => stageOpencodeCredentialsForUpload()
433
433
  }
434
434
  ];
435
+ function cloudVolumesUsable(sandboxClass) {
436
+ return sandboxClass !== "linux-vm";
437
+ }
435
438
  async function ensureAgentVolumesForCloud(backend, opts = {}) {
436
439
  const log = opts.onLog ?? (() => {
437
440
  });
@@ -513,7 +516,7 @@ async function refreshAgentCredentialsBackup(opts = {}) {
513
516
  async function seedCredentialsOne(backend, handle, spec, opts) {
514
517
  const log = opts.onLog ?? (() => {
515
518
  });
516
- const hasVolume = typeof backend.ensureVolume === "function";
519
+ const hasVolume = typeof backend.ensureVolume === "function" && cloudVolumesUsable(handle.sandboxClass);
517
520
  if (hasVolume && !opts.force) {
518
521
  const probe = await backend.exec(handle, `test -f ${spec.credentialsMountPath}/${SEED_MARKER}`);
519
522
  if (probe.exitCode === 0) {
@@ -668,7 +671,10 @@ async function seedDynamicConfig(backend, handle, opts) {
668
671
  try {
669
672
  let boxManifest = null;
670
673
  try {
671
- const res = await backend.exec(handle, `cat ${BOX_DYNAMIC_SYNC_MANIFEST} 2>/dev/null || true`);
674
+ const res = await backend.exec(
675
+ handle,
676
+ `cat ${BOX_DYNAMIC_SYNC_MANIFEST} 2>/dev/null || true`
677
+ );
672
678
  const out = res.stdout.trim();
673
679
  if (res.exitCode === 0 && out.length > 0) {
674
680
  boxManifest = JSON.parse(out);
@@ -697,7 +703,10 @@ async function seedDynamicConfig(backend, handle, opts) {
697
703
  steps.push(
698
704
  `rm -rf ${BOX_STAGE}`,
699
705
  `mkdir -p ${BOX_STAGE}`,
700
- `tar -xzf ${REMOTE_TAR} -C ${BOX_STAGE}`,
706
+ // See claude-json-overlay: the host tarball carries the host's uid/gid,
707
+ // which a root extract would restore verbatim and `cp -a` below would
708
+ // then propagate into the box user's home.
709
+ `tar -xzf ${REMOTE_TAR} -C ${BOX_STAGE} --no-same-permissions --no-same-owner -m`,
701
710
  `if [ -d ${BOX_STAGE}/workflows ]; then cp -a ${BOX_STAGE}/workflows/. ${BOX_WORKFLOWS_DIR}/; fi`,
702
711
  `if [ -d ${BOX_STAGE}/memory ]; then cp -a ${BOX_STAGE}/memory/. ${BOX_MEMORY_DIR}/; fi`,
703
712
  `rm -rf ${BOX_STAGE} ${REMOTE_TAR}`
@@ -764,7 +773,13 @@ async function seedClaudeJsonAtCreate(backend, handle, opts = {}) {
764
773
  await backend.uploadFile(handle, staged.tarballPath, REMOTE_TAR2);
765
774
  const extract = await backend.exec(
766
775
  handle,
767
- `set -e; mkdir -p ${BOX_CLAUDE_DIR}; tar -xzf ${REMOTE_TAR2} -C ${BOX_CLAUDE_DIR}; rm -f ${REMOTE_TAR2}`
776
+ // `--no-same-owner --no-same-permissions -m`: the host tarball records the
777
+ // HOST's uid/gid and mode, and GNU tar restores both when it runs as root.
778
+ // That is how `/home/vscode/.claude` ended up owned by uid 501 (a macOS
779
+ // uid that means nothing in the box) mode 0700 — unreadable by the agent.
780
+ // Harmless when the extract already runs unprivileged; load-bearing when
781
+ // it doesn't.
782
+ `set -e; mkdir -p ${BOX_CLAUDE_DIR}; tar -xzf ${REMOTE_TAR2} -C ${BOX_CLAUDE_DIR} --no-same-permissions --no-same-owner -m; rm -f ${REMOTE_TAR2}`
768
783
  );
769
784
  if (extract.exitCode !== 0) {
770
785
  log(
@@ -2862,7 +2877,7 @@ function createCloudProvider(backend, opts = {}) {
2862
2877
  onLog: log,
2863
2878
  // Daytona's linux-vm class accepts volume mounts and never honors them
2864
2879
  // (see ensureAgentVolumesForCloud) — take the per-create upload path.
2865
- volumesUsable: sandboxClass !== "linux-vm"
2880
+ volumesUsable: cloudVolumesUsable(sandboxClass)
2866
2881
  });
2867
2882
  const exposeServicePorts = await readExposedServicePorts(req.workspacePath);
2868
2883
  const credentialSyncOff = (req.credentialSync ?? (await loadEffectiveConfig(req.projectRoot ?? req.workspacePath)).effective.box.credentialSync) === false;
@@ -3448,7 +3463,7 @@ function createCloudProvider(backend, opts = {}) {
3448
3463
  }
3449
3464
  const handle = handleFor(box);
3450
3465
  const baseArgv = await backend.attachArgv(handle);
3451
- const inner = renderInnerCommand(kind, opts2);
3466
+ const inner = wrapAttachAsUser(renderInnerCommand(kind, opts2), backend.attachRunAs?.(handle));
3452
3467
  const viaStdin = backend.attachExecLacksTty === true && !opts2?.detached && kind !== "logs";
3453
3468
  const scriptPath = viaStdin ? attachScriptPath(opts2?.sessionName ?? kind) : "";
3454
3469
  if (viaStdin) {
@@ -3640,6 +3655,10 @@ function attachScriptPath(sessionName) {
3640
3655
  const safe = sessionName.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 40) || "attach";
3641
3656
  return `/tmp/agentbox-attach-${safe}.sh`;
3642
3657
  }
3658
+ function wrapAttachAsUser(inner, user) {
3659
+ if (!user) return inner;
3660
+ return `exec sudo -n -u ${user} -H bash -lc ${shellSingle(inner)}`;
3661
+ }
3643
3662
  function renderInnerCommand(kind, opts) {
3644
3663
  const sessionName = opts?.sessionName ?? defaultSessionName(kind);
3645
3664
  const fallback = opts?.command ?? defaultCommand(kind, opts);
@@ -4238,4 +4257,4 @@ export {
4238
4257
  openWebAppOnVncScreen,
4239
4258
  makeMockCloudBackend
4240
4259
  };
4241
- //# sourceMappingURL=chunk-4KYP775X.js.map
4260
+ //# sourceMappingURL=chunk-JLVUNDUB.js.map