@madarco/agentbox 0.24.5 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/LICENSE +21 -0
  3. package/README.md +4 -0
  4. package/dist/{_cloud-attach-ESCPOKG5.js → _cloud-attach-W2CFNXKO.js} +5 -5
  5. package/dist/{chunk-RFRWS5CD.js → chunk-4UNSBU5R.js} +2 -2
  6. package/dist/{chunk-H6A4BQMG.js → chunk-5F5SOSDY.js} +40 -1
  7. package/dist/chunk-5F5SOSDY.js.map +1 -0
  8. package/dist/{chunk-7DPDUZ7L.js → chunk-7C5MOA4Z.js} +194 -56
  9. package/dist/chunk-7C5MOA4Z.js.map +1 -0
  10. package/dist/{chunk-LJMGHFLZ.js → chunk-7PRLM3PH.js} +3 -3
  11. package/dist/chunk-G3H2L3O2.js +0 -0
  12. package/dist/{chunk-4HPLS5HJ.js → chunk-GHFIKSBJ.js} +110 -9
  13. package/dist/chunk-GHFIKSBJ.js.map +1 -0
  14. package/dist/{chunk-5JDOTQTM.js → chunk-LCZOQTIX.js} +4 -4
  15. package/dist/{chunk-QHISF6O6.js → chunk-LU3WAHTU.js} +3 -3
  16. package/dist/{chunk-CE3S7UDQ.js → chunk-NH3W6HUZ.js} +44 -12
  17. package/dist/chunk-NH3W6HUZ.js.map +1 -0
  18. package/dist/{chunk-OSPM4Q5V.js → chunk-VZC5J44U.js} +5 -5
  19. package/dist/chunk-VZC5J44U.js.map +1 -0
  20. package/dist/chunk-WJFZJZIM.js +0 -0
  21. package/dist/{chunk-3MDYQROX.js → chunk-Y3OPQWAQ.js} +11 -11
  22. package/dist/chunk-Y3OPQWAQ.js.map +1 -0
  23. package/dist/cloud-poller-SUNA6ZQC-7M5LJHHE.js +0 -0
  24. package/dist/{dist-TRKHS6I7.js → dist-3V5SLNK4.js} +6 -6
  25. package/dist/{dist-NOUPH5E6.js → dist-BIDAC4H4.js} +4 -4
  26. package/dist/{dist-VFPT5TDH.js → dist-I5OBPLP2.js} +6 -6
  27. package/dist/{dist-3M53BF4E.js → dist-IGQNVIV3.js} +6 -6
  28. package/dist/dist-KL73Z37T.js +677 -0
  29. package/dist/dist-KL73Z37T.js.map +1 -0
  30. package/dist/{dist-HPPHBZTO.js → dist-SBDYDH7H.js} +8 -2
  31. package/dist/{dist-FGXCG4JY.js → dist-UB3PYSCG.js} +6 -6
  32. package/dist/index.js +146 -54
  33. package/dist/index.js.map +1 -1
  34. package/dist/{prepared-state-BUO75YLZ-46W2PAHH.js → prepared-state-OBM2F7CU-DY7TZV4R.js} +2 -2
  35. package/package.json +29 -30
  36. package/runtime/_shared/agentbox-checkpoint-cleanup +0 -0
  37. package/runtime/_shared/agentbox-dockerd-start +0 -0
  38. package/runtime/_shared/agentbox-open +0 -0
  39. package/runtime/_shared/agentbox-portless-trust +0 -0
  40. package/runtime/_shared/agentbox-vnc-start +0 -0
  41. package/runtime/_shared/ctl.cjs +31 -4
  42. package/runtime/_shared/gh-shim +0 -0
  43. package/runtime/_shared/git-shim +0 -0
  44. package/runtime/_shared/linear-shim +0 -0
  45. package/runtime/_shared/ntn-shim +0 -0
  46. package/runtime/digitalocean/agentbox-checkpoint-cleanup +0 -0
  47. package/runtime/digitalocean/agentbox-dockerd-start +0 -0
  48. package/runtime/digitalocean/agentbox-open +0 -0
  49. package/runtime/digitalocean/agentbox-portless-trust +0 -0
  50. package/runtime/digitalocean/agentbox-vnc-start +0 -0
  51. package/runtime/digitalocean/ctl.cjs +31 -4
  52. package/runtime/digitalocean/gh-shim +0 -0
  53. package/runtime/digitalocean/git-shim +0 -0
  54. package/runtime/digitalocean/linear-shim +0 -0
  55. package/runtime/digitalocean/ntn-shim +0 -0
  56. package/runtime/digitalocean/scripts/install-box.sh +0 -0
  57. package/runtime/docker/packages/ctl/dist/bin.cjs +31 -4
  58. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup +0 -0
  59. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-dockerd-start +0 -0
  60. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-open +0 -0
  61. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-portless-trust +0 -0
  62. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-sshd-start +0 -0
  63. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-vnc-start +0 -0
  64. package/runtime/docker/packages/sandbox-docker/scripts/chromium-resolver +0 -0
  65. package/runtime/docker/packages/sandbox-docker/scripts/gh-shim +0 -0
  66. package/runtime/docker/packages/sandbox-docker/scripts/git-shim +0 -0
  67. package/runtime/docker/packages/sandbox-docker/scripts/linear-shim +0 -0
  68. package/runtime/docker/packages/sandbox-docker/scripts/ntn-shim +0 -0
  69. package/runtime/e2b/agentbox-checkpoint-cleanup +0 -0
  70. package/runtime/e2b/agentbox-dockerd-start +0 -0
  71. package/runtime/e2b/agentbox-open +0 -0
  72. package/runtime/e2b/agentbox-vnc-start +0 -0
  73. package/runtime/e2b/ctl.cjs +31 -4
  74. package/runtime/e2b/gh-shim +0 -0
  75. package/runtime/e2b/git-shim +0 -0
  76. package/runtime/e2b/linear-shim +0 -0
  77. package/runtime/e2b/ntn-shim +0 -0
  78. package/runtime/e2b/scripts/build-template.sh +0 -0
  79. package/runtime/hetzner/agentbox-checkpoint-cleanup +0 -0
  80. package/runtime/hetzner/agentbox-dockerd-start +0 -0
  81. package/runtime/hetzner/agentbox-open +0 -0
  82. package/runtime/hetzner/agentbox-portless-trust +0 -0
  83. package/runtime/hetzner/agentbox-vnc-start +0 -0
  84. package/runtime/hetzner/ctl.cjs +31 -4
  85. package/runtime/hetzner/gh-shim +0 -0
  86. package/runtime/hetzner/git-shim +0 -0
  87. package/runtime/hetzner/linear-shim +0 -0
  88. package/runtime/hetzner/ntn-shim +0 -0
  89. package/runtime/hetzner/scripts/install-box.sh +0 -0
  90. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  91. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  92. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  93. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  94. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  95. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  96. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  97. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  98. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  99. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d1lmiq._.js +6 -6
  100. package/runtime/hub/apps/hub/.next/server/chunks/_0760z6y._.js +1 -1
  101. package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0ro6vh6._.js +1 -1
  102. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  103. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  104. package/runtime/hub/apps/hub/{auth-HY5K55Y5.js → auth-MVL4NCQC.js} +3 -3
  105. package/runtime/hub/apps/hub/{auth-config-MNW2XGKK.js → auth-config-GRIXACTV.js} +3 -3
  106. package/runtime/hub/apps/hub/{chunk-OF242BLD.js → chunk-CKBHQ7OI.js} +1 -1
  107. package/runtime/hub/apps/hub/{chunk-PROXBLRJ.js → chunk-JLG5JJXD.js} +1 -1
  108. package/runtime/hub/apps/hub/{chunk-EY6HEDTK.js → chunk-LNHPLR3L.js} +11 -11
  109. package/runtime/hub/apps/hub/{chunk-DNR2YM2G.js → chunk-MA73PTOR.js} +57 -9
  110. package/runtime/hub/apps/hub/{chunk-TZFWAJVB.js → chunk-OG4KH2FZ.js} +5 -0
  111. package/runtime/hub/apps/hub/{chunk-5KMJIVZC.js → chunk-QBJOF5D3.js} +111 -10
  112. package/runtime/hub/apps/hub/chunk-QYJ37CUJ.js +62140 -0
  113. package/runtime/hub/apps/hub/{chunk-EFW34I43.js → chunk-UDZ3VXRF.js} +1 -1
  114. package/runtime/hub/apps/hub/{chunk-TRUQCO4U.js → chunk-V3OMPMI3.js} +40 -1
  115. package/runtime/hub/apps/hub/{cloud-poller-SUNA6ZQC-VSKVMYHL.js → cloud-poller-SUNA6ZQC-YAWTNA2W.js} +1 -1
  116. package/runtime/hub/apps/hub/{dist-YCRESLWD.js → dist-26KVXHXV.js} +7 -7
  117. package/runtime/hub/apps/hub/{dist-SX2NXGI6.js → dist-7LB4D4ZQ.js} +7 -7
  118. package/runtime/hub/apps/hub/{dist-M73U3ZDH.js → dist-ERQDDSOY.js} +7 -7
  119. package/runtime/hub/apps/hub/{dist-NTKPAYA3.js → dist-IZ2JCN5R.js} +8 -2
  120. package/runtime/hub/apps/hub/{dist-3DCKZYID.js → dist-SIQJD72C.js} +596 -113
  121. package/runtime/hub/apps/hub/{dist-RSWTJWRN.js → dist-YZJA4WRV.js} +5 -5
  122. package/runtime/hub/apps/hub/{dist-KV5ESR24.js → dist-ZVY2FWG6.js} +7 -7
  123. package/runtime/hub/apps/hub/esm-VGBJAFLR.js +79 -0
  124. package/runtime/hub/apps/hub/{execa-4DLVNM6E.js → execa-AFY4ZODY.js} +2 -2
  125. package/runtime/hub/apps/hub/{hub-token-QKQWV2I6.js → hub-token-BJG6Q5II.js} +3 -3
  126. package/runtime/hub/apps/hub/{prepared-state-BUO75YLZ-KR4YLKDC.js → prepared-state-OBM2F7CU-ZEYFNYFI.js} +3 -3
  127. package/runtime/hub/apps/hub/server.js +19 -19
  128. package/runtime/relay/bin.cjs +177 -42
  129. package/runtime/vercel/agentbox-checkpoint-cleanup +0 -0
  130. package/runtime/vercel/agentbox-dockerd-start +0 -0
  131. package/runtime/vercel/agentbox-open +0 -0
  132. package/runtime/vercel/agentbox-vnc-start +0 -0
  133. package/runtime/vercel/ctl.cjs +31 -4
  134. package/runtime/vercel/gh-shim +0 -0
  135. package/runtime/vercel/git-shim +0 -0
  136. package/runtime/vercel/linear-shim +0 -0
  137. package/runtime/vercel/ntn-shim +0 -0
  138. package/runtime/vercel/scripts/provision.sh +0 -0
  139. package/dist/chunk-3MDYQROX.js.map +0 -1
  140. package/dist/chunk-4HPLS5HJ.js.map +0 -1
  141. package/dist/chunk-7DPDUZ7L.js.map +0 -1
  142. package/dist/chunk-CE3S7UDQ.js.map +0 -1
  143. package/dist/chunk-H6A4BQMG.js.map +0 -1
  144. package/dist/chunk-OSPM4Q5V.js.map +0 -1
  145. package/dist/dist-2N3XHMBQ.js +0 -322
  146. package/dist/dist-2N3XHMBQ.js.map +0 -1
  147. /package/dist/{_cloud-attach-ESCPOKG5.js.map → _cloud-attach-W2CFNXKO.js.map} +0 -0
  148. /package/dist/{chunk-RFRWS5CD.js.map → chunk-4UNSBU5R.js.map} +0 -0
  149. /package/dist/{chunk-LJMGHFLZ.js.map → chunk-7PRLM3PH.js.map} +0 -0
  150. /package/dist/{chunk-5JDOTQTM.js.map → chunk-LCZOQTIX.js.map} +0 -0
  151. /package/dist/{chunk-QHISF6O6.js.map → chunk-LU3WAHTU.js.map} +0 -0
  152. /package/dist/{dist-HPPHBZTO.js.map → dist-3V5SLNK4.js.map} +0 -0
  153. /package/dist/{dist-NOUPH5E6.js.map → dist-BIDAC4H4.js.map} +0 -0
  154. /package/dist/{dist-TRKHS6I7.js.map → dist-I5OBPLP2.js.map} +0 -0
  155. /package/dist/{dist-3M53BF4E.js.map → dist-IGQNVIV3.js.map} +0 -0
  156. /package/dist/{dist-VFPT5TDH.js.map → dist-SBDYDH7H.js.map} +0 -0
  157. /package/dist/{dist-FGXCG4JY.js.map → dist-UB3PYSCG.js.map} +0 -0
  158. /package/dist/{prepared-state-BUO75YLZ-46W2PAHH.js.map → prepared-state-OBM2F7CU-DY7TZV4R.js.map} +0 -0
  159. /package/runtime/hub/apps/hub/.next/static/{43_nml7FKErUxJXpspAhb → c82uDoByt-dPQUHilRojD}/_buildManifest.js +0 -0
  160. /package/runtime/hub/apps/hub/.next/static/{43_nml7FKErUxJXpspAhb → c82uDoByt-dPQUHilRojD}/_clientMiddlewareManifest.js +0 -0
  161. /package/runtime/hub/apps/hub/.next/static/{43_nml7FKErUxJXpspAhb → c82uDoByt-dPQUHilRojD}/_ssgManifest.js +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../packages/sandbox-daytona/src/dockerfile-context.ts","../../../packages/sandbox-daytona/src/env-loader.ts","../../../packages/sandbox-daytona/src/prepared-state.ts","../../../packages/sandbox-daytona/src/backend.ts","../../../packages/sandbox-daytona/src/snapshot-wait.ts","../../../packages/sandbox-daytona/src/retry.ts","../../../packages/sandbox-daytona/src/credentials.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Locate `Dockerfile.box` + its build context so Daytona can `Image.fromDockerfile`\n * the same image the Docker provider builds locally. The Dockerfile COPYs from\n * the monorepo (packages/ctl/dist/bin.cjs, apps/cli/share/..., scripts/), so\n * the context dir must contain that tree.\n *\n * Mirrors `@agentbox/sandbox-docker`'s `resolveDockerBuild`, intentionally\n * inlined: sandbox-daytona must not depend on sandbox-docker (cross-provider\n * dep would defeat the point of `@agentbox/sandbox-cloud`).\n *\n * Resolution order:\n * 0. AGENTBOX_DOCKER_CONTEXT env override.\n * 1. Staged context shipped with the bundled `agent-box` package (sibling\n * of dist/, uniform in dev + installed).\n * 2. Legacy monorepo layout: Dockerfile.box at sandbox-docker's package\n * root, context = monorepo root.\n */\nexport interface DockerfileContext {\n dockerfile: string;\n context: string;\n}\n\nexport function resolveDockerfileContext(): DockerfileContext | null {\n const override = process.env.AGENTBOX_DOCKER_CONTEXT;\n if (override && existsSync(resolve(override, 'Dockerfile.box'))) {\n return { dockerfile: resolve(override, 'Dockerfile.box'), context: override };\n }\n const here = dirname(fileURLToPath(import.meta.url));\n const staged = resolve(here, '..', 'runtime', 'docker');\n if (existsSync(resolve(staged, 'Dockerfile.box'))) {\n return { dockerfile: resolve(staged, 'Dockerfile.box'), context: staged };\n }\n // Legacy monorepo: this module is at packages/sandbox-daytona/dist; the\n // Dockerfile lives at packages/sandbox-docker/Dockerfile.box; the build\n // context is the monorepo root.\n const monorepoRoot = resolve(here, '..', '..', '..');\n const dockerfile = resolve(monorepoRoot, 'packages', 'sandbox-docker', 'Dockerfile.box');\n if (existsSync(dockerfile)) {\n return { dockerfile, context: monorepoRoot };\n }\n return null;\n}\n\n/**\n * Locate the daytona-specific `custom-system-CLAUDE.md` that overlays the\n * docker-shaped one baked into `Dockerfile.box`. Daytona boxes have no host\n * `.git/` bind-mount, so the in-box hint needs daytona-specific git wording\n * (use `agentbox-ctl git` for any host-touching op). Same two-tier lookup\n * shape as `resolveDockerfileContext()`: staged CLI runtime first, monorepo\n * source as the dev fallback.\n */\nexport function resolveDaytonaCustomClaudeMd(): string | null {\n const here = dirname(fileURLToPath(import.meta.url));\n const staged = resolve(here, '..', 'runtime', 'daytona', 'custom-system-CLAUDE.md');\n if (existsSync(staged)) return staged;\n const monorepoRoot = resolve(here, '..', '..', '..');\n const dev = resolve(\n monorepoRoot,\n 'packages',\n 'sandbox-daytona',\n 'scripts',\n 'custom-system-CLAUDE.md',\n );\n if (existsSync(dev)) return dev;\n return null;\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\n\n/**\n * Daytona env auto-loader. The SDK reads `DAYTONA_API_KEY` /\n * `DAYTONA_JWT_TOKEN` + `DAYTONA_ORGANIZATION_ID` from `process.env`. We pull\n * those keys in from `~/.agentbox/secrets.env` so the SDK Just Works after\n * the user runs `agentbox daytona login` once.\n *\n * Lookup order (first wins; process.env is never overwritten):\n * 1. `process.env` (already set in the shell).\n * 2. `~/.agentbox/secrets.env` — written by `agentbox daytona login`.\n *\n * Project-level `.env` / `.env.local` are intentionally NOT consulted: those\n * files belong to the app code being developed, and a `DAYTONA_API_KEY`\n * there is typically meant for in-box code execution, not for the host CLI\n * to harvest and provision sandboxes with.\n *\n * Only Daytona-prefixed keys are imported; the rest of the file is left\n * alone. The loader is idempotent and side-effect-free after the first call.\n */\nconst DAYTONA_KEYS = [\n 'DAYTONA_API_KEY',\n 'DAYTONA_JWT_TOKEN',\n 'DAYTONA_ORGANIZATION_ID',\n 'DAYTONA_API_URL',\n 'DAYTONA_TARGET',\n] as const;\n\nlet loaded = false;\n\nexport function ensureDaytonaEnvLoaded(): void {\n if (loaded) return;\n loaded = true;\n importDaytonaFromFile(resolve(homedir(), '.agentbox', 'secrets.env'));\n}\n\nfunction importDaytonaFromFile(path: string): void {\n if (!existsSync(path)) return;\n let body: string;\n try {\n body = readFileSync(path, 'utf8');\n } catch {\n return;\n }\n const parsed = parseEnvFile(body);\n for (const key of DAYTONA_KEYS) {\n if (process.env[key] !== undefined) continue;\n const value = parsed[key];\n if (typeof value === 'string') {\n process.env[key] = value;\n }\n }\n}\n\n/**\n * Minimal `.env` parser: handles `KEY=value`, `KEY=\"value with spaces\"`,\n * `KEY='value with $special chars'`, `export KEY=value`, blank lines, and\n * `#` comments. Doesn't do variable interpolation — that's surprising to\n * users coming from full dotenv, but secrets typically don't reference each\n * other and we'd rather be predictable.\n */\nexport function parseEnvFile(body: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const rawLine of body.split(/\\r?\\n/)) {\n const line = rawLine.trim();\n if (line.length === 0 || line.startsWith('#')) continue;\n const stripped = line.startsWith('export ') ? line.slice('export '.length) : line;\n const eq = stripped.indexOf('=');\n if (eq <= 0) continue;\n const key = stripped.slice(0, eq).trim();\n let value = stripped.slice(eq + 1).trim();\n // Strip surrounding quotes (single or double).\n if (\n value.length >= 2 &&\n ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\")))\n ) {\n value = value.slice(1, -1);\n }\n out[key] = value;\n }\n return out;\n}\n","/**\n * Daytona provider's `~/.agentbox/daytona-prepared.json` reader/writer +\n * build-context fingerprinting for the org-scoped base snapshot.\n *\n * The daytona prepare bakes the docker `Dockerfile.box` plus a daytona-\n * specific `custom-system-CLAUDE.md` overlay. The fingerprint covers both\n * — same canonical file map as the docker provider for the dockerfile\n * inputs, plus one extra entry for the daytona overlay.\n */\n\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { DaytonaSandboxClass } from '@agentbox/config';\nimport {\n claudeInstallFingerprint,\n computeContextSha256,\n DOCKER_CONTEXT_FILE_MAP,\n readCliStamp,\n readPreparedStateRaw,\n resolveContextFilesFrom,\n writePreparedStateRaw,\n type ContextFile,\n type PreparedBaseSnapshot,\n} from '@agentbox/sandbox-core';\nimport { resolveDaytonaCustomClaudeMd, resolveDockerfileContext } from './dockerfile-context.js';\n\nconst SCHEMA = 1 as const;\n\n/** Provider-specific extras baked into the daytona snapshot. `size` is the\n * normalized `cpu-memory-disk` spec the snapshot was created with (absent =\n * a default-resource bake). `class` is the sandbox class it was baked as —\n * absent means a snapshot from before classes existed, i.e. a container.\n * A snapshot's class is immutable and cannot make a sandbox of the other\n * class, so this is what `provision` records on the box record. */\nexport interface DaytonaPreparedExtras {\n size?: string;\n class?: DaytonaSandboxClass;\n /**\n * The box image's `ENV` (`KEY=VALUE` strings), recorded by the linux-vm bake.\n *\n * A VM does NOT inherit the image's env — the conversion keeps the rootfs and\n * drops the metadata — so the bake writes it into the VM's `/etc` AND records\n * it here, because those two cover different processes: on-disk covers login\n * shells, while `create` hands this list to the sandbox as env vars, which is\n * what a plain non-login `exec` (how `agent-browser` starts Chromium) sees.\n * Absent on container bakes, which inherit `ENV` normally.\n */\n env?: string[];\n}\n\nexport type PreparedDaytonaState = PreparedBaseSnapshot<string, DaytonaPreparedExtras>;\n\n/**\n * Resolve every file that influences the daytona base snapshot: the docker\n * build context (shared map from sandbox-core) plus the daytona-specific\n * CLAUDE.md overlay added by `Image.addLocalFile` in `prepare.ts`.\n *\n * Returns `null` if any file is missing — callers degrade to \"always\n * rebuild\" rather than stamp a misleading fingerprint.\n */\nexport function resolveDaytonaContextFiles(): ContextFile[] | null {\n const docker = resolveDockerContextFilesForDaytona();\n if (!docker) return null;\n const overlay = resolveDaytonaCustomClaudeMd();\n if (!overlay) return null;\n return [\n ...docker,\n // Daytona-specific overlay: separate logical name so a docker/daytona\n // CLAUDE.md drift produces different fingerprints (the daytona snapshot\n // contains both files in distinct locations).\n { rel: 'daytona/custom-system-CLAUDE.md', abs: overlay },\n ];\n}\n\n/**\n * Just the DOCKER half of the context — no daytona overlay, no seed-schema salt.\n *\n * This is the exact file set (and therefore the exact sha) that CI hashes when\n * it publishes `ghcr.io/madarco/agentbox/box:sha-<...>`, so it — and only it —\n * can name the published image. The linux-vm bake needs that ref because Daytona\n * builds a VM snapshot only from a prebuilt registry image, never a Dockerfile.\n */\nexport function resolveDockerContextFilesForDaytona(): ContextFile[] | null {\n const ctx = resolveDockerfileContext();\n if (!ctx) return null;\n // sandbox-daytona's package root = parent of src/ or parent of dist/.\n // Mirrors the `resolve(here, '..', '..', '..')` walk in dockerfile-context.ts.\n const here = dirname(fileURLToPath(import.meta.url));\n const packageRoot = resolve(here, '..');\n const monorepoRoot = resolve(here, '..', '..', '..');\n // Docker's dev fallback is anchored at sandbox-docker's root, not\n // sandbox-daytona's, so we pass the monorepo root and prefix the dev\n // paths to walk into packages/sandbox-docker/.\n //\n // Simpler: just point devRoot at sandbox-docker's package root when it\n // exists (legacy monorepo layout).\n const dockerPackageRoot = resolve(monorepoRoot, 'packages', 'sandbox-docker');\n return resolveContextFilesFrom(DOCKER_CONTEXT_FILE_MAP, {\n contextDir: ctx.context,\n devRoot: existsSync(dockerPackageRoot) ? dockerPackageRoot : packageRoot,\n });\n}\n\n/**\n * The docker build-context sha for a given install mode — i.e. the tag of the\n * published GHCR box image the linux-vm base boots from.\n *\n * Folded with `claudeInstallFingerprint`, exactly like the docker pull path\n * (`pullOrBuild`): the same context built with `AGENTBOX_CLAUDE_INSTALL=npm` is\n * a different image and carries a different tag. CI publishes both variants\n * (`.github/workflows/box-image.yml` matrixes over the install mode), so an\n * npm-install bake now has a tag to boot from too — it used to have none, which\n * is why the VM path had to refuse npm outright and fall back to a container.\n */\nexport async function computeDockerBaseSha(\n claudeInstall: 'native' | 'npm' = 'native',\n): Promise<string | null> {\n const files = resolveDockerContextFilesForDaytona();\n if (!files) return null;\n return claudeInstallFingerprint(await computeContextSha256(files), claudeInstall);\n}\n\nexport interface DaytonaFingerprint {\n contextSha256: string;\n files: ContextFile[];\n}\n\n/**\n * Bumped when the daytona seed-bake BUILD LOGIC changes in a way the\n * context-file fingerprint can't see (the files are unchanged but the emitted\n * Dockerfile steps differ). `relctx-1`: switched from absolute `addLocalFile`\n * COPYs (which silently never landed) to relative `dockerfileCommands` COPYs.\n * Folding it into the fingerprint forces existing snapshots to re-bake once.\n */\nconst DAYTONA_SEED_SCHEMA = 'relctx-1';\n\nexport async function computeDaytonaContextFingerprint(): Promise<DaytonaFingerprint | null> {\n const files = resolveDaytonaContextFiles();\n if (!files) return null;\n const rawSha = await computeContextSha256(files);\n const contextSha256 = createHash('sha256')\n .update(`${rawSha}\\0daytona-seed=${DAYTONA_SEED_SCHEMA}`)\n .digest('hex');\n return { contextSha256, files };\n}\n\n/**\n * Compute the CURRENT build-context fingerprint for the daytona base snapshot.\n * Side-effect-free wrapper around `computeDaytonaContextFingerprint` that\n * returns just the SHA (or `undefined` when assets can't be resolved). Used\n * by the CLI's `evaluateBaseFreshness` to compare against the stored\n * `daytona-prepared.json.base.contextSha256`.\n */\nexport async function currentDaytonaBaseFingerprintLive(\n claudeInstall: 'native' | 'npm' = 'native',\n): Promise<string | undefined> {\n try {\n const fp = await computeDaytonaContextFingerprint();\n if (!fp?.contextSha256) return undefined;\n // Fold in claudeInstall exactly as `prepare` does — otherwise an npm-baked\n // base never matches the stored (npm-folded) fingerprint.\n return claudeInstallFingerprint(fp.contextSha256, claudeInstall);\n } catch {\n return undefined;\n }\n}\n\nexport function readPreparedDaytonaState(): PreparedDaytonaState | null {\n const raw = readPreparedStateRaw('daytona');\n if (raw === null || typeof raw !== 'object') return null;\n const parsed = raw as Partial<PreparedDaytonaState>;\n if (parsed.schema !== SCHEMA) return null;\n return { schema: SCHEMA, base: parsed.base, extras: parsed.extras };\n}\n\nexport function writePreparedDaytonaState(opts: {\n snapshotName: string;\n contextSha256: string;\n /** Normalized `cpu-memory-disk` size the snapshot was baked with (absent = default). */\n size?: string;\n /** Sandbox class the snapshot was baked as. Absent on pre-class bakes = container. */\n class?: DaytonaSandboxClass;\n /** The image env the linux-vm bake had to restore (see DaytonaPreparedExtras). */\n env?: string[];\n}): void {\n const stamp = readCliStamp();\n const extras: DaytonaPreparedExtras = {\n ...(opts.size ? { size: opts.size } : {}),\n ...(opts.class ? { class: opts.class } : {}),\n ...(opts.env && opts.env.length > 0 ? { env: opts.env } : {}),\n };\n const state: PreparedDaytonaState = {\n schema: SCHEMA,\n base: {\n imageRef: opts.snapshotName,\n contextSha256: opts.contextSha256,\n cliVersion: stamp.cliVersion,\n cliCommit: stamp.cliCommit,\n createdAt: new Date().toISOString(),\n },\n ...(Object.keys(extras).length > 0 ? { extras } : {}),\n };\n writePreparedStateRaw('daytona', state);\n}\n\n/**\n * A prepared snapshot matches when its build-context fingerprint, its baked\n * size AND its baked class all equal the requested ones. Neither size nor class\n * is folded into `contextSha256` — the live freshness check\n * (`currentDaytonaBaseFingerprintLive`) compares fingerprints only and takes no\n * config, so folding either in would make every sized/classed bake read as\n * \"context drifted\".\n *\n * An absent baked class means a snapshot from before classes existed, which was\n * necessarily a container — so it only matches a container request.\n */\nexport function preparedMatches(\n state: PreparedDaytonaState | null,\n current: string,\n size?: string,\n sandboxClass?: DaytonaSandboxClass,\n): boolean {\n if (state?.base?.contextSha256 !== current) return false;\n if ((state?.extras?.size ?? undefined) !== (size ?? undefined)) return false;\n if (sandboxClass === undefined) return true;\n return (state?.extras?.class ?? 'container') === sandboxClass;\n}\n","/**\n * Daytona `CloudBackend` — maps the provider-neutral cloud primitives onto\n * `@daytona/sdk`. Lazy SDK client + lazy sandbox handle resolution so\n * importing this module costs nothing until a daytona-tagged box does something.\n */\n\nimport { Daytona, DaytonaNotFoundError, Image, SandboxState, type Sandbox } from '@daytona/sdk';\nimport { DAYTONA_VM_REGION } from '@agentbox/config';\nimport type { CloudSandboxSummary } from '@agentbox/core';\nimport type {\n CloudBackend,\n CloudExecOptions,\n CloudExecResult,\n CloudFileEntry,\n CloudHandle,\n CloudPreviewUrl,\n CloudProvisionRequest,\n CloudState,\n CloudVolumeMount,\n} from '@agentbox/core';\nimport { resolveDockerfileContext } from './dockerfile-context.js';\nimport { ensureDaytonaEnvLoaded } from './env-loader.js';\nimport { readPreparedDaytonaState } from './prepared-state.js';\nimport { waitForSnapshotActive } from './snapshot-wait.js';\nimport { withDaytonaRetry } from './retry.js';\n\n/**\n * Thin shorthand for `withDaytonaRetry` with our defaults. Most methods are\n * idempotent and use `retryOnAmbiguous: true`; the few that aren't override.\n */\nfunction retry<T>(\n method: string,\n fn: () => Promise<T>,\n opts: {\n attemptTimeoutMs?: number;\n retryOnAmbiguous?: boolean;\n /** When true, single-shot — no backoff list, no retries. */\n noRetry?: boolean;\n } = {},\n): Promise<T> {\n return withDaytonaRetry(\n {\n method,\n retryOnAmbiguous: opts.retryOnAmbiguous ?? true,\n attemptTimeoutMs: opts.attemptTimeoutMs,\n backoffMs: opts.noRetry === true ? [] : undefined,\n },\n fn,\n );\n}\n\n/**\n * Sentinel image ref the cloud-provider hands to us when the user didn't pass\n * `--image`. We translate it to `Image.fromDockerfile(...)` so Daytona builds\n * the same box image the Docker provider builds locally.\n */\nexport const DEFAULT_BOX_IMAGE_REF = 'agentbox/box:dev';\n\n/**\n * Default sandbox shape — matches Daytona's own `daytona-vm-medium` preset.\n *\n * This MUST be passed explicitly at snapshot-create time. Daytona's true default\n * for a snapshot with no `resources` is 1 vCPU / 1 GiB / **3 GiB disk**, and the\n * box image doesn't fit in 3 GiB: the snapshot build dies mid-pull with a bare\n * \"internal error\".\n */\nexport const DAYTONA_DEFAULT_RESOURCES = { cpu: 2, memory: 4, disk: 8 } as const;\n\n/**\n * Clients keyed by region target ('' = the account default).\n *\n * Region only matters for **create**: `Daytona.create()` places the sandbox in\n * its *client's* target region (the `regionId` create param is ignored), and\n * only `us-east-1` has linux-vm runners. Everything else — `get`, `exec`,\n * `list`, start/stop/pause/delete — is region-agnostic: a default-target client\n * reaches a `us-east-1` sandbox fine and `list()` spans regions (verified\n * 2026-07-12). So the rest of the backend can keep using the default client and\n * only `provision` asks for a targeted one.\n */\nconst clients = new Map<string, Daytona>();\n\nexport function getClient(target = ''): Daytona {\n const cached = clients.get(target);\n if (cached) return cached;\n // Pull DAYTONA_* keys from `.env.local` / `.env` / `~/.agentbox/secrets.env`\n // into process.env first — the SDK reads from process.env and most users\n // keep secrets in a project file rather than their shell rc.\n ensureDaytonaEnvLoaded();\n try {\n // Daytona() reads DAYTONA_API_KEY / DAYTONA_JWT_TOKEN + DAYTONA_ORGANIZATION_ID\n // from env.\n const created = target.length > 0 ? new Daytona({ target }) : new Daytona();\n clients.set(target, created);\n return created;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n // The interactive prompt in `agentbox daytona login` handles first-run\n // setup; this error path is for non-TTY callers (CI, scripts) where the\n // prompt was skipped.\n throw new Error(\n `Daytona credentials not configured: ${msg}\\n` +\n `Run \\`agentbox daytona login\\` interactively, or set DAYTONA_API_KEY in the environment.`,\n );\n }\n}\n\nasync function getSandbox(id: string): Promise<Sandbox> {\n return getClient().get(id);\n}\n\nasync function maybeGetSandbox(id: string): Promise<Sandbox | null> {\n try {\n return await getClient().get(id);\n } catch {\n return null;\n }\n}\n\n/**\n * Map Daytona's `SandboxState` (fine-grained, incl. transitional values) onto\n * our 4-value `CloudState`. Transitional states ('starting', 'creating') are\n * reported as 'running' so callers don't ping-pong.\n *\n * Both of Daytona's cold states collapse to our 'paused': `archived` is what a\n * container box gets (our pause == Daytona's archive), `paused` is the real\n * VM freeze. A linux-vm box can never be archived and a container box can never\n * be paused, so the two are mutually exclusive per box — see `pause()`.\n */\nfunction mapState(s: SandboxState | string | undefined): CloudState {\n switch (s) {\n case SandboxState.STARTED:\n return 'running';\n case SandboxState.STARTING:\n case SandboxState.CREATING:\n case SandboxState.RESTORING:\n case SandboxState.BUILDING_SNAPSHOT:\n case SandboxState.PULLING_SNAPSHOT:\n case SandboxState.PENDING_BUILD:\n case SandboxState.STOPPING:\n case SandboxState.RESUMING:\n return 'running';\n case SandboxState.STOPPED:\n return 'stopped';\n case SandboxState.ARCHIVED:\n case SandboxState.ARCHIVING:\n case SandboxState.PAUSED:\n case SandboxState.PAUSING:\n return 'paused';\n case SandboxState.DESTROYED:\n case SandboxState.DESTROYING:\n case SandboxState.ERROR:\n case SandboxState.BUILD_FAILED:\n case SandboxState.UNKNOWN:\n default:\n return 'missing';\n }\n}\n\n/**\n * Translate our provider-neutral `CloudVolumeMount` into the SDK shape Daytona\n * expects. The SDK's `VolumeMount` carries `volumeId` + `mountPath` (+ optional\n * `subpath` for S3-prefix mounts); a 1:1 mapping with our type.\n */\nfunction toDaytonaVolumeMount(v: CloudVolumeMount): {\n volumeId: string;\n mountPath: string;\n subpath?: string;\n} {\n return {\n volumeId: v.volumeId,\n mountPath: v.mountPath,\n ...(v.subpath ? { subpath: v.subpath } : {}),\n };\n}\n\n/** Translate the request's image ref into something Daytona's `create` accepts. */\nfunction resolveImage(ref: string): string | Image {\n if (ref !== DEFAULT_BOX_IMAGE_REF) return ref;\n const ctx = resolveDockerfileContext();\n if (!ctx) {\n throw new Error(\n \"could not locate the AgentBox Dockerfile.box build context for the Daytona snapshot. \" +\n \"Set AGENTBOX_DOCKER_CONTEXT to a directory containing Dockerfile.box, or pass --image <ref> with a Daytona-compatible image.\",\n );\n }\n // Image.fromDockerfile bundles the directory the Dockerfile lives in and\n // ships it to Daytona to build a snapshot. The Dockerfile.box COPYs from\n // the monorepo tree; the staged `runtime/docker` context already mirrors\n // that tree, so the build resolves COPY paths correctly.\n return Image.fromDockerfile(ctx.dockerfile);\n}\n\n/**\n * Parse a `cpu-memory-disk` GB size spec (e.g. `4-8-20`) into Daytona's\n * `resources` shape. Returns `undefined` on any malformed input — three\n * positive integer slots are required.\n */\nexport function parseDaytonaSize(\n spec: string | undefined,\n): { cpu: number; memory: number; disk: number } | undefined {\n if (!spec) return undefined;\n const parts = spec.trim().split('-');\n if (parts.length !== 3) return undefined;\n const nums = parts.map((p) => Number(p));\n if (nums.some((n) => !Number.isInteger(n) || n <= 0)) return undefined;\n return { cpu: nums[0]!, memory: nums[1]!, disk: nums[2]! };\n}\n\nexport const daytonaBackend: CloudBackend = {\n name: 'daytona',\n\n async provision(req: CloudProvisionRequest): Promise<CloudHandle> {\n // No-retry: provision is non-idempotent — a 504 after the request reaches\n // the origin could create a duplicate billable sandbox we can't reference\n // for cleanup. The wrapper still bounds wall-clock at 900s (matching the\n // existing inline SDK timeout) so a wedged connection fails cleanly.\n return retry(\n 'provision',\n async () => {\n // Two SDK overloads:\n // - `CreateSandboxFromSnapshotParams` takes `snapshot:` and no\n // `onSnapshotCreateLogs` (the snapshot already exists, nothing to build).\n // - `CreateSandboxFromImageParams` takes `image:` and accepts\n // `onSnapshotCreateLogs` for streaming the Dockerfile build.\n // TypeScript can't infer the right overload from a union literal, so\n // split the call.\n // A `--size` / `box.sizeDaytona` like `4-8-20` overrides the default\n // resources. Note: Daytona rejects `resources` on the snapshot path\n // (stripped below), so this only takes effect when creating from an\n // image — snapshot-resume keeps the snapshot's baked-in resources.\n let sizeResources: { cpu: number; memory: number; disk: number } | undefined;\n if (req.size && req.size.length > 0) {\n sizeResources = parseDaytonaSize(req.size);\n if (!sizeResources) {\n req.onLog?.(\n `daytona: ignoring invalid size '${req.size}' (expected 'cpu-memory-disk' GB, e.g. '4-8-20')`,\n );\n }\n }\n const resources = sizeResources ?? req.resources;\n const prepared = readPreparedDaytonaState();\n const baseRef = req.snapshot ?? req.image;\n const bootingPreparedBase =\n prepared?.base?.imageRef !== undefined && baseRef === prepared.base.imageRef;\n // A linux-vm does NOT inherit the box image's `ENV` — the conversion keeps\n // the rootfs and drops the metadata — so the bake recorded it and we hand\n // it to the sandbox here. The bake also wrote it into the VM's /etc, but\n // that only reaches LOGIN shells; a plain `exec` (which is how the host\n // starts `agent-browser`, hence Chromium) sees only these env vars. Without\n // it there is no DISPLAY and the in-box browser dies with \"Missing X server\".\n // The box's own env (relay tokens, …) wins over the image's.\n const imageEnv: Record<string, string> = {};\n if (bootingPreparedBase) {\n for (const kv of prepared.extras?.env ?? []) {\n const i = kv.indexOf('=');\n if (i > 0) imageEnv[kv.slice(0, i)] = kv.slice(i + 1);\n }\n }\n const baseParams = {\n ...(resources ? { resources } : {}),\n envVars: { ...imageEnv, ...req.env },\n ...(req.volumes && req.volumes.length > 0\n ? { volumes: req.volumes.map(toDaytonaVolumeMount) }\n : {}),\n labels: { 'agentbox.name': req.name },\n // Daytona auto-stops a sandbox after N minutes of INACTIVITY (its own\n // default is 15). The host keepalive loop pushes this forward via\n // `renewTimeout` while an agent is working, so only a genuinely idle\n // box lapses. 0 disables it entirely.\n ...(typeof req.timeoutMs === 'number'\n ? { autoStopInterval: Math.max(0, Math.round(req.timeoutMs / 60_000)) }\n : {}),\n };\n // The class the base we're about to boot was ACTUALLY baked as. A\n // snapshot's class is immutable, so this — not `box.daytonaClass` —\n // decides what kind of box we can create. The two diverge whenever the\n // bake fell back: with no published box image (npm install mode, or any\n // locally shifted fingerprint) a linux-vm bake degrades to a container.\n // Believing config over reality dead-ended the user immediately after a\n // successful `prepare`, with \"no linux-vm base snapshot — run prepare\".\n // Absent `class` on a recorded base = baked before classes existed, i.e.\n // a container.\n const bakedClass = bootingPreparedBase\n ? (prepared.extras?.class ?? 'container')\n : undefined;\n const sandboxClass = bakedClass ?? req.sandboxClass;\n if (bakedClass && req.sandboxClass && bakedClass !== req.sandboxClass) {\n req.onLog?.(\n `daytona: base '${baseRef ?? ''}' was baked as '${bakedClass}', so this box will be a ` +\n `'${bakedClass}' one (box.daytonaClass asks for '${req.sandboxClass}'). ` +\n `Re-bake with \\`agentbox prepare --provider daytona --force\\` to change it.`,\n );\n }\n // `create` places the sandbox in its CLIENT's region — the `regionId`\n // create param is ignored — and only `us-east-1` has linux-vm runners.\n // An explicit `box.daytonaRegion` wins; otherwise derive the region from\n // the class we are actually booting, NOT from the requested one, or a\n // container base gets looked up in the one region that has no container\n // runners (and then reads as \"missing\", which is how this surfaced).\n const region =\n req.location && req.location.length > 0\n ? req.location\n : sandboxClass === 'linux-vm'\n ? DAYTONA_VM_REGION\n : '';\n const client = getClient(region);\n // The first-time Dockerfile.box snapshot build is ~41 layers and pulls\n // Chromium — comfortably 5+ minutes wall time. Daytona's default ready\n // timeout is too short for that; override with 15 min so a cold build\n // doesn't fail mid-snapshot. Cached snapshots and snapshot-based\n // creates come up in seconds.\n // Resolve `req.image` against Daytona's snapshot registry first when\n // it's set to a non-default value: `agentbox prepare --provider\n // daytona` registers a named snapshot and writes `box.image:\n // <name>` into project config; subsequent creates should boot from\n // that snapshot, not try to pull `<name>:latest` from Docker Hub.\n // Default ref (agentbox/box:dev) skips the lookup and goes through\n // resolveImage (Image.fromDockerfile). Explicit `req.snapshot` always\n // wins (cloud checkpoint path).\n let snapshotName = req.snapshot;\n if (!snapshotName && req.image && req.image !== DEFAULT_BOX_IMAGE_REF) {\n try {\n const snap = await client.snapshot.get(req.image);\n if (snap && snap.name) snapshotName = snap.name;\n } catch {\n // Not a known snapshot — fall through and treat as a Docker image ref.\n }\n }\n // Daytona rejects `resources` on the snapshot path — the snapshot's\n // own params encode them. Strip resources only for the snapshot\n // branch; the image branch keeps them.\n const snapshotParams: Record<string, unknown> = { ...baseParams };\n delete snapshotParams.resources;\n // On the snapshot path the size is fixed at bake time. If the user asked\n // for a size that differs from what the snapshot was baked with, warn\n // loudly — silently ignoring `--size` would leave them wondering why the\n // box came up the old size.\n if (snapshotName && sizeResources) {\n const bakedSize = prepared?.extras?.size;\n const requestedKey = `${String(sizeResources.cpu)}-${String(sizeResources.memory)}-${String(sizeResources.disk)}`;\n if (bakedSize !== requestedKey) {\n req.onLog?.(\n `daytona: WARNING — size '${requestedKey}' is ignored on the snapshot path; ` +\n `this snapshot was baked at ${bakedSize ?? 'the default size'}. ` +\n `Daytona resources are fixed at bake time — re-bake with ` +\n `\\`agentbox prepare --provider daytona --size ${requestedKey} --force\\` to change them.`,\n );\n }\n }\n // The image path builds a Dockerfile through Daytona's declarative\n // builder, which is CONTAINER-ONLY. Falling through to it when the user\n // asked for a VM would hand them a container box that silently can't\n // pause — so refuse, and point at the bake that produces a VM base.\n if (!snapshotName && sandboxClass === 'linux-vm') {\n throw new Error(\n `no linux-vm base snapshot for daytona: Daytona can only build a VM snapshot from a ` +\n `prebuilt image, not from a Dockerfile, so there is nothing to boot.\\n` +\n `Run \\`agentbox prepare --provider daytona\\` to bake one, or set ` +\n `\\`agentbox config set box.daytonaClass container\\` to use the container class.`,\n );\n }\n const sandbox = snapshotName\n ? await client.create({ snapshot: snapshotName, ...snapshotParams }, { timeout: 900 })\n : await client.create(\n { image: resolveImage(req.image), ...baseParams },\n {\n timeout: 900,\n ...(req.onLog ? { onSnapshotCreateLogs: req.onLog } : {}),\n },\n );\n // Record the class the box ACTUALLY booted as (resolved above from the\n // base's prepared state), never the requested one — a user whose\n // `box.daytonaClass` disagrees with the snapshot would otherwise have us\n // persist a lie, and `pause()` would then pick the wrong call.\n const bootedClass = sandboxClass;\n return {\n sandboxId: sandbox.id,\n ...(bootedClass ? { sandboxClass: bootedClass } : {}),\n };\n },\n { retryOnAmbiguous: false, attemptTimeoutMs: 900_000 },\n );\n },\n\n async ensureVolume(name: string): Promise<{ volumeId: string }> {\n // Daytona's `volume.get(name, create=true)` returns the existing volume or\n // initiates creation on first call. Critically, a freshly-created volume\n // comes back in `creating`/`pending_create` state — passing such a volume\n // into `Daytona.create({ volumes: […] })` is rejected with\n // \"Volume is not in a ready state. Current state: creating\". So poll\n // `volume.get` until the state lands on `ready` (or a terminal failure).\n //\n // Volumes are org-scoped on Daytona — every sandbox in the same Daytona\n // organization sees the same id, which is what we want for sharing agent\n // credentials across all of a user's boxes.\n //\n // Each individual `volume.get` call is retry-wrapped so a transient edge\n // hiccup mid-poll doesn't fail the whole ensure.\n const client = getClient();\n let vol = await retry('volume.get(create)', () => client.volume.get(name, true));\n // Volumes typically transition from creating → ready within a few seconds.\n // Allow up to 60s in case of slow control-plane operations.\n const deadline = Date.now() + 60_000;\n while (vol.state !== 'ready') {\n if (vol.state === 'error' || vol.state === 'deleted' || vol.state === 'deleting') {\n throw new Error(\n `Daytona volume '${name}' is in unrecoverable state '${vol.state}'. ` +\n `Delete it from the Daytona dashboard and retry.`,\n );\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Daytona volume '${name}' did not become ready within 60s (state: ${vol.state}). ` +\n `Try again — the Daytona control plane may be slow.`,\n );\n }\n await new Promise((r) => setTimeout(r, 1000));\n vol = await retry('volume.get(poll)', () => client.volume.get(name));\n }\n return { volumeId: vol.id };\n },\n\n async get(sandboxId: string): Promise<CloudHandle | null> {\n return retry('get', async () => {\n const sb = await maybeGetSandbox(sandboxId);\n return sb ? { sandboxId: sb.id } : null;\n });\n },\n\n async list(): Promise<CloudSandboxSummary[]> {\n return retry('list', async () => {\n const client = getClient();\n // `client.list()` is an AsyncIterableIterator that pages internally (it\n // was a single awaited page before SDK 0.196). It spans regions, so one\n // pass sees `us` container boxes and `us-east-1` VM boxes alike.\n const items: CloudSandboxSummary[] = [];\n for await (const sb of client.list()) {\n const summary: CloudSandboxSummary = { sandboxId: sb.id };\n const raw = sb as unknown as {\n name?: string;\n labels?: Record<string, string>;\n state?: string;\n createdAt?: string;\n };\n const friendly = raw.labels?.['agentbox.name'] ?? raw.name;\n if (friendly) summary.name = friendly;\n if (raw.createdAt) summary.createdAt = raw.createdAt;\n if (typeof raw.state === 'string') summary.state = mapState(raw.state);\n items.push(summary);\n }\n return items;\n });\n },\n\n async start(h: CloudHandle): Promise<void> {\n return retry(\n 'start',\n async () => {\n const sb = await getSandbox(h.sandboxId);\n await sb.start();\n },\n { attemptTimeoutMs: 60_000 },\n );\n },\n\n async stop(h: CloudHandle): Promise<void> {\n return retry(\n 'stop',\n async () => {\n const sb = await getSandbox(h.sandboxId);\n await sb.stop();\n },\n { attemptTimeoutMs: 60_000 },\n );\n },\n\n async pause(h: CloudHandle): Promise<void> {\n // The two classes need different calls and each rejects the other's:\n // - linux-vm: `pause()` freezes CPU + memory, so running processes and\n // tmux sessions survive a resume. It cannot be archived\n // (\"Sandboxes in this region or class cannot be archived\").\n // - container: no pause primitive; `archive()` moves it to cold storage\n // (filesystem only) — the historical AgentBox behavior.\n //\n // `h.sandboxClass` comes off the box record. It's absent for records written\n // before the class existed and for the keepalive loop's synthetic handles,\n // so fall back to trying both rather than guessing wrong.\n return retry(\n 'pause',\n async () => {\n const sb = await getSandbox(h.sandboxId);\n // linux-vm: freeze in place, memory and all.\n const freeze = async (): Promise<void> => {\n await sb.pause();\n };\n // container: Daytona archives only a STOPPED sandbox — calling\n // `archive()` on a running one fails with \"Sandbox is not stopped\", so\n // stop it first. (`stop()` is a no-op on an already-stopped sandbox.)\n const archive = async (): Promise<void> => {\n await sb.stop();\n await sb.archive();\n };\n // Try the recorded class first, then the other. The recorded class can\n // be wrong or absent — pre-feature records, the keepalive loop's\n // synthetic handles, and a checkpoint restored while `box.daytonaClass`\n // names the *other* class (the box's real class comes from the snapshot,\n // not from config). Whichever call is wrong is rejected outright rather\n // than doing something surprising, so trying both is safe.\n const preferVm = h.sandboxClass !== 'container';\n try {\n await (preferVm ? freeze() : archive());\n } catch (err) {\n try {\n await (preferVm ? archive() : freeze());\n } catch {\n throw err; // report the failure for the class we believed it was\n }\n }\n },\n { attemptTimeoutMs: 120_000 },\n );\n },\n\n async resume(h: CloudHandle): Promise<void> {\n // `start()` resumes both classes — a paused VM thaws (memory intact), an\n // archived container is restored from cold storage.\n return retry(\n 'resume',\n async () => {\n const sb = await getSandbox(h.sandboxId);\n await sb.start();\n },\n { attemptTimeoutMs: 60_000 },\n );\n },\n\n /**\n * Daytona's `autoStopInterval` is an idle window that any request to the\n * sandbox resets — including the host relay's own continuous preview-URL\n * polling, which therefore holds every tracked box open forever. The host\n * keepalive loop reads this and pauses an idle box itself instead of waiting\n * for a lapse that never comes. See `CloudBackend.timeoutModel`.\n */\n timeoutModel: 'inactivity',\n\n /**\n * Daytona's SSH gateway gives a shell session a terminal but an exec session\n * none — `ssh -tt <token>@ssh.app.daytona.io 'tty'` answers \"not a tty\" while\n * the same connection with no command lands on /dev/pts/1. So interactive\n * attach connects command-less and gets its command via stdin. See\n * `CloudBackend.attachExecLacksTty`.\n */\n attachExecLacksTty: true,\n\n /**\n * Hold off Daytona's auto-stop while the in-box agent is working.\n *\n * Daytona's timeout is an INACTIVITY window, not an absolute deadline like\n * vercel's/e2b's, so there is nothing to extend to a target time — the box\n * simply needs to look active. `refreshActivity()` resets that clock, which\n * grants another full `autoStopInterval`. So both deadline args are unused:\n * the host loop calls us precisely when it wants the box kept alive, and that\n * call is the whole signal.\n */\n async renewTimeout(h: CloudHandle): Promise<void> {\n await retry(\n 'renewTimeout',\n async () => {\n const sb = await getSandbox(h.sandboxId);\n await sb.refreshActivity();\n },\n { attemptTimeoutMs: 30_000 },\n );\n },\n\n async destroy(h: CloudHandle): Promise<void> {\n return retry(\n 'destroy',\n async () => {\n const sb = await maybeGetSandbox(h.sandboxId);\n if (!sb) return; // already gone — destroy is idempotent\n // Daytona's `delete()` on a running sandbox is queued, not synchronous —\n // observed in practice: `delete()` returns ok, the sandbox stays in\n // 'started' for tens of seconds, then eventually disappears. Stopping\n // first makes the delete synchronous so callers (and the dashboard) see\n // it gone immediately. Swallow stop errors — if the sandbox is already\n // stopped/archived, delete still works.\n try {\n await sb.stop(60);\n } catch {\n /* best-effort */\n }\n try {\n await sb.delete(60);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n // Already deleted between stop and delete — fine.\n if (!/not found/i.test(msg)) throw err;\n }\n },\n { attemptTimeoutMs: 120_000 },\n );\n },\n\n async state(h: CloudHandle): Promise<CloudState> {\n return retry('state', async () => {\n const sb = await maybeGetSandbox(h.sandboxId);\n if (!sb) return 'missing';\n return mapState(sb.state);\n });\n },\n\n async exec(\n h: CloudHandle,\n cmd: string,\n opts?: CloudExecOptions,\n ): Promise<CloudExecResult> {\n return retry(\n 'exec',\n async () => {\n const sb = await getSandbox(h.sandboxId);\n // Daytona's ExecuteResponse returns combined output in `result` with no\n // separate stderr stream. Surface it as stdout and leave stderr empty —\n // callers that need split streams must redirect inside `cmd` itself.\n const r = await sb.process.executeCommand(cmd, opts?.cwd, opts?.env);\n return { exitCode: r.exitCode, stdout: r.result, stderr: '' };\n },\n { attemptTimeoutMs: opts?.attemptTimeoutMs ?? 120_000, noRetry: opts?.noRetry },\n );\n },\n\n async uploadFile(h: CloudHandle, localPath: string, remotePath: string): Promise<void> {\n return retry(\n 'uploadFile',\n async () => {\n const sb = await getSandbox(h.sandboxId);\n await sb.fs.uploadFile(localPath, remotePath);\n },\n { attemptTimeoutMs: 300_000 },\n );\n },\n\n async downloadFile(h: CloudHandle, remotePath: string, localPath: string): Promise<void> {\n return retry(\n 'downloadFile',\n async () => {\n const sb = await getSandbox(h.sandboxId);\n await sb.fs.downloadFile(remotePath, localPath);\n },\n { attemptTimeoutMs: 300_000 },\n );\n },\n\n async listFiles(h: CloudHandle, remoteDir: string): Promise<CloudFileEntry[]> {\n return retry('listFiles', async () => {\n const sb = await getSandbox(h.sandboxId);\n const files = await sb.fs.listFiles(remoteDir);\n return files.map((f) => ({\n name: f.name,\n isDir: Boolean((f as { isDir?: boolean }).isDir),\n }));\n });\n },\n\n async previewUrl(h: CloudHandle, port: number): Promise<CloudPreviewUrl> {\n return retry('previewUrl', async () => {\n const sb = await getSandbox(h.sandboxId);\n const p = await sb.getPreviewLink(port);\n // The host CloudBoxPoller attaches `token` as `x-daytona-preview-token`\n // for every /bridge call. Browser-bound URLs use `signedPreviewUrl` below\n // instead (the two token kinds are not interchangeable on Daytona).\n return { url: p.url, token: p.token };\n });\n },\n\n async signedPreviewUrl(\n h: CloudHandle,\n port: number,\n expiresInSeconds: number,\n ): Promise<CloudPreviewUrl> {\n return retry('signedPreviewUrl', async () => {\n const sb = await getSandbox(h.sandboxId);\n const s = await sb.getSignedPreviewUrl(port, expiresInSeconds);\n return { url: s.url, token: s.token };\n });\n },\n\n async attachArgv(h: CloudHandle): Promise<string[]> {\n return retry('attachArgv', async () => {\n const sb = await getSandbox(h.sandboxId);\n // 60 min default expiry matches the SDK default; an interactive session\n // longer than that is rare. `sandbox-cloud`'s buildAttach appends\n // `-t '<inner cmd>'` for the per-session tmux attach.\n const ssh = await sb.createSshAccess(60);\n return [\n 'ssh',\n // First-connect to a never-seen host fingerprint should be silent in a\n // PTY — the user already authenticated via Daytona's API.\n '-o', 'StrictHostKeyChecking=accept-new',\n // Daytona's SSH gateway terminates per-token; no key file, no port.\n `${ssh.token}@ssh.app.daytona.io`,\n ];\n });\n },\n\n async revokeAttachToken(h: CloudHandle, argv: string[]): Promise<void> {\n // argv[3] = `${token}@ssh.app.daytona.io`; pull the token off the front.\n const userhost = argv[argv.length - 1] ?? '';\n const atIdx = userhost.indexOf('@');\n if (atIdx <= 0) return;\n const token = userhost.slice(0, atIdx);\n if (token.length === 0) return;\n try {\n await retry('revokeAttachToken', async () => {\n const sb = await getSandbox(h.sandboxId);\n await sb.revokeSshAccess(token);\n });\n } catch {\n // Best-effort — tokens auto-expire after 60 min anyway.\n }\n },\n\n async createSnapshot(h: CloudHandle, snapshotName: string): Promise<void> {\n // A cold (filesystem-only) snapshot requires the sandbox STOPPED, and the\n // API does not stop it for you — a capture attempted on a running sandbox\n // is rejected. So: stop, capture, start again. The caller is responsible for\n // reconnecting the box afterwards (the stop kills ctl/dockerd/tmux) — see\n // `makeDaytonaCheckpoint`.\n //\n // The hot variant (filesystem + memory, linux-vm only) would avoid the stop\n // entirely, but it needs `includeMemory`, and the published TS SDK silently\n // drops that argument. Out of reach until upstream fixes the wrapper.\n //\n // No retry on ambiguous failures: a 504 mid-capture could leave a half-built\n // named snapshot that a retry would collide on. Matches `provision`'s policy.\n return retry(\n 'createSnapshot',\n async () => {\n const sb = await getSandbox(h.sandboxId);\n await sb.stop();\n try {\n await sb._experimental_createSnapshot(snapshotName, 900);\n await waitForSnapshotActive(getClient(), snapshotName);\n } finally {\n // Always bring the box back, even if the capture failed — leaving a\n // user's box stopped because a checkpoint errored is a worse outcome\n // than the failed checkpoint itself.\n await sb.start();\n }\n },\n { attemptTimeoutMs: 900_000, retryOnAmbiguous: false },\n );\n },\n\n async deleteSnapshot(snapshotName: string): Promise<void> {\n return retry('deleteSnapshot', async () => {\n try {\n const client = getClient();\n const snapshot = await client.snapshot.get(snapshotName);\n await client.snapshot.delete(snapshot);\n } catch (err) {\n // Idempotent: a snapshot that's already gone is success from the\n // caller's perspective (mirrors `destroy()`'s \"not found\" handling).\n if (err instanceof DaytonaNotFoundError) return;\n const msg = err instanceof Error ? err.message : String(err);\n if (/not found/i.test(msg)) return;\n throw err;\n }\n });\n },\n};\n","/**\n * Wait for a Daytona snapshot to reach `active`.\n *\n * `_experimental_createSnapshot` returns once the capture is *requested*; the\n * snapshot only becomes usable a little later. Acting on it before then — a\n * `create({ snapshot })`, or deleting the source sandbox — is racy, so every\n * capture path waits here first.\n *\n * Its own module because both the VM bake and the checkpoint path need it, and\n * the bake imports the backend (which owns the checkpoint), so a shared home\n * avoids an import cycle.\n */\nimport type { Daytona } from '@daytona/sdk';\n\nexport async function waitForSnapshotActive(\n client: Daytona,\n name: string,\n timeoutMs = 900_000,\n): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n let state: string | undefined;\n try {\n state = (await client.snapshot.get(name))?.state;\n } catch {\n // A just-requested snapshot can 404 briefly before it's registered.\n state = undefined;\n }\n if (state === 'active') return;\n if (state === 'error' || state === 'build_failed') {\n throw new Error(`daytona snapshot '${name}' ended in state '${state}'`);\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `daytona snapshot '${name}' did not become active within ${String(Math.round(timeoutMs / 60_000))} min ` +\n `(state: ${state ?? 'unknown'})`,\n );\n }\n await new Promise((r) => setTimeout(r, 3000));\n }\n}\n","/**\n * Bounded retry wrapper for `daytonaBackend` SDK calls. Daytona's CloudFront\n * edge intermittently 504s on `executeCommand` and other API calls (backlog\n * item 6.1) — without bounded retries an edge hiccup propagates as an\n * unbounded wedge in the calling code. This helper classifies transient\n * failures vs. permanent ones using the SDK's typed error classes, bounds\n * each attempt with a timeout, and caps the total wall-clock cost.\n *\n * Non-idempotent ops (`provision`) pass `retryOnAmbiguous: false` so a 504\n * after the request reached the origin doesn't create a duplicate sandbox.\n */\n\nimport {\n DaytonaAuthenticationError,\n DaytonaAuthorizationError,\n DaytonaConflictError,\n DaytonaConnectionError,\n DaytonaError,\n DaytonaNotFoundError,\n DaytonaRateLimitError,\n DaytonaTimeoutError,\n DaytonaValidationError,\n} from '@daytona/sdk';\n\nexport interface WithRetryOptions {\n /** Method name, used in retry log lines. */\n method: string;\n /** Per-attempt timeout (ms). Default 30_000. */\n attemptTimeoutMs?: number;\n /** Backoff before attempts 2, 3, … (ms). Default [1000, 2000, 4000]. */\n backoffMs?: readonly number[];\n /**\n * Whether to retry on errors where we can't be sure the server applied\n * the request — connection failures, per-attempt timeouts, and 5xx\n * responses (since 504 from CloudFront can mean \"origin still processing\").\n * Set false for non-idempotent operations (e.g. `provision`) where a\n * retry could create a duplicate.\n */\n retryOnAmbiguous: boolean;\n /** Override the default `process.stderr` retry sink (used by tests). */\n onRetry?: (line: string) => void;\n}\n\nconst DEFAULT_BACKOFF: readonly number[] = [1000, 2000, 4000];\nconst DEFAULT_ATTEMPT_TIMEOUT_MS = 30_000;\n\n/** Internal sentinel used by the per-attempt timeout race. */\nclass AttemptTimeoutError extends Error {\n constructor(method: string, ms: number) {\n super(`daytona ${method}: per-attempt timeout after ${String(ms)}ms`);\n this.name = 'AttemptTimeoutError';\n }\n}\n\nexport function isAttemptTimeout(err: unknown): err is AttemptTimeoutError {\n return err instanceof AttemptTimeoutError;\n}\n\n/**\n * Classify an error as retriable or not. `allowAmbiguous` gates the cases\n * where the server may or may not have applied the request — the caller\n * decides based on idempotency.\n */\nexport function isRetriable(err: unknown, allowAmbiguous: boolean): boolean {\n // Rate-limit responses always carry an intent from the server: back off.\n if (err instanceof DaytonaRateLimitError) return true;\n\n // Permanent client-side failures: never retry — the next call will get\n // the same answer and we'd just be wasting wall-clock.\n if (\n err instanceof DaytonaNotFoundError ||\n err instanceof DaytonaAuthenticationError ||\n err instanceof DaytonaAuthorizationError ||\n err instanceof DaytonaValidationError ||\n err instanceof DaytonaConflictError\n ) {\n return false;\n }\n\n // Connection / per-attempt timeout: the request may not have reached\n // the server. Gated by allowAmbiguous so non-idempotent callers can opt\n // out of double-execute risk.\n if (\n err instanceof DaytonaConnectionError ||\n err instanceof DaytonaTimeoutError ||\n err instanceof AttemptTimeoutError\n ) {\n return allowAmbiguous;\n }\n\n // Base DaytonaError: branch on statusCode. 5xx is ambiguous; 4xx we\n // didn't catch above is a permanent failure we hadn't seen before.\n if (err instanceof DaytonaError) {\n const status = err.statusCode;\n if (typeof status === 'number' && status >= 500 && status <= 599) {\n return allowAmbiguous;\n }\n return false;\n }\n\n // Axios-style fallback for raw errors that leak through without an SDK\n // wrapper. Match the same shape the SDK uses internally.\n if (err && typeof err === 'object') {\n const code = (err as { code?: unknown }).code;\n if (\n code === 'ECONNRESET' ||\n code === 'ETIMEDOUT' ||\n code === 'ECONNABORTED' ||\n code === 'EAI_AGAIN' ||\n code === 'ECONNREFUSED' ||\n code === 'ENOTFOUND'\n ) {\n return allowAmbiguous;\n }\n const status =\n (err as { response?: { status?: unknown } }).response?.status ??\n (err as { status?: unknown }).status ??\n (err as { statusCode?: unknown }).statusCode;\n if (typeof status === 'number' && status >= 500 && status <= 599) {\n return allowAmbiguous;\n }\n }\n\n return false;\n}\n\n/**\n * Run `fn`, retrying on transient failures with capped exponential backoff.\n * Each attempt is bounded by `attemptTimeoutMs` via Promise.race; total\n * wall-clock = sum(backoffMs) + maxAttempts * attemptTimeoutMs.\n */\nexport async function withDaytonaRetry<T>(\n opts: WithRetryOptions,\n fn: () => Promise<T>,\n): Promise<T> {\n const backoff = opts.backoffMs ?? DEFAULT_BACKOFF;\n const maxAttempts = backoff.length + 1;\n const timeoutMs = opts.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS;\n const log = opts.onRetry ?? defaultRetryLog;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await raceTimeout(fn(), timeoutMs, opts.method);\n } catch (err) {\n const last = attempt === maxAttempts;\n if (last || !isRetriable(err, opts.retryOnAmbiguous)) throw err;\n const delay = backoff[attempt - 1] ?? backoff[backoff.length - 1] ?? 4000;\n log(\n `daytona ${opts.method}: attempt ${String(attempt)} failed (${errorSummary(err)}); retrying in ${String(delay)}ms`,\n );\n await sleep(delay);\n }\n }\n // Unreachable: the loop above either returns or throws.\n throw new Error(`withDaytonaRetry: exhausted attempts for ${opts.method}`);\n}\n\nfunction defaultRetryLog(line: string): void {\n // Prefix so log scrapers + users can distinguish retry chatter from real\n // CLI output. `\\n` before is intentional — many CLI surfaces use clack\n // spinners on stdout, and stderr lines without a leading newline can\n // collide with a redraw.\n process.stderr.write(`\\n[daytona-retry] ${line}\\n`);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function raceTimeout<T>(p: Promise<T>, ms: number, method: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n p,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new AttemptTimeoutError(method, ms)), ms);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\nfunction errorSummary(err: unknown): string {\n if (err instanceof DaytonaError) {\n const status = err.statusCode;\n const cls = err.constructor.name;\n return `${cls}${typeof status === 'number' ? ` ${String(status)}` : ''}: ${truncate(err.message)}`;\n }\n if (err instanceof Error) {\n const code = (err as { code?: unknown }).code;\n return code !== undefined ? `${err.name}(${String(code)}): ${truncate(err.message)}` : `${err.name}: ${truncate(err.message)}`;\n }\n return truncate(String(err));\n}\n\nfunction truncate(s: string, max = 160): string {\n return s.length > max ? `${s.slice(0, max)}…` : s;\n}\n","import { spawnSync } from 'node:child_process';\nimport { hostOpenCommand, writeManagedSecrets, type CredSetResult } from '@agentbox/sandbox-core';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\nimport {\n cancel,\n confirm,\n isCancel,\n intro,\n log,\n note,\n outro,\n password,\n spinner,\n text,\n} from '@clack/prompts';\nimport { ensureDaytonaEnvLoaded } from './env-loader.js';\n\n// Ctrl+C at a prompt resolves with the cancel symbol; turn that into a real\n// quit so the command never silently continues as if the user answered \"No\".\nfunction exitOnCancel<T>(v: T | symbol): T {\n if (isCancel(v)) {\n cancel('Cancelled.');\n process.exit(130);\n }\n return v as T;\n}\n\nconst DASHBOARD_KEYS_URL = 'https://app.daytona.io/dashboard/keys';\n\n/**\n * Keys we manage in `~/.agentbox/secrets.env`. When the user reconfigures we\n * strip any prior values for these keys before appending the new ones so the\n * file never accumulates duplicates.\n */\nconst MANAGED_KEYS = ['DAYTONA_API_KEY', 'DAYTONA_JWT_TOKEN', 'DAYTONA_ORGANIZATION_ID'] as const;\ntype ManagedKey = (typeof MANAGED_KEYS)[number];\n\nexport interface EnsureDaytonaCredentialsOptions {\n /** Re-prompt even when valid credentials are already present (used by `agentbox daytona login`). */\n force?: boolean;\n}\n\n/**\n * First-run interactive setup for Daytona credentials. Walks the user through\n * opening the dashboard, pasting an API key (or JWT + organization ID), and\n * persists the result to `~/.agentbox/secrets.env` — which the env-loader\n * already picks up for every cloud command.\n *\n * No-op when credentials are already configured (env var or our secrets\n * file). Silent no-op when stdin isn't a TTY so scripted/CI callers get the\n * \"credentials not configured\" error from the SDK instead of a hung prompt.\n */\nexport async function ensureDaytonaCredentials(\n opts: EnsureDaytonaCredentialsOptions = {},\n): Promise<void> {\n ensureDaytonaEnvLoaded();\n\n if (!opts.force && hasUsableCredentials()) return;\n if (!process.stdin.isTTY) return;\n\n intro('Daytona setup');\n note(\n `AgentBox needs a Daytona API key to provision cloud boxes.\\n` +\n `Generate one at ${DASHBOARD_KEYS_URL}`,\n 'API key required',\n );\n\n const open = exitOnCancel(\n await confirm({\n message: `Open ${DASHBOARD_KEYS_URL} in your browser?`,\n initialValue: true,\n }),\n );\n if (open) openDashboard();\n\n // One retry on auth failure (typos are the common case). Beyond that we bail\n // and surface the validation error; the user can re-run `agentbox daytona login`.\n for (let attempt = 0; attempt < 2; attempt++) {\n const creds = await promptForCredentials();\n\n const result = await validateCredentials(creds);\n if (result.ok) {\n persistCredentials(creds);\n log.success(`Daytona credentials saved to ${secretsPath()}`);\n outro('Setup complete.');\n return;\n }\n if (result.kind === 'auth' && attempt === 0) {\n log.error(`That key was rejected by Daytona: ${result.message}`);\n log.info('Try again, or press Ctrl-C to cancel.');\n continue;\n }\n if (result.kind === 'network') {\n log.warn(`Could not reach Daytona to validate (${result.message}) — saving anyway.`);\n persistCredentials(creds);\n log.success(`Daytona credentials saved to ${secretsPath()}`);\n outro('Setup complete (unvalidated).');\n return;\n }\n throw new Error(`Daytona credentials rejected: ${result.message}`);\n }\n}\n\nfunction hasUsableCredentials(): boolean {\n if (process.env.DAYTONA_API_KEY) return true;\n if (process.env.DAYTONA_JWT_TOKEN && process.env.DAYTONA_ORGANIZATION_ID) return true;\n return false;\n}\n\ninterface Credentials {\n apiKey?: string;\n jwtToken?: string;\n organizationId?: string;\n}\n\nasync function promptForCredentials(): Promise<Credentials> {\n const key = exitOnCancel(\n await password({\n message: 'Paste your Daytona API key (or JWT token)',\n validate(v) {\n if (!v || v.trim().length === 0) return 'Cannot be empty';\n return undefined;\n },\n }),\n );\n const trimmed = key.trim();\n\n // JWTs start with `eyJ` (base64-encoded `{\"`). API keys don't, and don't need\n // an org ID — the SDK derives it from the key. Only ask for org ID for JWTs.\n if (trimmed.startsWith('eyJ')) {\n const org = exitOnCancel(\n await text({\n message: 'Paste your Daytona organization ID',\n placeholder: 'org_...',\n validate(v) {\n if (!v || v.trim().length === 0) return 'Cannot be empty';\n return undefined;\n },\n }),\n );\n return { jwtToken: trimmed, organizationId: org.trim() };\n }\n\n return { apiKey: trimmed };\n}\n\ntype ValidationResult =\n | { ok: true }\n | { ok: false; kind: 'auth'; message: string }\n | { ok: false; kind: 'network'; message: string };\n\nasync function validateCredentials(creds: Credentials): Promise<ValidationResult> {\n const s = spinner();\n s.start('Validating credentials with Daytona');\n\n // Snapshot existing env so we can restore on failure — never poison\n // process.env with a bad key.\n const snapshot = snapshotManagedEnv();\n applyToEnv(creds);\n\n try {\n // Dynamic import so the SDK only loads when we actually need it (keeps the\n // Docker hot path lean, same reason as the provider registry).\n const { Daytona } = await import('@daytona/sdk');\n const client = new Daytona();\n await client.list();\n s.stop('Daytona credentials accepted');\n return { ok: true };\n } catch (err) {\n restoreManagedEnv(snapshot);\n const message = err instanceof Error ? err.message : String(err);\n s.stop('Daytona credentials check failed');\n if (/401|403|unauthor|forbidden|invalid/i.test(message)) {\n return { ok: false, kind: 'auth', message };\n }\n return { ok: false, kind: 'network', message };\n }\n}\n\nfunction snapshotManagedEnv(): Record<ManagedKey, string | undefined> {\n const out = {} as Record<ManagedKey, string | undefined>;\n for (const k of MANAGED_KEYS) out[k] = process.env[k];\n return out;\n}\n\nfunction restoreManagedEnv(snap: Record<ManagedKey, string | undefined>): void {\n for (const k of MANAGED_KEYS) {\n if (snap[k] === undefined) delete process.env[k];\n else process.env[k] = snap[k];\n }\n}\n\nfunction applyToEnv(creds: Credentials): void {\n // Wipe the other auth method so the SDK doesn't get confused by stale env\n // (e.g. an old JWT lingering from a previous shell export).\n for (const k of MANAGED_KEYS) delete process.env[k];\n if (creds.apiKey) process.env.DAYTONA_API_KEY = creds.apiKey;\n if (creds.jwtToken) process.env.DAYTONA_JWT_TOKEN = creds.jwtToken;\n if (creds.organizationId) process.env.DAYTONA_ORGANIZATION_ID = creds.organizationId;\n}\n\nfunction persistCredentials(creds: Credentials): void {\n // Only the provided auth method's keys are written; `writeManagedSecrets`\n // strips every managed key first, so a stale JWT is cleared when switching to\n // an API key (and vice-versa). Unrelated DAYTONA_API_URL / DAYTONA_TARGET the\n // user dropped in the file stay untouched.\n const record: Record<string, string> = {};\n if (creds.apiKey) record.DAYTONA_API_KEY = creds.apiKey;\n if (creds.jwtToken) record.DAYTONA_JWT_TOKEN = creds.jwtToken;\n if (creds.organizationId) record.DAYTONA_ORGANIZATION_ID = creds.organizationId;\n writeManagedSecrets(MANAGED_KEYS, record);\n}\n\n/**\n * Non-interactive credential set (the headless path the hub drives). Accepts\n * either `{ apiKey }` or `{ jwtToken, organizationId }`, validates against\n * Daytona (a cheap `list()`), then persists to `~/.agentbox/secrets.env`. A\n * network failure still persists (offline host isn't blocked) but reports a\n * warning label.\n */\nexport async function setDaytonaCredentials(\n fields: Record<string, string>,\n): Promise<CredSetResult> {\n const apiKey = (fields.apiKey ?? '').trim();\n const jwtToken = (fields.jwtToken ?? '').trim();\n const organizationId = (fields.organizationId ?? '').trim();\n let creds: Credentials;\n if (apiKey) {\n creds = { apiKey };\n } else if (jwtToken && organizationId) {\n creds = { jwtToken, organizationId };\n } else {\n return {\n ok: false,\n error: 'provide apiKey, or jwtToken + organizationId',\n status: { configured: false },\n };\n }\n const result = await validateCredentials(creds);\n if (!result.ok && result.kind === 'auth') {\n return {\n ok: false,\n error: `credentials rejected by Daytona: ${result.message}`,\n status: { configured: false },\n };\n }\n persistCredentials(creds);\n const label = result.ok ? (creds.apiKey ? 'key' : 'jwt') : 'key (unvalidated)';\n return { ok: true, status: { configured: true, label } };\n}\n\nfunction openDashboard(): void {\n try {\n const r = spawnSync(hostOpenCommand(), [DASHBOARD_KEYS_URL], { stdio: 'ignore' });\n if (r.status !== 0) {\n log.warn(`Could not auto-open the browser — visit ${DASHBOARD_KEYS_URL} manually.`);\n }\n } catch {\n log.warn(`Could not auto-open the browser — visit ${DASHBOARD_KEYS_URL} manually.`);\n }\n}\n\nexport function secretsPath(): string {\n return resolve(homedir(), '.agentbox', 'secrets.env');\n}\n\n/** What's currently configured. Used by `daytona login --status`. */\nexport interface DaytonaCredStatus {\n apiKey?: string;\n jwtToken?: string;\n organizationId?: string;\n source: 'env' | 'secrets.env' | 'none';\n}\n\nexport function readDaytonaCredStatus(): DaytonaCredStatus {\n // Snapshot what the shell already had before the loader runs so we can\n // distinguish env-from-shell from env-loaded-from-secrets.env.\n const shellHadKey = !!process.env.DAYTONA_API_KEY || !!process.env.DAYTONA_JWT_TOKEN;\n ensureDaytonaEnvLoaded();\n const apiKey = process.env.DAYTONA_API_KEY;\n const jwtToken = process.env.DAYTONA_JWT_TOKEN;\n const organizationId = process.env.DAYTONA_ORGANIZATION_ID;\n if (!apiKey && !jwtToken) return { source: 'none' };\n return {\n apiKey,\n jwtToken,\n organizationId,\n source: shellHadKey ? 'env' : 'secrets.env',\n };\n}\n\nexport function maskKey(value: string): string {\n if (value.length <= 8) return '*'.repeat(value.length);\n return `${value.slice(0, 4)}…${'*'.repeat(8)}${value.slice(-4)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,SAAS,eAAe;AACjC,SAAS,qBAAqB;ACF9B,SAAS,cAAAA,aAAY,oBAAoB;AACzC,SAAS,eAAe;AACxB,SAAS,WAAAC,gBAAe;ACQxB,SAAS,kBAAkB;AAC3B,SAAS,cAAAD,mBAAkB;AAC3B,SAAS,WAAAE,UAAS,WAAAD,gBAAe;AACjC,SAAS,iBAAAE,sBAAqB;ACP9B,SAAS,SAAS,wBAAAC,uBAAsB,OAAO,oBAAkC;AEMjF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;OACK;ACtBP,SAAS,iBAAiB;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ChC;AACF;AAEO,SAAS,QAAQ,OAAuB;AAC7C,MAAI,MAAM,UAAU,EAAG,QAAO,IAAI,OAAO,MAAM,MAAM;AACrD,SAAO,GAAG,MAAM,MAAM,GAAG,CAAC,CAAC,SAAI,IAAI,OAAO,CAAC,CAAC,GAAG,MAAM,MAAM,EAAE,CAAC;AAChE;","names":["existsSync","resolve","dirname","fileURLToPath","DaytonaNotFoundError","homedir","resolve","existsSync","dirname","fileURLToPath","log","DaytonaNotFoundError","Daytona"]}
@@ -3,7 +3,7 @@ import {
3
3
  loadEffectiveConfig,
4
4
  setConfigValue,
5
5
  unsetConfigValue
6
- } from "./chunk-H6A4BQMG.js";
6
+ } from "./chunk-5F5SOSDY.js";
7
7
  import {
8
8
  UserFacingError,
9
9
  claudeInstallFingerprint,
@@ -12,7 +12,7 @@ import {
12
12
  preparedStatePathFor,
13
13
  readPreparedStateRaw,
14
14
  writePreparedStateRaw
15
- } from "./chunk-3MDYQROX.js";
15
+ } from "./chunk-Y3OPQWAQ.js";
16
16
 
17
17
  // ../../packages/sandbox-digitalocean/dist/chunk-7SUT53X5.js
18
18
  import { existsSync, readFileSync } from "fs";
@@ -991,4 +991,4 @@ export {
991
991
  updatePreparedState,
992
992
  currentDigitalOceanBaseFingerprintLive
993
993
  };
994
- //# sourceMappingURL=chunk-LJMGHFLZ.js.map
994
+ //# sourceMappingURL=chunk-7PRLM3PH.js.map
File without changes
@@ -22,13 +22,13 @@ import {
22
22
  readBoxStatus,
23
23
  registerBoxWithRelay,
24
24
  syncClaudeCredentials
25
- } from "./chunk-OSPM4Q5V.js";
25
+ } from "./chunk-VZC5J44U.js";
26
26
  import {
27
27
  hashProjectPath,
28
28
  loadEffectiveConfig,
29
29
  projectDirSegment,
30
30
  sanitizeMnemonic
31
- } from "./chunk-H6A4BQMG.js";
31
+ } from "./chunk-5F5SOSDY.js";
32
32
  import {
33
33
  AGENT_SYNC_SPECS,
34
34
  BOX_DYNAMIC_SYNC_MANIFEST,
@@ -66,6 +66,7 @@ import {
66
66
  resolveSyncTopology,
67
67
  resyncWorkspace,
68
68
  shouldAcceptCredentialUpdate,
69
+ stageAllAgentStatic,
69
70
  stageClaudeCredentialsForUpload,
70
71
  stageClaudeJsonOnlyForUpload,
71
72
  stageClaudeStaticForUpload,
@@ -76,7 +77,7 @@ import {
76
77
  stageOpencodeStateForUpload,
77
78
  stageOpencodeStaticForUpload,
78
79
  writeCredentialBackup
79
- } from "./chunk-3MDYQROX.js";
80
+ } from "./chunk-Y3OPQWAQ.js";
80
81
 
81
82
  // ../../packages/sandbox-cloud/dist/index.js
82
83
  import { basename as basename2, resolve } from "path";
@@ -417,6 +418,12 @@ async function ensureAgentVolumesForCloud(backend, opts = {}) {
417
418
  const log = opts.onLog ?? (() => {
418
419
  });
419
420
  const allAgents = AGENT_SPECS.map((s) => s.kind);
421
+ if (opts.volumesUsable === false) {
422
+ log(
423
+ `cloud backend '${backend.name}' cannot mount volumes for this sandbox class \u2014 agent credentials seeded per-create only`
424
+ );
425
+ return { mounts: [], env: buildForwardedEnv(allAgents), agents: allAgents };
426
+ }
420
427
  if (typeof backend.ensureVolume !== "function") {
421
428
  log(
422
429
  `cloud backend '${backend.name}' has no volume primitive \u2014 agent credentials seeded per-create only`
@@ -2079,7 +2086,11 @@ function createCloudProvider(backend, opts = {}) {
2079
2086
  if (!sandboxId) {
2080
2087
  throw new Error(`cloud box ${box.name} has no sandboxId \u2014 record is malformed`);
2081
2088
  }
2082
- return { sandboxId, inbound: box.cloud?.inbound };
2089
+ return {
2090
+ sandboxId,
2091
+ inbound: box.cloud?.inbound,
2092
+ sandboxClass: box.cloud?.sandboxClass
2093
+ };
2083
2094
  }
2084
2095
  function mintBox(req) {
2085
2096
  const id = generateBoxId();
@@ -2271,7 +2282,7 @@ function createCloudProvider(backend, opts = {}) {
2271
2282
  const image = opts.provisionImage ? await opts.provisionImage(req) : req.image ?? FALLBACK_IMAGE;
2272
2283
  const resources = opts.defaultResources ?? { cpu: 2, memory: 4, disk: 8 };
2273
2284
  const timeoutOverride = req.providerOptions?.["timeoutMs"];
2274
- const timeoutMs = typeof timeoutOverride === "number" && timeoutOverride > 0 ? timeoutOverride : void 0;
2285
+ const timeoutMs = typeof timeoutOverride === "number" && timeoutOverride >= 0 ? timeoutOverride : void 0;
2275
2286
  const networkPolicyOpt = req.providerOptions?.["networkPolicy"];
2276
2287
  const networkPolicy = typeof networkPolicyOpt === "string" && networkPolicyOpt.trim() !== "" ? networkPolicyOpt.trim() : void 0;
2277
2288
  const sizeOpt = req.providerOptions?.["size"];
@@ -2282,6 +2293,8 @@ function createCloudProvider(backend, opts = {}) {
2282
2293
  const inbound = typeof inboundOpt === "string" && inboundOpt.trim() !== "" ? inboundOpt.trim() : void 0;
2283
2294
  const projectOpt = req.providerOptions?.["project"];
2284
2295
  const project = typeof projectOpt === "string" && projectOpt.trim() !== "" ? projectOpt.trim() : void 0;
2296
+ const classOpt = req.providerOptions?.["sandboxClass"];
2297
+ const sandboxClass = typeof classOpt === "string" && classOpt.trim() !== "" ? classOpt.trim() : void 0;
2285
2298
  const relayToken = generateRelayToken();
2286
2299
  const bridgeToken = generateRelayToken();
2287
2300
  try {
@@ -2309,7 +2322,12 @@ function createCloudProvider(backend, opts = {}) {
2309
2322
  );
2310
2323
  }
2311
2324
  }
2312
- const agentVolumes = await ensureAgentVolumesForCloud(backend, { onLog: log });
2325
+ const agentVolumes = await ensureAgentVolumesForCloud(backend, {
2326
+ onLog: log,
2327
+ // Daytona's linux-vm class accepts volume mounts and never honors them
2328
+ // (see ensureAgentVolumesForCloud) — take the per-create upload path.
2329
+ volumesUsable: sandboxClass !== "linux-vm"
2330
+ });
2313
2331
  const exposeServicePorts = await readExposedServicePorts(req.workspacePath);
2314
2332
  const credentialSyncOff = (req.credentialSync ?? (await loadEffectiveConfig(req.projectRoot ?? req.workspacePath)).effective.box.credentialSync) === false;
2315
2333
  const provisionEnv = {
@@ -2339,6 +2357,7 @@ function createCloudProvider(backend, opts = {}) {
2339
2357
  location,
2340
2358
  project,
2341
2359
  inbound,
2360
+ sandboxClass,
2342
2361
  timeoutMs,
2343
2362
  exposePorts: exposeServicePorts,
2344
2363
  networkPolicy,
@@ -2637,6 +2656,10 @@ function createCloudProvider(backend, opts = {}) {
2637
2656
  // Inbound-access policy the backend applied to the per-box firewall
2638
2657
  // (VPS providers). Persisted so drift re-syncs preserve the whitelist.
2639
2658
  inbound: handle.inbound,
2659
+ // Daytona sandbox class, read back from the class of the snapshot the
2660
+ // box actually booted from (not from config, which can disagree).
2661
+ // pause() branches on it: a VM pauses, a container archives.
2662
+ sandboxClass: handle.sandboxClass,
2640
2663
  // Only host-seeded boxes share a fork base with the host, so only
2641
2664
  // they can be resynced back to the host tip on session start (7.5).
2642
2665
  // inBoxClone / plane boxes clone from a leased URL — left unset.
@@ -2814,12 +2837,28 @@ function createCloudProvider(backend, opts = {}) {
2814
2837
  const handle = handleFor(box);
2815
2838
  const baseArgv = await backend.attachArgv(handle);
2816
2839
  const inner = renderInnerCommand(kind, opts2);
2817
- const argv = opts2?.detached ? [...baseArgv.slice(1), inner] : [...baseArgv.slice(1), "-t", inner];
2840
+ const viaStdin = backend.attachExecLacksTty === true && !opts2?.detached && kind !== "logs";
2841
+ const scriptPath = viaStdin ? attachScriptPath(opts2?.sessionName ?? kind) : "";
2842
+ if (viaStdin) {
2843
+ const b64 = Buffer.from(inner, "utf8").toString("base64");
2844
+ await backend.exec(
2845
+ handle,
2846
+ `printf %s '${b64}' | base64 -d > ${scriptPath} && chmod 700 ${scriptPath}`
2847
+ );
2848
+ }
2849
+ const argv = opts2?.detached ? [...baseArgv.slice(1), inner] : viaStdin ? [...baseArgv.slice(1)] : [...baseArgv.slice(1), "-t", inner];
2818
2850
  const fullArgv = [baseArgv[0], ...argv];
2819
2851
  const cleanup = backend.revokeAttachToken ? async () => {
2820
2852
  await backend.revokeAttachToken(handle, baseArgv);
2821
2853
  } : void 0;
2822
- return { argv: fullArgv, cleanup };
2854
+ return {
2855
+ argv: fullArgv,
2856
+ // `exec` so the script replaces the login shell: the user never lands
2857
+ // back on a prompt when they detach from tmux.
2858
+ ...viaStdin ? { initialInput: `exec bash ${scriptPath}
2859
+ ` } : {},
2860
+ cleanup
2861
+ };
2823
2862
  },
2824
2863
  async uploadPath(box, hostSrcs, boxDst, exclude) {
2825
2864
  return uploadToCloudBox(backend, handleFor(box), hostSrcs, boxDst, exclude);
@@ -2985,6 +3024,10 @@ function hostTermForCloud() {
2985
3024
  const t = process.env["TERM"];
2986
3025
  return t && /^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(t) ? t : "xterm-256color";
2987
3026
  }
3027
+ function attachScriptPath(sessionName) {
3028
+ const safe = sessionName.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 40) || "attach";
3029
+ return `/tmp/agentbox-attach-${safe}.sh`;
3030
+ }
2988
3031
  function renderInnerCommand(kind, opts) {
2989
3032
  const sessionName = opts?.sessionName ?? defaultSessionName(kind);
2990
3033
  const fallback = opts?.command ?? defaultCommand(kind, opts);
@@ -3036,6 +3079,62 @@ function defaultCommand(kind, opts) {
3036
3079
  function shellSingle(s) {
3037
3080
  return "'" + s.replace(/'/g, "'\\''") + "'";
3038
3081
  }
3082
+ function remoteTarFor(kind) {
3083
+ return `/tmp/agentbox-seed-${kind}.tar.gz`;
3084
+ }
3085
+ var REMOTE_CLAUDE_MD = "/tmp/agentbox-custom-CLAUDE.md";
3086
+ function buildAgentStaticSeedCommands(usable, opts = {}) {
3087
+ const cmds = [];
3088
+ if (opts.claudeMdOverlay) {
3089
+ cmds.push(
3090
+ `sudo -n mkdir -p /etc/claude-code && sudo -n install -m 0644 ${REMOTE_CLAUDE_MD} /etc/claude-code/CLAUDE.md && rm -f ${REMOTE_CLAUDE_MD}`
3091
+ );
3092
+ }
3093
+ for (const s of usable) {
3094
+ cmds.push(
3095
+ `mkdir -p ${s.extractDir} && tar -xzf ${remoteTarFor(s.kind)} -C ${s.extractDir} --no-same-permissions --no-same-owner -m && rm -f ${remoteTarFor(s.kind)}`
3096
+ );
3097
+ }
3098
+ if (usable.length > 0) {
3099
+ cmds.push(
3100
+ "sudo -n chown -R vscode:vscode /home/vscode/.claude /home/vscode/.codex /home/vscode/.local && ( [ -d /home/vscode/.agents ] && sudo -n chown -R vscode:vscode /home/vscode/.agents || true )"
3101
+ );
3102
+ }
3103
+ return cmds;
3104
+ }
3105
+ async function seedAgentStaticIntoCloudBox(backend, handle, opts = {}) {
3106
+ const log = opts.onLog ?? (() => {
3107
+ });
3108
+ const stages = await stageAllAgentStatic({ hostWorkspace: opts.hostWorkspace });
3109
+ try {
3110
+ for (const s of stages) {
3111
+ for (const w of s.staged.warnings) log(w);
3112
+ }
3113
+ const usable = stages.filter((s) => s.staged.tarballPath !== null);
3114
+ if (opts.claudeMdOverlay) {
3115
+ await backend.uploadFile(handle, opts.claudeMdOverlay, REMOTE_CLAUDE_MD);
3116
+ }
3117
+ for (const s of usable) {
3118
+ await backend.uploadFile(handle, s.staged.tarballPath, remoteTarFor(s.kind));
3119
+ }
3120
+ const cmds = buildAgentStaticSeedCommands(usable, {
3121
+ claudeMdOverlay: Boolean(opts.claudeMdOverlay)
3122
+ });
3123
+ for (const cmd of cmds) {
3124
+ const r = await backend.exec(handle, cmd);
3125
+ if (r.exitCode !== 0) {
3126
+ throw new Error(
3127
+ `agent-static seed failed (exit ${String(r.exitCode)}): ${cmd}
3128
+ ${r.stdout}${r.stderr}`
3129
+ );
3130
+ }
3131
+ }
3132
+ log(`seeded agent static config: ${usable.map((s) => s.kind).join(", ") || "(none)"}`);
3133
+ return { seeded: usable.map((s) => s.kind) };
3134
+ } finally {
3135
+ await Promise.all(stages.map((s) => s.staged.cleanup()));
3136
+ }
3137
+ }
3039
3138
  async function openWebAppOnVncScreen(box, provider) {
3040
3139
  const persisted = await readBoxStatus(box);
3041
3140
  const hasWebService = persisted?.services.some((s) => s.expose) ?? false;
@@ -3061,6 +3160,7 @@ export {
3061
3160
  ensureAgentVolumesForCloud,
3062
3161
  seedAgentVolumesIfFresh,
3063
3162
  agentSpecsForCloud,
3163
+ cloudSnapshotName,
3064
3164
  listCloudBackendDirs,
3065
3165
  listCloudCheckpoints,
3066
3166
  listAllCloudCheckpoints,
@@ -3073,6 +3173,7 @@ export {
3073
3173
  createCloudProvider,
3074
3174
  hostTermForCloud,
3075
3175
  renderInnerCommand,
3176
+ seedAgentStaticIntoCloudBox,
3076
3177
  openWebAppOnVncScreen
3077
3178
  };
3078
- //# sourceMappingURL=chunk-4HPLS5HJ.js.map
3179
+ //# sourceMappingURL=chunk-GHFIKSBJ.js.map