@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.
- package/CHANGELOG.md +24 -0
- package/dist/{_cloud-attach-EUO2OL7W.js → _cloud-attach-7WVNYNJI.js} +6 -6
- package/dist/{chunk-2JHPGPLE.js → chunk-5I7IFACI.js} +2 -2
- package/dist/{chunk-AC3HU25W.js → chunk-5NVHJS7D.js} +2 -2
- package/dist/{chunk-PFEBKXFD.js → chunk-6UCHNX75.js} +19 -12
- package/dist/{chunk-PFEBKXFD.js.map → chunk-6UCHNX75.js.map} +1 -1
- package/dist/{chunk-UEEW5TW7.js → chunk-F77AZT2M.js} +2 -2
- package/dist/{chunk-UTOC2NHC.js → chunk-FCMBVJFQ.js} +2 -2
- package/dist/{chunk-73D2HKA3.js → chunk-HLBK5ZR6.js} +5 -5
- package/dist/{chunk-4KYP775X.js → chunk-JLVUNDUB.js} +26 -7
- package/dist/chunk-JLVUNDUB.js.map +1 -0
- package/dist/{chunk-BIKWXLX7.js → chunk-JTYWZJIU.js} +3 -3
- package/dist/{chunk-7LC5IG5K.js → chunk-LEVYTABB.js} +3 -3
- package/dist/{chunk-FEFLAITR.js → chunk-MS4NWRXN.js} +2 -2
- package/dist/{chunk-WJUKN4L4.js → chunk-N6EBPKTJ.js} +45 -3
- package/dist/chunk-N6EBPKTJ.js.map +1 -0
- package/dist/{chunk-4NUETVTR.js → chunk-OUOV4OM2.js} +7 -7
- package/dist/{chunk-I7BSBUPC.js → chunk-P5A6MT75.js} +7 -7
- package/dist/{chunk-FELVUIIM.js → chunk-RXH634SC.js} +2 -2
- package/dist/{chunk-QDU7YDME.js → chunk-SXXN7JOC.js} +18 -18
- package/dist/{chunk-B4YFG5TB.js → chunk-TDW2T3HR.js} +4 -4
- package/dist/{chunk-S32GHLVU.js → chunk-TPHSVKMX.js} +2 -2
- package/dist/{chunk-53OTEDBS.js → chunk-ZCHWZYIN.js} +3 -3
- package/dist/cloud-backends.js +3 -3
- package/dist/{control-plane-YQFX2ILX.js → control-plane-TOFT56CT.js} +10 -10
- package/dist/{cp-hub-upload-RMJ3XJ65.js → cp-hub-upload-OTBR5SL3.js} +2 -2
- package/dist/{deploy-hetzner-EECQ4JCM.js → deploy-hetzner-EE5CYX4N.js} +4 -4
- package/dist/{dist-Q4UDCSZQ.js → dist-7HSAWFRN.js} +3 -3
- package/dist/{dist-XUOHE22G.js → dist-BVZBXQ2Y.js} +4 -4
- package/dist/{dist-NFF2KEMB.js → dist-GMIBT6IK.js} +43 -19
- package/dist/{dist-NFF2KEMB.js.map → dist-GMIBT6IK.js.map} +1 -1
- package/dist/{dist-NTUHJOK3.js → dist-JSEXGLYK.js} +3 -3
- package/dist/{dist-TXFTYNNE.js → dist-RWFKW4IU.js} +2 -2
- package/dist/{dist-Z2TPC3EN.js → dist-XV77P3RW.js} +3 -3
- package/dist/{dist-E5EXDZG4.js → dist-Y2GCMA6N.js} +2 -2
- package/dist/{hub-3HPYOV5O.js → hub-53E6EFZB.js} +11 -11
- package/dist/{hub-docker-target-ZKAWXVPH.js → hub-docker-target-CS5XHSSA.js} +7 -7
- package/dist/index.js +47 -39
- package/dist/index.js.map +1 -1
- package/dist/{prepare-KIVDQRMN.js → prepare-VTLE7RCJ.js} +15 -15
- package/dist/{prepared-custody-EFSOOAIQ.js → prepared-custody-ATP6GQGW.js} +11 -11
- package/dist/{publish-credentials-F2A5OVCO.js → publish-credentials-NAWOHOLK.js} +3 -3
- package/dist/{registry-O3X2CDDU.js → registry-5CPAQ2KN.js} +3 -3
- package/dist/{remote-docker-share-QDCBM5UM.js → remote-docker-share-XBV76ZAZ.js} +4 -4
- package/dist/{tool-grant-push-6ISDIJKH.js → tool-grant-push-5GJYMC7C.js} +2 -2
- package/package.json +1 -1
- package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
- package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
- package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
- package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
- package/runtime/hub/apps/hub/{chunk-BI4MPGQT.js → chunk-CTNPQ75B.js} +7 -7
- package/runtime/hub/apps/hub/{chunk-2WB3A5IN.js → chunk-DJPQLZ5Y.js} +1 -1
- package/runtime/hub/apps/hub/{chunk-RPPOFMPA.js → chunk-GUKVXSIY.js} +25 -6
- package/runtime/hub/apps/hub/{dist-F547YSBE.js → dist-2G5INR3G.js} +2 -2
- package/runtime/hub/apps/hub/{dist-YB3Y2XDK.js → dist-CIB4ZPJW.js} +85 -19
- package/runtime/hub/apps/hub/{dist-W5SGEJLA.js → dist-PI5ZAQGG.js} +1 -1
- package/runtime/hub/apps/hub/{dist-4F6XEJHK.js → dist-VDPNQEZ7.js} +2 -2
- package/runtime/hub/apps/hub/{dist-FEHV4PC7.js → dist-VZM32WR4.js} +1 -1
- package/runtime/hub/apps/hub/{dist-P7NT6VLK.js → dist-Y3LGOZ56.js} +1 -1
- package/runtime/hub/apps/hub/{dist-A3JOKKYG.js → dist-ZOJYJJ26.js} +1 -1
- package/runtime/hub/apps/hub/{hub-worker-I5QBLSRU.js → hub-worker-YQCQKCXS.js} +3 -3
- package/runtime/hub/apps/hub/server.js +8 -8
- package/runtime/hub/apps/hub/tsconfig.tsbuildinfo +1 -1
- package/dist/chunk-4KYP775X.js.map +0 -1
- package/dist/chunk-WJUKN4L4.js.map +0 -1
- /package/dist/{_cloud-attach-EUO2OL7W.js.map → _cloud-attach-7WVNYNJI.js.map} +0 -0
- /package/dist/{chunk-2JHPGPLE.js.map → chunk-5I7IFACI.js.map} +0 -0
- /package/dist/{chunk-AC3HU25W.js.map → chunk-5NVHJS7D.js.map} +0 -0
- /package/dist/{chunk-UEEW5TW7.js.map → chunk-F77AZT2M.js.map} +0 -0
- /package/dist/{chunk-UTOC2NHC.js.map → chunk-FCMBVJFQ.js.map} +0 -0
- /package/dist/{chunk-73D2HKA3.js.map → chunk-HLBK5ZR6.js.map} +0 -0
- /package/dist/{chunk-BIKWXLX7.js.map → chunk-JTYWZJIU.js.map} +0 -0
- /package/dist/{chunk-7LC5IG5K.js.map → chunk-LEVYTABB.js.map} +0 -0
- /package/dist/{chunk-FEFLAITR.js.map → chunk-MS4NWRXN.js.map} +0 -0
- /package/dist/{chunk-4NUETVTR.js.map → chunk-OUOV4OM2.js.map} +0 -0
- /package/dist/{chunk-I7BSBUPC.js.map → chunk-P5A6MT75.js.map} +0 -0
- /package/dist/{chunk-FELVUIIM.js.map → chunk-RXH634SC.js.map} +0 -0
- /package/dist/{chunk-QDU7YDME.js.map → chunk-SXXN7JOC.js.map} +0 -0
- /package/dist/{chunk-B4YFG5TB.js.map → chunk-TDW2T3HR.js.map} +0 -0
- /package/dist/{chunk-S32GHLVU.js.map → chunk-TPHSVKMX.js.map} +0 -0
- /package/dist/{chunk-53OTEDBS.js.map → chunk-ZCHWZYIN.js.map} +0 -0
- /package/dist/{control-plane-YQFX2ILX.js.map → control-plane-TOFT56CT.js.map} +0 -0
- /package/dist/{cp-hub-upload-RMJ3XJ65.js.map → cp-hub-upload-OTBR5SL3.js.map} +0 -0
- /package/dist/{deploy-hetzner-EECQ4JCM.js.map → deploy-hetzner-EE5CYX4N.js.map} +0 -0
- /package/dist/{dist-NTUHJOK3.js.map → dist-7HSAWFRN.js.map} +0 -0
- /package/dist/{dist-Q4UDCSZQ.js.map → dist-BVZBXQ2Y.js.map} +0 -0
- /package/dist/{dist-TXFTYNNE.js.map → dist-JSEXGLYK.js.map} +0 -0
- /package/dist/{dist-XUOHE22G.js.map → dist-RWFKW4IU.js.map} +0 -0
- /package/dist/{dist-Z2TPC3EN.js.map → dist-XV77P3RW.js.map} +0 -0
- /package/dist/{dist-E5EXDZG4.js.map → dist-Y2GCMA6N.js.map} +0 -0
- /package/dist/{hub-3HPYOV5O.js.map → hub-53E6EFZB.js.map} +0 -0
- /package/dist/{hub-docker-target-ZKAWXVPH.js.map → hub-docker-target-CS5XHSSA.js.map} +0 -0
- /package/dist/{prepare-KIVDQRMN.js.map → prepare-VTLE7RCJ.js.map} +0 -0
- /package/dist/{prepared-custody-EFSOOAIQ.js.map → prepared-custody-ATP6GQGW.js.map} +0 -0
- /package/dist/{publish-credentials-F2A5OVCO.js.map → publish-credentials-NAWOHOLK.js.map} +0 -0
- /package/dist/{registry-O3X2CDDU.js.map → registry-5CPAQ2KN.js.map} +0 -0
- /package/dist/{remote-docker-share-QDCBM5UM.js.map → remote-docker-share-XBV76ZAZ.js.map} +0 -0
- /package/dist/{tool-grant-push-6ISDIJKH.js.map → tool-grant-push-5GJYMC7C.js.map} +0 -0
- /package/runtime/hub/apps/hub/.next/static/{nDHi_1342DzyGDC14ocQo → 2P6VYtaUNxtdBvOVMolM-}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{nDHi_1342DzyGDC14ocQo → 2P6VYtaUNxtdBvOVMolM-}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{nDHi_1342DzyGDC14ocQo → 2P6VYtaUNxtdBvOVMolM-}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/sandbox-daytona/src/index.ts","../../../packages/sandbox-daytona/src/checkpoint.ts","../../../packages/sandbox-daytona/src/prepare.ts","../../../packages/sandbox-daytona/src/prepare-vm.ts","../../../packages/sandbox-daytona/src/provider-module.ts","../../../packages/sandbox-daytona/src/status.ts"],"sourcesContent":["/**\n * The Daytona Cloud sandbox provider. A thin `CloudBackend` over\n * `@daytona/sdk`, composed via `@agentbox/sandbox-cloud`'s `createCloudProvider`\n * for everything provider-agnostic (workspace seeding, ctl launch, state).\n */\n\nimport type { Provider } from '@agentbox/core';\nimport type { ProviderModule } from '@agentbox/sandbox-core';\nimport { createCloudProvider } from '@agentbox/sandbox-cloud';\nimport { DAYTONA_DEFAULT_RESOURCES, daytonaBackend, DEFAULT_BOX_IMAGE_REF } from './backend.js';\nimport { makeDaytonaCheckpoint } from './checkpoint.js';\nimport { prepareDaytona } from './prepare.js';\nimport { currentDaytonaBaseFingerprintLive } from './prepared-state.js';\nimport { ensureDaytonaCredentials, setDaytonaCredentials } from './credentials.js';\nimport { doctorChecks, readCredStatusSummary, sizeIgnoredReason } from './provider-module.js';\n\nconst cloudProvider = createCloudProvider(daytonaBackend, {\n defaultResources: { ...DAYTONA_DEFAULT_RESOURCES },\n});\n\nexport const daytonaProvider: Provider = {\n ...cloudProvider,\n prepare: prepareDaytona,\n // Overrides the generic cloud checkpoint: a Daytona cold snapshot needs the\n // sandbox stopped, which kills the in-box daemons, so the capture has to\n // reconnect the box afterwards. See `makeDaytonaCheckpoint`.\n checkpoint: makeDaytonaCheckpoint(cloudProvider),\n baseFingerprint: (claudeInstall) => currentDaytonaBaseFingerprintLive(claudeInstall),\n};\n\n/** Uniform surface the CLI provider loader resolves this package through. */\nexport const providerModule: ProviderModule = {\n provider: daytonaProvider,\n backend: daytonaBackend,\n ensureCredentials: ensureDaytonaCredentials,\n readCredStatus: readCredStatusSummary,\n setCredentials: setDaytonaCredentials,\n currentBaseFingerprintLive: (claudeInstall) => currentDaytonaBaseFingerprintLive(claudeInstall),\n sizeIgnoredReason,\n doctorChecks,\n};\n\nexport { DAYTONA_DEFAULT_RESOURCES, daytonaBackend, DEFAULT_BOX_IMAGE_REF };\nexport { resolveDockerfileContext, type DockerfileContext } from './dockerfile-context.js';\nexport { ensureDaytonaEnvLoaded } from './env-loader.js';\nexport { currentDaytonaBaseFingerprintLive } from './prepared-state.js';\n// Called by the CLI provider registry to gate first-run interactive setup.\n// Plain async function — no commander surface — so adding it here doesn't\n// pull commander/clack into consumers' type graphs. The full CLI command\n// lives at the `./cli` subpath export.\nexport { ensureDaytonaCredentials, setDaytonaCredentials } from './credentials.js';\nexport type { EnsureDaytonaCredentialsOptions } from './credentials.js';\nexport {\n getDaytonaStatus,\n type DaytonaStatus,\n type DaytonaSnapshotSummary,\n type DaytonaVolumeSummary,\n} from './status.js';\n","/**\n * Daytona cloud checkpoints.\n *\n * Overrides the generic cloud checkpoint (`makeCloudCheckpoint`) because\n * Daytona's capture has two properties the generic one doesn't model:\n *\n * 1. **A cold snapshot requires the sandbox STOPPED, and Daytona will not stop\n * it for you.** (The hot, filesystem+memory variant needs `includeMemory`,\n * which the published TS SDK silently drops — so it's out of reach until\n * upstream fixes the wrapper.) So we stop, capture, and start again. The\n * stop kills the in-box `ctl` daemon, dockerd, VNC and the agent's tmux\n * session, so the box must be *reconnected* afterwards or the user is left\n * with a running sandbox whose services are all dead.\n *\n * 2. **A snapshot name must never be reused.** Recreating a snapshot under a\n * recently-deleted name yields one that reports `active` but cannot boot\n * (\"Sandbox failed to start: internal error\") — Daytona's delete is async\n * and racing it corrupts the new snapshot. `agentbox checkpoint rm <name>`\n * followed by a re-create with the same name would walk straight into that,\n * so the Daytona-side name carries a nonce while the user-facing checkpoint\n * name stays whatever they typed. The manifest maps one to the other.\n */\nimport type { BoxRecord, Provider, ProviderCheckpoint } from '@agentbox/core';\nimport {\n cloudSnapshotName,\n currentCloudBaseFingerprint,\n listCloudCheckpoints,\n removeCloudCheckpointDir,\n resolveCloudCheckpoint,\n writeCloudCheckpointManifest,\n} from '@agentbox/sandbox-cloud';\nimport { readCliStamp } from '@agentbox/sandbox-core';\nimport { daytonaBackend } from './backend.js';\n\nconst BACKEND_NAME = 'daytona';\n\nexport function makeDaytonaCheckpoint(cloudProvider: Provider): ProviderCheckpoint {\n return {\n async create(box: BoxRecord, name: string) {\n if (!box.projectRoot) {\n throw new Error(\n 'cloud checkpoint requires the box to have a project root (run `agentbox checkpoint` from inside the project)',\n );\n }\n const sandboxId = box.cloud?.sandboxId;\n if (!sandboxId) {\n throw new Error(`daytona box ${box.name} has no sandboxId — record is malformed`);\n }\n const handle = { sandboxId, sandboxClass: box.cloud?.sandboxClass };\n // Unique per capture — see the name-reuse note above.\n const snapshotName = `${cloudSnapshotName(box.projectRoot, name)}-${Math.floor(Date.now() / 1000).toString(36)}`;\n\n await daytonaBackend.createSnapshot?.(handle, snapshotName);\n\n // The capture stopped and restarted the sandbox, so everything the box was\n // running is gone. `reconnect` re-runs the bootstrap (ctl, dockerd, VNC,\n // preview URLs) — without it the box looks up but answers nothing.\n await cloudProvider.reconnect(box);\n\n const info = await writeCloudCheckpointManifest(box.projectRoot, BACKEND_NAME, name, {\n snapshotName,\n sourceBoxId: box.id,\n sourceBoxName: box.name,\n baseProvider: BACKEND_NAME,\n baseFingerprint: currentCloudBaseFingerprint(BACKEND_NAME),\n cliVersion: readCliStamp().cliVersion,\n });\n return { ref: info.name };\n },\n\n async list(projectRoot: string) {\n const entries = await listCloudCheckpoints(projectRoot, BACKEND_NAME);\n return entries.map((e) => ({ ref: e.name, createdAt: e.manifest.createdAt }));\n },\n\n async remove(projectRoot: string, ref: string) {\n const entry = await resolveCloudCheckpoint(projectRoot, BACKEND_NAME, ref);\n if (!entry) return;\n try {\n await daytonaBackend.deleteSnapshot?.(entry.manifest.snapshotName);\n } catch {\n // Best-effort: drop the local manifest even when the remote delete fails,\n // so the user isn't left holding a pointer to nothing.\n }\n await removeCloudCheckpointDir(projectRoot, BACKEND_NAME, ref);\n },\n };\n}\n","/**\n * Daytona-side implementation of the `Provider.prepare` hook (`agentbox\n * prepare --provider daytona`). One-time, user-triggered:\n *\n * 1. Stage filtered tarballs of the host's `~/.claude`, `~/.codex`, and\n * `~/.local/share/opencode` static config (no auth tokens — those go on\n * the per-org `agentbox-credentials` volume at create time).\n * 2. Build a layered Daytona `Image`: start from `Dockerfile.box`, then\n * `.addLocalFile()` each staged tarball + `.runCommands()` to extract\n * them into the right paths inside the image.\n * 3. Call `daytona.snapshot.create({ name, image }, { onLogs })` — Daytona\n * runs the build server-side, registers the result as an org-scoped\n * named snapshot, and returns when it's `active`.\n *\n * Replaces the old `agentbox daytona publish-snapshot` flow that\n * provisioned a sandbox + ran an in-sandbox bake + called the broken\n * `_experimental_createSnapshot`. The new path never provisions a sandbox.\n *\n * Source of truth for the public API:\n * https://www.daytona.io/docs/en/snapshots/\n */\n\nimport { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { Image } from '@daytona/sdk';\nimport type { PrepareOptions, PrepareResult } from '@agentbox/core';\nimport { DAYTONA_VM_REGION, type DaytonaSandboxClass } from '@agentbox/config';\nimport {\n claudeInstallFingerprint,\n stageAllAgentStatic,\n type AgentStaticStage,\n} from '@agentbox/sandbox-core';\nimport {\n DAYTONA_DEFAULT_RESOURCES,\n daytonaBackend,\n getClient,\n parseDaytonaSize,\n} from './backend.js';\nimport { resolveDaytonaCustomClaudeMd, resolveDockerfileContext } from './dockerfile-context.js';\nimport { ensureDaytonaEnvLoaded } from './env-loader.js';\nimport {\n bakeDaytonaVmBase,\n deleteSnapshotQuietly,\n VmBaseImageUnavailableError,\n} from './prepare-vm.js';\nimport {\n computeDaytonaContextFingerprint,\n computeDockerBaseSha,\n preparedMatches,\n readPreparedDaytonaState,\n writePreparedDaytonaState,\n} from './prepared-state.js';\n\n/**\n * Default snapshot name. Keyed on the first 12 chars of the build-context\n * fingerprint so identical content produces the same snapshot name across\n * machines / CLI runs (idempotent): if the named snapshot already exists\n * on Daytona, prepare can short-circuit without uploading the build\n * context again. Falls back to a timestamp when fingerprinting fails\n * (partial dev rebuild).\n */\nexport function defaultSnapshotName(\n fingerprint: string | null,\n sizeKey?: string,\n sandboxClass?: DaytonaSandboxClass,\n): string {\n // The size suffix keeps re-sized bakes from colliding on one name, so a\n // `--size 2-4-8` snapshot doesn't overwrite the `4-8-20` one. Same for the\n // class: a VM and a container snapshot of the same context are different\n // artifacts and cannot substitute for each other. Container stays unsuffixed\n // so existing snapshot names keep resolving.\n const suffix = `${sizeKey ? `-${sizeKey}` : ''}${sandboxClass === 'linux-vm' ? '-vm' : ''}`;\n if (fingerprint) return `agentbox-base-${fingerprint.slice(0, 12)}${suffix}`;\n return `agentbox-base-${Math.floor(Date.now() / 1000).toString()}${suffix}`;\n}\n\n/**\n * Daytona build paths for a staged tool. The tarball is copied into the seed\n * build-context dir under `contextRel` (a RELATIVE name — the Daytona builder\n * only resolves COPY sources that map to a relative archive entry; an absolute\n * `addLocalFile` COPY silently fails to land), then COPYed to `remoteTar`.\n */\nfunction daytonaSeedPaths(kind: AgentStaticStage['kind']): {\n contextRel: string;\n remoteTar: string;\n} {\n return {\n contextRel: `agentbox-seed-${kind}.tar.gz`,\n remoteTar: `/tmp/agentbox-seed-${kind}.tar.gz`,\n };\n}\n\n/** Relative name the daytona CLAUDE.md overlay is staged under in the seed context dir. */\nconst DAYTONA_CLAUDE_MD_REL = 'agentbox-custom-CLAUDE.md';\n\n/**\n * Build the appended Dockerfile commands for the seed bake. Every `COPY` source\n * is a RELATIVE name resolved against the seed build-context dir — the Daytona\n * builder drops absolute-source COPYs (they archive to a stripped relative entry\n * that the absolute source can't reference), so relative names are mandatory.\n * Runs as root (COPY drops files root-owned; chown -R + /etc/claude-code need\n * root), then restores `USER vscode` so the image keeps its default-user invariant.\n * Pure + exported for the regression test.\n */\nexport function buildDaytonaSeedCommands(\n usable: ReadonlyArray<Pick<AgentStaticStage, 'kind' | 'extractDir'>>,\n): string[] {\n const cmds: string[] = [\n 'USER root',\n `COPY ${DAYTONA_CLAUDE_MD_REL} /tmp/agentbox-custom-CLAUDE.md`,\n ...usable.map(\n (s) => `COPY ${daytonaSeedPaths(s.kind).contextRel} ${daytonaSeedPaths(s.kind).remoteTar}`,\n ),\n 'RUN install -m 0644 /tmp/agentbox-custom-CLAUDE.md /etc/claude-code/CLAUDE.md && rm -f /tmp/agentbox-custom-CLAUDE.md',\n ...usable.map(\n (s) =>\n `RUN mkdir -p ${s.extractDir} && tar -xzf ${daytonaSeedPaths(s.kind).remoteTar} -C ${s.extractDir} --no-same-permissions --no-same-owner -m`,\n ),\n ];\n if (usable.length > 0) {\n // Own the extracted trees as the box user, then drop the staging tarballs.\n // ~/.agents is only present when the host had one (skills dir); guard it.\n cmds.push(\n 'RUN chown -R vscode:vscode /home/vscode/.claude /home/vscode/.codex /home/vscode/.local' +\n ' && ( [ -d /home/vscode/.agents ] && chown -R vscode:vscode /home/vscode/.agents || true )' +\n ' && rm -f /tmp/agentbox-seed-*.tar.gz',\n );\n }\n cmds.push('USER vscode');\n return cmds;\n}\n\n/**\n * Run `agentbox prepare --provider daytona`. Returns `{ snapshotName }` on\n * success so the CLI can pin it into the project config.\n */\nexport async function prepareDaytona(opts: PrepareOptions): Promise<PrepareResult> {\n ensureDaytonaEnvLoaded();\n const log = opts.onLog ?? (() => {});\n\n // Fingerprint the build context first so we can (a) name the snapshot\n // deterministically and (b) detect cache hits against the recorded\n // prepared state. Computed before staging so an early `null` (partial\n // dev rebuild) doesn't waste a tar staging cycle.\n const claudeInstall = opts.claudeInstall ?? 'native';\n\n // Bake-time resources. A `--size` / `box.sizeDaytona` like `4-8-20` sets the\n // snapshot's baked CPU/memory/disk (Daytona rejects resources on the create\n // snapshot path, so it MUST be set here). Normalize to a canonical\n // `cpu-memory-disk` string for the snapshot-name suffix + prepared-state so\n // `04-08-20` and `4-8-20` don't fork the cache.\n const sizeSpec = opts.size?.trim() || undefined;\n const sizeResources = sizeSpec ? parseDaytonaSize(sizeSpec) : undefined;\n if (sizeSpec && !sizeResources) {\n throw new Error(\n `invalid --size '${sizeSpec}' for daytona: expected 'cpu-memory-disk' GB, e.g. '4-8-20'.`,\n );\n }\n const sizeKey = sizeResources\n ? `${String(sizeResources.cpu)}-${String(sizeResources.memory)}-${String(sizeResources.disk)}`\n : undefined;\n\n // The class is fixed at bake time — a snapshot of one class cannot create a\n // sandbox of the other — so it belongs in the snapshot name and the cache key.\n let sandboxClass: DaytonaSandboxClass =\n opts.sandboxClass === 'container' ? 'container' : 'linux-vm';\n const rawFingerprint = await computeDaytonaContextFingerprint();\n // Fold the install mode into the sha so native↔npm are distinct cache\n // identities (`native` leaves the hash unchanged) — the snapshot name and the\n // prepared-state match both derive from it.\n const fingerprint = rawFingerprint\n ? {\n ...rawFingerprint,\n contextSha256: claudeInstallFingerprint(rawFingerprint.contextSha256, claudeInstall),\n }\n : rawFingerprint;\n // Not const: a linux-vm bake that finds no published base image downgrades to\n // container below, and must then drop the `-vm` suffix from its name.\n let snapshotName =\n opts.name ?? defaultSnapshotName(fingerprint?.contextSha256 ?? null, sizeKey, sandboxClass);\n\n const prepared = readPreparedDaytonaState();\n if (\n !opts.force &&\n fingerprint &&\n preparedMatches(prepared, fingerprint.contextSha256, sizeKey, sandboxClass)\n ) {\n // Confirm the snapshot still exists on Daytona before short-circuiting.\n // A \"yes locally, no on the server\" mismatch must rebuild.\n try {\n const existing = await getClient().snapshot.get(prepared?.base?.imageRef ?? snapshotName);\n if (existing?.name) {\n log(\n `daytona snapshot '${existing.name}' up to date ` +\n `(fingerprint ${fingerprint.contextSha256.slice(0, 12)}) — skipping rebuild ` +\n `(pass --force to override)`,\n );\n return { snapshotName: existing.name };\n }\n log(\n `recorded snapshot '${prepared?.base?.imageRef ?? snapshotName}' not found on Daytona; rebuilding`,\n );\n } catch {\n log(`recorded snapshot lookup failed; rebuilding (pass --force to silence)`);\n }\n } else if (!opts.force && fingerprint && prepared?.base?.contextSha256) {\n const bakedSize = prepared.extras?.size;\n const bakedClass = prepared.extras?.class ?? 'container';\n const sameContext = prepared.base.contextSha256 === fingerprint.contextSha256;\n if (sameContext && bakedClass !== sandboxClass) {\n log(\n `daytona sandbox class changed (was ${bakedClass}, now ${sandboxClass}); rebuilding snapshot`,\n );\n } else if (sameContext && bakedSize !== sizeKey) {\n log(\n `daytona size changed (was ${bakedSize ?? 'default'}, now ${sizeKey ?? 'default'}); ` +\n `rebuilding snapshot`,\n );\n } else {\n log(\n `daytona build context changed (was ${prepared.base.contextSha256.slice(0, 12)}, ` +\n `now ${fingerprint.contextSha256.slice(0, 12)}); rebuilding snapshot`,\n );\n }\n }\n\n const ctx = resolveDockerfileContext();\n if (!ctx) {\n throw new Error(\n 'could not locate AgentBox Dockerfile.box build context for the Daytona snapshot. ' +\n 'Set AGENTBOX_DOCKER_CONTEXT to the directory containing Dockerfile.box.',\n );\n }\n\n const daytonaClaudeMd = resolveDaytonaCustomClaudeMd();\n if (!daytonaClaudeMd) {\n throw new Error(\n 'could not locate packages/sandbox-daytona/scripts/custom-system-CLAUDE.md ' +\n '(or its staged runtime/daytona/ copy). Ensure `pnpm -w build` ran so the ' +\n 'CLI staging populated runtime/daytona/.',\n );\n }\n\n if (sandboxClass === 'linux-vm') {\n const dockerBaseSha = await computeDockerBaseSha(claudeInstall);\n if (!dockerBaseSha) {\n throw new Error(\n 'could not fingerprint the docker build context, which names the published box image ' +\n 'a linux-vm base must boot from. Ensure `pnpm -w build` ran, or set ' +\n '`agentbox config set box.daytonaClass container`.',\n );\n }\n try {\n const baked = await bakeDaytonaVmBase({\n client: getClient(opts.location ?? DAYTONA_VM_REGION),\n backend: daytonaBackend,\n regionId: opts.location ?? DAYTONA_VM_REGION,\n snapshotName,\n dockerBaseSha,\n registry: opts.registry,\n baseImage: opts.vmBaseImage,\n // Always explicit: a snapshot created with no `resources` gets Daytona's\n // 1 vCPU / 1 GiB / 3 GiB default, and the box image does not fit in 3 GiB\n // (the build dies mid-pull with a bare \"internal error\").\n resources: sizeResources ?? { ...DAYTONA_DEFAULT_RESOURCES },\n hostWorkspace: opts.hostWorkspace,\n claudeMdOverlay: daytonaClaudeMd,\n onLog: log,\n });\n if (fingerprint) {\n writePreparedDaytonaState({\n snapshotName: baked.snapshotName,\n contextSha256: fingerprint.contextSha256,\n size: sizeKey,\n // This path always sends explicit resources (see the `resources:` line\n // above), so the effective size is exactly what we asked for.\n effectiveSize: sizeKey ?? formatDaytonaSize(DAYTONA_DEFAULT_RESOURCES),\n class: 'linux-vm',\n env: baked.env,\n });\n log(\n `recorded daytona-prepared.json (fingerprint ${fingerprint.contextSha256.slice(0, 12)})`,\n );\n }\n // Reap the snapshot this bake replaces. Only after the new one is recorded\n // — a failed bake must never leave the user with no base at all. Never the\n // one we just made, and never a container snapshot (a user who flips the\n // class back would want it).\n const superseded = prepared?.base?.imageRef;\n if (\n superseded &&\n superseded !== baked.snapshotName &&\n prepared?.extras?.class === 'linux-vm'\n ) {\n log(`removing superseded snapshot '${superseded}'`);\n await deleteSnapshotQuietly(getClient(opts.location ?? DAYTONA_VM_REGION), superseded);\n }\n return { snapshotName: baked.snapshotName };\n } catch (err) {\n if (!(err instanceof VmBaseImageUnavailableError)) throw err;\n // No published image for this context (a locally edited Dockerfile.box is\n // the usual cause — a contributor, not an end user). Daytona cannot build\n // a VM from a Dockerfile, so the only thing we *can* bake is a container.\n log(\n `daytona: ${err.message} This usually means a locally modified Dockerfile.box. ` +\n `Daytona can't build a linux-vm base from a Dockerfile, so falling back to a ` +\n `container snapshot (no pause/resume).`,\n );\n sandboxClass = 'container';\n // Re-derive the name without the `-vm` suffix, or we'd register a\n // container snapshot under a name that advertises a VM.\n snapshotName =\n opts.name ?? defaultSnapshotName(fingerprint?.contextSha256 ?? null, sizeKey, sandboxClass);\n }\n }\n\n const stages = await stageAllAgentStatic({ hostWorkspace: opts.hostWorkspace });\n // Surface staging warnings (codex Keychain landmine, etc.) before the\n // longer build kicks off.\n for (const s of stages) {\n for (const w of s.staged.warnings) log(w);\n }\n\n // The Daytona SDK's `Image.fromDockerfile` takes only a path — no build args —\n // and appended `.env()`/`.runCommands()` land *after* the base Dockerfile's\n // Claude RUN (too late, and a native 403 would already have failed the build).\n // So for npm mode we build from a sibling temp Dockerfile with the\n // `AGENTBOX_CLAUDE_INSTALL` ARG default flipped to `npm`. It must live in the\n // original's directory so the Dockerfile's relative COPY sources still resolve.\n let tempDockerfile: string | null = null;\n const dockerfilePath =\n claudeInstall === 'npm'\n ? (tempDockerfile = writeNpmDockerfile(ctx.dockerfile))\n : ctx.dockerfile;\n\n // Seed build-context dir: the daytona CLAUDE.md + each staged tarball are\n // copied here under RELATIVE names so the appended `COPY <name>` sources map\n // to relative archive entries the Daytona builder actually reconstructs.\n // (An absolute `addLocalFile` COPY emits `COPY /abs/tmp/x` but archives the\n // entry as the stripped `abs/tmp/x` — the mismatch silently drops the layer.)\n let seedContextDir: string | null = null;\n try {\n // git-lfs (binary + `git lfs install --system`) is inherited for free from\n // Dockerfile.box, so an in-box checkout of an LFS repo smudges real content.\n // No daytona-specific overlay step is needed; the host-side object seeding\n // lives in sandbox-cloud's workspace-seed (seedCloneLfsObjects).\n let image: Image = Image.fromDockerfile(dockerfilePath);\n\n seedContextDir = mkdtempSync(join(tmpdir(), 'agentbox-daytona-seed-'));\n // Overlay the daytona-specific /etc/claude-code/CLAUDE.md on top of the\n // docker-shaped one baked by Dockerfile.box (daytona boxes have no host\n // .git/ bind-mount, so the in-box hint needs daytona-specific git wording).\n copyFileSync(daytonaClaudeMd, join(seedContextDir, DAYTONA_CLAUDE_MD_REL));\n\n const usable = stages.filter((s) => s.staged.tarballPath !== null);\n for (const s of usable) {\n copyFileSync(\n s.staged.tarballPath as string,\n join(seedContextDir, daytonaSeedPaths(s.kind).contextRel),\n );\n }\n\n image = image.dockerfileCommands(buildDaytonaSeedCommands(usable), seedContextDir);\n\n // Region: a container snapshot registers wherever the client points (the\n // account default unless the user pinned `box.daytonaRegion`).\n const client = getClient(opts.location ?? '');\n log(`creating Daytona snapshot '${snapshotName}'${sizeResources ? ` (${sizeKey})` : ''}…`);\n const snapshot = await client.snapshot.create(\n {\n name: snapshotName,\n image,\n ...(sizeResources ? { resources: sizeResources } : {}),\n ...(opts.location ? { regionId: opts.location } : {}),\n },\n {\n onLogs: (chunk: string) => log(String(chunk).split('\\n').filter(Boolean).join(' ')),\n },\n );\n log(`snapshot '${snapshot.name}' is ${snapshot.state ?? 'created'}`);\n if (fingerprint) {\n writePreparedDaytonaState({\n snapshotName: snapshot.name ?? snapshotName,\n contextSha256: fingerprint.contextSha256,\n size: sizeKey,\n // Without an explicit size this path lets Daytona pick, so read the\n // resources back off the created snapshot. Absent when the SDK doesn't\n // report them — better silent than a guessed number in a warning.\n effectiveSize: sizeKey ?? snapshotResourceKey(snapshot),\n class: 'container',\n });\n log(`recorded daytona-prepared.json (fingerprint ${fingerprint.contextSha256.slice(0, 12)})`);\n }\n return { snapshotName: snapshot.name ?? snapshotName };\n } finally {\n await Promise.all(stages.map((s) => s.staged.cleanup()));\n if (tempDockerfile) rmSync(tempDockerfile, { force: true });\n if (seedContextDir) rmSync(seedContextDir, { recursive: true, force: true });\n }\n}\n\n/**\n * Write a sibling copy of `Dockerfile.box` with the `AGENTBOX_CLAUDE_INSTALL`\n * ARG default flipped from `native` to `npm`, and return its path. A sibling\n * (same directory) keeps the Dockerfile's relative COPY sources resolvable.\n * Throws if the ARG line isn't found (Dockerfile drifted from this expectation).\n */\nfunction writeNpmDockerfile(originalPath: string): string {\n const original = readFileSync(originalPath, 'utf8');\n const flipped = original.replace(\n 'ARG AGENTBOX_CLAUDE_INSTALL=native',\n 'ARG AGENTBOX_CLAUDE_INSTALL=npm',\n );\n if (flipped === original) {\n throw new Error(\n `could not enable npm Claude install for Daytona: 'ARG AGENTBOX_CLAUDE_INSTALL=native' ` +\n `not found in ${originalPath}. The Dockerfile.box drifted from the expected shape.`,\n );\n }\n const target = join(dirname(originalPath), '.agentbox-claude-npm.Dockerfile');\n writeFileSync(target, flipped);\n return target;\n}\n\n/** `cpu-memory-disk` key for a resource triple, the form `extras.size` uses. */\nfunction formatDaytonaSize(r: { cpu: number; memory: number; disk: number }): string {\n return `${String(r.cpu)}-${String(r.memory)}-${String(r.disk)}`;\n}\n\n/**\n * Resources of a snapshot Daytona sized itself. Defensive: the SDK's snapshot\n * shape is not guaranteed to carry them, and this only feeds a warning string.\n */\nfunction snapshotResourceKey(snapshot: unknown): string | undefined {\n const r = (snapshot as { resources?: { cpu?: number; memory?: number; disk?: number } })\n ?.resources;\n if (!r || typeof r.cpu !== 'number' || typeof r.memory !== 'number' || typeof r.disk !== 'number')\n return undefined;\n return formatDaytonaSize({ cpu: r.cpu, memory: r.memory, disk: r.disk });\n}\n","/**\n * The `linux-vm` half of `agentbox prepare --provider daytona`.\n *\n * The container path builds its base with Daytona's declarative builder\n * (`Image.fromDockerfile` + layered seed commands). **That is not available for\n * VMs** — Daytona builds a VM snapshot only from a prebuilt registry image\n * (verified 2026-07-12: passing an `Image` with `sandboxClass: LINUX_VM` fails\n * with `build snapshot: rpc error: code = Unauthenticated`). So the VM bake is\n * shaped like Hetzner's and Vercel's instead — boot once, provision in-place,\n * snapshot the result:\n *\n * 1. `snapshot.create` a VM snapshot straight from the published GHCR box\n * image (`ghcr.io/madarco/agentbox/box:sha-<docker-context-sha>`), which\n * CI already builds and publishes. ~66s, vs ~7 min for a Dockerfile build.\n * 2. Boot one throwaway sandbox from it and, in-place:\n * a. repair `sudo` (see below),\n * b. seed the host's agent static config + the daytona CLAUDE.md overlay.\n * 3. Stop it and cold-snapshot it as the real base, then delete it.\n *\n * ## Why sudo needs repairing\n *\n * Converting the container image into a VM rootfs strips setuid bits: `sudo`\n * lands as mode 0755 and cannot escalate (\"must be owned by uid 0 and have the\n * setuid bit set\"). Only mount/umount/su keep theirs. That breaks the seed\n * (installing `/etc/claude-code/CLAUDE.md` needs root) and breaks the\n * passwordless sudo the in-box agent is told it has. `create({ user: 'root' })`\n * is not a way out — the sandbox then fails to start.\n *\n * The escape hatch is the docker socket, which the image already gives us:\n * dockerd runs at boot and `vscode` is in the `docker` group, so a privileged\n * container can write the host VM's filesystem. The repair persists into the\n * snapshot, so every box booted from this base has working sudo from the start.\n */\nimport { createHash } from 'node:crypto';\nimport type { CloudBackend, CloudHandle } from '@agentbox/core';\nimport type { Daytona } from '@daytona/sdk';\nimport { SandboxClass } from '@daytona/sdk';\nimport { seedAgentStaticIntoCloudBox } from '@agentbox/sandbox-cloud';\nimport { BOX_IMAGE_REGISTRY, registryRefForSha } from '@agentbox/sandbox-core';\nimport { waitForSnapshotActive } from './snapshot-wait.js';\n\n/**\n * Restore sudo's setuid bit (and quiet its hostname warning) from inside the\n * box, by borrowing root from the docker daemon. Exported for the unit test.\n *\n * `--privileged -v /:/host` is what lets an unprivileged `vscode` write a\n * root-owned file: the container runs as root and sees the VM's rootfs at\n * /host. This is not a privilege escalation we are introducing — `vscode` is\n * already in the `docker` group, which is root-equivalent by construction.\n */\nexport function buildSudoRepairCommand(): string {\n return (\n 'docker run --rm --privileged -v /:/host alpine sh -c ' +\n `'chown root:root /host/usr/bin/sudo && chmod 4755 /host/usr/bin/sudo && ` +\n // sudo emits \"unable to resolve host <name>\" on every call when the box's\n // hostname has no /etc/hosts entry. Noisy, and it costs a DNS timeout.\n `grep -q \"\\\\b$(cat /host/etc/hostname)\\\\b\" /host/etc/hosts || ` +\n `echo \"127.0.0.1 $(cat /host/etc/hostname)\" >> /host/etc/hosts'`\n );\n}\n\n/** Poll until dockerd answers — it starts at boot, but not instantly. */\nexport function buildDockerWaitCommand(): string {\n return 'for i in $(seq 1 30); do docker info >/dev/null 2>&1 && exit 0; sleep 2; done; exit 1';\n}\n\nexport interface VmBaseBakeOptions {\n client: Daytona;\n backend: CloudBackend;\n /** Region the VM snapshot is registered in — only us-east-1 has VM runners. */\n regionId: string;\n /** Final base-snapshot name, pinned into `box.imageDaytona`. */\n snapshotName: string;\n /** Raw docker build-context sha — names the published GHCR image. */\n dockerBaseSha: string;\n /** Registry override (`box.imageRegistry`); empty = the public default. */\n registry?: string;\n /**\n * Explicit base image (`box.daytonaVmBaseImage`), bypassing the\n * fingerprint-tagged lookup. The escape hatch for a build context with no\n * published image — chiefly a locally modified `Dockerfile.box`, i.e. anyone\n * developing on the monorepo, since a local `pnpm build` regenerates\n * `packages/ctl/dist/bin.cjs` and shifts the context sha off CI's.\n */\n baseImage?: string;\n resources?: { cpu: number; memory: number; disk: number };\n hostWorkspace?: string;\n /** Host path to the daytona `/etc/claude-code/CLAUDE.md` overlay. */\n claudeMdOverlay: string;\n onLog?: (line: string) => void;\n}\n\n/**\n * Thrown when the GHCR image the VM base must boot from doesn't exist for this\n * build context — a locally edited `Dockerfile.box`, or an npm Claude install\n * (CI publishes only the native variant). The caller degrades to the container\n * class rather than dead-ending the user.\n */\nexport class VmBaseImageUnavailableError extends Error {}\n\n/** Does the registry actually have this tag? Anonymous HEAD — no docker needed. */\nexport async function ghcrTagExists(ref: string): Promise<boolean> {\n // ghcr.io/<owner>/<path>:<tag>\n const m = /^ghcr\\.io\\/(.+):([^:]+)$/.exec(ref);\n if (!m) return true; // non-GHCR registry: don't pretend to know; let the bake try.\n const [, repo, tag] = m;\n try {\n const tokenRes = await fetch(\n `https://ghcr.io/token?scope=repository:${repo}:pull&service=ghcr.io`,\n );\n if (!tokenRes.ok) return false;\n const { token } = (await tokenRes.json()) as { token?: string };\n if (!token) return false;\n const res = await fetch(`https://ghcr.io/v2/${repo}/manifests/${tag}`, {\n method: 'HEAD',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: [\n 'application/vnd.oci.image.index.v1+json',\n 'application/vnd.oci.image.manifest.v1+json',\n 'application/vnd.docker.distribution.manifest.list.v2+json',\n 'application/vnd.docker.distribution.manifest.v2+json',\n ].join(','),\n },\n });\n return res.ok;\n } catch {\n // Network trouble is not \"the tag is missing\" — let the bake surface the\n // real error rather than silently downgrading the user to a container.\n return true;\n }\n}\n\n/**\n * The image's declared environment (`ENV` in Dockerfile.box, plus PATH), read\n * from its config blob in the registry.\n *\n * A container inherits `ENV` from the image's *metadata*. A linux-vm does not:\n * the conversion turns the image into a rootfs, and metadata is not a file, so\n * every `ENV` silently disappears — `DISPLAY=:1` above all, which is why the\n * in-box browser died with \"Missing X server or $DISPLAY\" on a VM box while\n * working fine on docker and container-class daytona. (Same family as the\n * setuid-stripping the sudo repair works around.)\n *\n * Read rather than hardcoded: Dockerfile.box owns these values, and a copy here\n * would rot the first time someone adds an ENV. The config blob is a few hundred\n * bytes — no image pull.\n *\n * Returns null when the env can't be read (non-GHCR override, network trouble):\n * the caller warns and bakes anyway rather than failing the whole prepare.\n */\nexport async function fetchImageEnv(ref: string): Promise<string[] | null> {\n const m = /^ghcr\\.io\\/(.+):([^:]+)$/.exec(ref);\n if (!m) return null;\n const [, repo, tag] = m;\n const accept = [\n 'application/vnd.oci.image.index.v1+json',\n 'application/vnd.oci.image.manifest.v1+json',\n 'application/vnd.docker.distribution.manifest.list.v2+json',\n 'application/vnd.docker.distribution.manifest.v2+json',\n ].join(',');\n try {\n const tokenRes = await fetch(\n `https://ghcr.io/token?scope=repository:${repo}:pull&service=ghcr.io`,\n );\n if (!tokenRes.ok) return null;\n const { token } = (await tokenRes.json()) as { token?: string };\n if (!token) return null;\n const headers = { Authorization: `Bearer ${token}`, Accept: accept };\n\n const get = async (r: string): Promise<Record<string, unknown> | null> => {\n const res = await fetch(`https://ghcr.io/v2/${repo}/${r}`, { headers });\n return res.ok ? ((await res.json()) as Record<string, unknown>) : null;\n };\n\n let manifest = await get(`manifests/${tag}`);\n // Multi-arch index -> pick the linux/amd64 child (Daytona is x86_64 only).\n const children = manifest?.manifests as\n | Array<{ digest: string; platform?: { os?: string; architecture?: string } }>\n | undefined;\n if (children) {\n const amd64 = children.find(\n (c) => c.platform?.os === 'linux' && c.platform.architecture === 'amd64',\n );\n if (!amd64) return null;\n manifest = await get(`manifests/${amd64.digest}`);\n }\n const configDigest = (manifest?.config as { digest?: string } | undefined)?.digest;\n if (!configDigest) return null;\n const config = await get(`blobs/${configDigest}`);\n const env = (config?.config as { Env?: unknown } | undefined)?.Env;\n if (!Array.isArray(env)) return null;\n return env.filter((e): e is string => typeof e === 'string' && e.includes('='));\n } catch {\n return null;\n }\n}\n\n/**\n * Put the image's `ENV` back on disk in the VM, where a rootfs can carry it.\n *\n * Two files, because two kinds of process need it and neither reads the other's:\n * - `/etc/profile.d/` — login shells (the ssh attach, any `bash -lc`).\n * - `/etc/environment` — PAM, and it's the conventional home for these.\n *\n * The values are also handed to `create` as sandbox env vars (see the backend),\n * which is what covers plain non-login `exec` — the path `agent-browser` runs on.\n */\nexport function buildEnvRestoreCommand(env: string[]): string {\n const shQuote = (v: string): string => `'${v.replace(/'/g, `'\\\\''`)}'`;\n const profile = env\n .map((e) => {\n const i = e.indexOf('=');\n return `export ${e.slice(0, i)}=${shQuote(e.slice(i + 1))}`;\n })\n .join('\\n');\n const envFile = env.join('\\n');\n const b64 = (s: string): string => Buffer.from(`${s}\\n`, 'utf8').toString('base64');\n // base64 through a pipe: the values contain quotes and colons, and this command\n // is itself shipped through a shell.\n return (\n `printf %s '${b64(profile)}' | base64 -d | sudo tee /etc/profile.d/agentbox-image-env.sh >/dev/null && ` +\n `sudo chmod 644 /etc/profile.d/agentbox-image-env.sh && ` +\n `printf %s '${b64(envFile)}' | base64 -d | sudo tee -a /etc/environment >/dev/null`\n );\n}\n\n/** What a VM bake produced: the snapshot, and the image env it had to restore. */\nexport interface VmBaseBakeResult {\n snapshotName: string;\n /**\n * The image's `ENV`, recorded so `create` can also hand it to the sandbox.\n * The on-disk copy covers login shells; sandbox env vars cover the plain\n * non-login `exec` that `agent-browser` (and every other host-driven command)\n * runs on. Empty when the registry couldn't be read.\n */\n env: string[];\n}\n\n/**\n * Bake the linux-vm base snapshot.\n */\nexport async function bakeDaytonaVmBase(opts: VmBaseBakeOptions): Promise<VmBaseBakeResult> {\n const log = opts.onLog ?? (() => {});\n let imageEnv: string[] = [];\n const override = opts.baseImage?.trim();\n const registry = opts.registry && opts.registry.length > 0 ? opts.registry : BOX_IMAGE_REGISTRY;\n const imageRef = override || registryRefForSha(opts.dockerBaseSha, registry);\n\n // An explicit override is the user's problem to get right — if it doesn't\n // exist, Daytona's own error is clearer than a guess from us, and silently\n // downgrading them to a container would ignore what they asked for.\n if (!override && !(await ghcrTagExists(imageRef))) {\n throw new VmBaseImageUnavailableError(\n `the linux-vm base needs a published box image, and '${imageRef}' isn't in the registry.`,\n );\n }\n if (override) log(`using box.daytonaVmBaseImage override: ${imageRef}`);\n\n // Tier 1: the plain box image as a VM snapshot. Content-addressed by the\n // docker sha, so a re-bake with different agent config reuses it (this is the\n // expensive step — it pulls a ~2 GB image). An overridden image gets its own\n // name so it can't collide with a fingerprint-derived one.\n const vmBaseStem = override\n ? `agentbox-vmbase-x${sha12(override)}`\n : `agentbox-vmbase-${opts.dockerBaseSha.slice(0, 12)}`;\n\n let vmBaseName = vmBaseStem;\n if (await snapshotIsActive(opts.client, vmBaseName)) {\n log(`reusing linux-vm base image snapshot '${vmBaseName}'`);\n } else {\n vmBaseName = await createVmBaseSnapshot(opts, vmBaseStem, imageRef, log);\n }\n\n // Tier 2: boot it, provision in-place, snapshot the result.\n log('booting a throwaway sandbox to seed the base…');\n let sandbox;\n try {\n sandbox = await opts.client.create({ snapshot: vmBaseName }, { timeout: 900 });\n } catch {\n // A snapshot recreated under a recently-deleted name reports `active` but\n // cannot boot (\"Sandbox failed to start: internal error\") — Daytona's delete\n // is async and racing it corrupts the new snapshot. Nothing distinguishes\n // this from a healthy snapshot until you try to boot it, so treat a boot\n // failure as \"the base is poisoned\", rebuild under a name that has never\n // existed, and retry once.\n log(`linux-vm base '${vmBaseName}' failed to boot; rebuilding it under a fresh name…`);\n await deleteSnapshotQuietly(opts.client, vmBaseName);\n vmBaseName = await createVmBaseSnapshot(opts, `${vmBaseStem}-${nonce()}`, imageRef, log);\n sandbox = await opts.client.create({ snapshot: vmBaseName }, { timeout: 900 });\n }\n const handle: CloudHandle = { sandboxId: sandbox.id, sandboxClass: 'linux-vm' };\n try {\n const wait = await opts.backend.exec(handle, buildDockerWaitCommand());\n if (wait.exitCode !== 0) {\n throw new Error(\n 'dockerd never came up in the VM base, so sudo cannot be repaired ' +\n '(the repair borrows root from the docker socket).',\n );\n }\n log('repairing sudo (the VM rootfs conversion strips setuid bits)…');\n const repair = await opts.backend.exec(handle, buildSudoRepairCommand());\n if (repair.exitCode !== 0) {\n throw new Error(\n `failed to restore sudo in the VM base (exit ${String(repair.exitCode)}): ` +\n `${repair.stdout}${repair.stderr}`,\n );\n }\n\n // The conversion drops the image's ENV along with the setuid bits. Put it\n // back on disk (needs the sudo we just repaired). Without it a VM box has no\n // DISPLAY, and the in-box browser dies with \"Missing X server or $DISPLAY\".\n imageEnv = (await fetchImageEnv(imageRef)) ?? [];\n if (imageEnv.length > 0) {\n log(`restoring the image's ${String(imageEnv.length)} env vars (the VM conversion drops them)…`);\n const envFix = await opts.backend.exec(handle, buildEnvRestoreCommand(imageEnv));\n if (envFix.exitCode !== 0) {\n throw new Error(\n `failed to restore the image environment in the VM base (exit ${String(envFix.exitCode)}): ` +\n `${envFix.stdout}${envFix.stderr}`,\n );\n }\n } else {\n log(\n `warning: could not read the environment of '${imageRef}' from the registry — ` +\n `a VM box may come up without DISPLAY (no in-box browser).`,\n );\n }\n\n await seedAgentStaticIntoCloudBox(opts.backend, handle, {\n hostWorkspace: opts.hostWorkspace,\n claudeMdOverlay: opts.claudeMdOverlay,\n onLog: log,\n });\n\n // Cold snapshot: filesystem only, and Daytona requires the sandbox STOPPED.\n // It does not stop for you.\n log('stopping the sandbox to capture a cold snapshot…');\n await sandbox.stop();\n // Never reuse a name (see the boot-failure comment above): a re-bake gets a\n // fresh one and the snapshot it replaces is deleted afterwards. The name\n // doesn't need to be deterministic — prepared state records whatever we\n // pinned, and that's what the skip-rebuild check reads.\n const finalName = `${opts.snapshotName}-${nonce()}`;\n log(`capturing base snapshot '${finalName}'…`);\n await sandbox._experimental_createSnapshot(finalName, 900);\n await waitForSnapshotActive(opts.client, finalName);\n log(`snapshot '${finalName}' is active`);\n return { snapshotName: finalName, env: imageEnv };\n } finally {\n // Always reap the throwaway — an orphan VM bills by the hour.\n try {\n await sandbox.delete(120);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n log(`warning: could not delete the temporary bake sandbox ${sandbox.id}: ${msg}`);\n }\n }\n}\n\n/** Stable 12-hex digest of an image ref, for a collision-free snapshot name. */\nfunction sha12(s: string): string {\n return createHash('sha256').update(s).digest('hex').slice(0, 12);\n}\n\n/** Short, monotonic, never-reused token for a snapshot name. */\nfunction nonce(): string {\n return Math.floor(Date.now() / 1000).toString(36);\n}\n\nasync function createVmBaseSnapshot(\n opts: VmBaseBakeOptions,\n name: string,\n imageRef: string,\n log: (line: string) => void,\n): Promise<string> {\n log(`creating linux-vm base image snapshot '${name}' from ${imageRef}…`);\n await opts.client.snapshot.create(\n {\n name,\n image: imageRef,\n sandboxClass: SandboxClass.LINUX_VM,\n regionId: opts.regionId,\n // Always explicit: a snapshot with no `resources` gets Daytona's 1 vCPU /\n // 1 GiB / 3 GiB default, and the box image does not fit in 3 GiB — the\n // build dies mid-pull with a bare \"internal error\".\n resources: opts.resources ?? { cpu: 2, memory: 4, disk: 8 },\n },\n { onLogs: (c: string) => log(String(c).split('\\n').filter(Boolean).join(' ')) },\n );\n return name;\n}\n\nasync function snapshotIsActive(client: Daytona, name: string): Promise<boolean> {\n try {\n const snap = await client.snapshot.get(name);\n return snap?.state === 'active';\n } catch {\n return false;\n }\n}\n\n/** Best-effort delete — used to reap a superseded or poisoned snapshot. */\nexport async function deleteSnapshotQuietly(client: Daytona, name: string): Promise<void> {\n try {\n const snap = await client.snapshot.get(name);\n await client.snapshot.delete(snap);\n } catch {\n /* already gone, or never existed */\n }\n}\n","/**\n * Doctor probes + normalized credential status for the daytona provider,\n * assembled into `providerModule` in `index.ts`. Moved out of apps/cli so the\n * CLI dispatches to it generically (see `@agentbox/sandbox-core`'s `ProviderModule`).\n */\n\nimport { loadEffectiveConfig, resolveDaytonaClass } from '@agentbox/config';\nimport { errSummary, type CheckResult, type CredStatusSummary } from '@agentbox/sandbox-core';\nimport { parseDaytonaSize } from './backend.js';\nimport { readPreparedDaytonaState } from './prepared-state.js';\nimport { getDaytonaStatus, hasDaytonaCredentials } from './status.js';\n\nexport function readCredStatusSummary(): CredStatusSummary {\n // Credentials only — no network. This runs in the install wizard's provider\n // step just to answer \"logged in?\", and it used to fetch the whole snapshot +\n // volume inventory to do it.\n return { configured: hasDaytonaCredentials().configured };\n}\n\nexport async function doctorChecks(): Promise<CheckResult[]> {\n try {\n // Snapshots only: the rows below render the snapshot count and nothing else,\n // so the volume list was a second API round-trip whose result was discarded.\n const status = await getDaytonaStatus({ volumes: false });\n if (!status.configured) {\n return [\n {\n label: 'credentials',\n status: 'warn',\n // The SDK's reason is a paragraph (env-var enumeration) — doctor just\n // needs the vercel/e2b-style one-liner; `prepare --status` keeps it.\n detail: 'not configured',\n hint: '`agentbox daytona login`',\n },\n ];\n }\n const credRes: CheckResult = { label: 'credentials', status: 'ok', detail: 'configured' };\n return [credRes, await baseSnapshotCheck(status.snapshots.length)];\n } catch (err) {\n return [{ label: 'credentials', status: 'warn', detail: errSummary(err) }];\n }\n}\n\n/**\n * A snapshot existing isn't enough: a snapshot's class is immutable and can only\n * create sandboxes of that same class, so a container base with\n * `box.daytonaClass: linux-vm` configured is unusable — every create would fail.\n * Counting snapshots would report that as healthy, so compare the class too.\n */\nasync function baseSnapshotCheck(snapshotCount: number): Promise<CheckResult> {\n if (snapshotCount === 0) {\n return {\n label: 'base snapshot',\n status: 'warn',\n detail: 'none',\n hint: '`agentbox prepare --provider daytona`',\n };\n }\n const prepared = readPreparedDaytonaState();\n // Absent `class` = a snapshot baked before classes existed, which was\n // necessarily a container.\n const bakedClass = prepared?.base ? (prepared.extras?.class ?? 'container') : undefined;\n\n let wantClass: string | undefined;\n try {\n wantClass = resolveDaytonaClass((await loadEffectiveConfig(process.cwd())).effective);\n } catch {\n // No project config to read (e.g. doctor run outside a project) — the count\n // is still worth reporting; just don't claim anything about the class.\n }\n\n if (bakedClass && wantClass && bakedClass !== wantClass) {\n return {\n label: 'base snapshot',\n status: 'warn',\n detail: `baked as '${bakedClass}' but box.daytonaClass is '${wantClass}' — creates will fail`,\n hint: '`agentbox prepare --provider daytona --force`',\n };\n }\n return {\n label: 'base snapshot',\n status: 'ok',\n detail: `${String(snapshotCount)} agentbox snapshot(s)${bakedClass ? ` (base: ${bakedClass})` : ''}`,\n };\n}\n\n/**\n * Daytona fixes resources when the SNAPSHOT is baked and rejects them on the\n * create call (`backend.ts` deletes `resources` on the snapshot path), so a\n * size that disagrees with the bake is discarded. Same comparison the backend\n * makes at provision — kept in step so the two can't drift.\n */\nexport function sizeIgnoredReason(size: string): string | null {\n const parsed = parseDaytonaSize(size);\n // A foreign spec (a hetzner server type sitting in the generic `box.size`)\n // isn't ours to judge — `prepare` surfaces that. Stay quiet.\n if (!parsed) return null;\n const requested = `${String(parsed.cpu)}-${String(parsed.memory)}-${String(parsed.disk)}`;\n const prepared = readPreparedDaytonaState();\n // Nothing baked yet: `prepare` will bake AT this size, so there is no\n // mismatch to report. Warning here would tell a first-run user their brand\n // new setting is ignored, which is the opposite of true.\n if (!prepared?.base) return null;\n // `effectiveSize` names real numbers even for a default bake; `size` (the\n // requested spec) is the fallback for snapshots baked before it was recorded.\n const baked = prepared.extras?.effectiveSize ?? prepared.extras?.size;\n if (requested === baked) return null;\n return (\n `daytona: size '${requested}' is ignored on the snapshot path; this snapshot was baked at ` +\n `${baked ?? 'the default size'}. Daytona resources are fixed at bake time — re-bake with ` +\n `\\`agentbox prepare --provider daytona --size ${requested} --force\\` to change them.`\n );\n}\n","/**\n * Read-only status helpers for `agentbox prepare` (no-args mode). Surfaces\n * the user-facing inventory of agentbox-owned base images / snapshots /\n * volumes on the configured Daytona org so the user can see at a glance\n * what's already prepared and what isn't.\n *\n * Daytona-side state lives in two places:\n * - **Snapshots** — built by `agentbox prepare --provider daytona`. Listed\n * filtered to `agentbox*` so we don't surface unrelated org snapshots.\n * - **Volumes** — the per-org `agentbox-credentials` volume created lazily\n * by `ensureAgentVolumesForCloud` on first `agentbox create --provider\n * daytona`.\n *\n * All calls swallow auth/network errors and return an empty section — the\n * status command must work for users who don't have Daytona configured.\n */\n\nimport { ensureDaytonaEnvLoaded } from './env-loader.js';\nimport { getClient } from './backend.js';\n\nexport interface DaytonaSnapshotSummary {\n name: string;\n state?: string;\n /** Snapshot size in GB, as reported by Daytona (may be undefined for non-`active` states). */\n sizeGb?: number;\n createdAt?: string;\n errorReason?: string;\n}\n\nexport interface DaytonaVolumeSummary {\n name: string;\n id: string;\n state?: string;\n createdAt?: string;\n lastUsedAt?: string;\n}\n\nexport interface DaytonaStatus {\n /** True when Daytona credentials are present + the SDK could connect. */\n configured: boolean;\n /** Snapshots whose name starts with `agentbox` (case-insensitive). */\n snapshots: DaytonaSnapshotSummary[];\n /** Volumes whose name starts with `agentbox` (case-insensitive). */\n volumes: DaytonaVolumeSummary[];\n /** Non-fatal explanation when `configured` is false. */\n reason?: string;\n}\n\nfunction isAgentboxName(name: unknown): boolean {\n return typeof name === 'string' && name.toLowerCase().startsWith('agentbox');\n}\n\n/**\n * Upper bound on a status list call. This is a *diagnostic* read — a hung API\n * must degrade to \"couldn't list\" rather than stall the caller. `doctor` in\n * particular prints no spinner, so an unbounded await just looks like a freeze.\n * Mirrors the bound the cloud-state probes already use host-side.\n */\nconst STATUS_PROBE_TIMEOUT_MS = 8000;\n\nfunction withStatusTimeout<T>(p: Promise<T>, what: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const t = setTimeout(\n () => reject(new Error(`${what} timed out after ${String(STATUS_PROBE_TIMEOUT_MS)}ms`)),\n STATUS_PROBE_TIMEOUT_MS,\n );\n // The SDK call keeps running; we just stop waiting on it. unref so a pending\n // timer can't hold the process open after the CLI is done.\n t.unref?.();\n p.then(\n (v) => {\n clearTimeout(t);\n resolve(v);\n },\n (e: unknown) => {\n clearTimeout(t);\n reject(e instanceof Error ? e : new Error(String(e)));\n },\n );\n });\n}\n\n/**\n * Are Daytona credentials present? Credential-only: constructs the SDK client\n * (which throws when no key/JWT is configured) and makes **no network call**.\n *\n * This is what `configured` in {@link DaytonaStatus} has always meant — the\n * status helper sets it as soon as the client is built, before any list. Callers\n * that only want that answer (the install wizard's provider picker, doctor's\n * \"credentials\" row) should ask here rather than pay for two API round-trips.\n */\nexport function hasDaytonaCredentials(): { configured: boolean; reason?: string } {\n try {\n ensureDaytonaEnvLoaded();\n getClient();\n return { configured: true };\n } catch (err) {\n return {\n configured: false,\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n}\n\nexport interface DaytonaStatusOptions {\n /**\n * Fetch the volume list. Each list is a separate round-trip to the Daytona\n * API, and `doctor` renders only the snapshot count — so it asks for snapshots\n * alone and halves the network cost of the check. `prepare --status`, which\n * prints the volume inventory, leaves this on. Default true (the full picture).\n */\n volumes?: boolean;\n}\n\n/**\n * Collect a read-only summary of agentbox-owned snapshots + volumes on the\n * Daytona org. Never throws — failure paths return `configured: false` with\n * a one-line reason.\n *\n * Only reaches the network when credentials are present: with no key `getClient()`\n * throws and we return `configured: false` before any request — so an unconfigured\n * machine pays nothing.\n */\nexport async function getDaytonaStatus(opts: DaytonaStatusOptions = {}): Promise<DaytonaStatus> {\n const wantVolumes = opts.volumes !== false;\n try {\n ensureDaytonaEnvLoaded();\n } catch (err) {\n return {\n configured: false,\n snapshots: [],\n volumes: [],\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n\n let client;\n try {\n client = getClient();\n } catch (err) {\n return {\n configured: false,\n snapshots: [],\n volumes: [],\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n\n const snapshots: DaytonaSnapshotSummary[] = [];\n const volumes: DaytonaVolumeSummary[] = [];\n const reasons: string[] = [];\n\n // Both lists are independent round-trips; issue them together rather than\n // back to back. Each is bounded — an unreachable/slow Daytona must degrade to\n // \"couldn't list\" rather than hang `doctor` (which has no spinner at all, so a\n // stall just looks like a freeze).\n const listSnapshots = async (): Promise<void> => {\n try {\n const list = await withStatusTimeout(client.snapshot.list(), 'snapshot list');\n const items = (list as { items?: unknown[] }).items ?? (Array.isArray(list) ? list : []);\n for (const s of items) {\n const dto = s as { name?: unknown; state?: unknown; size?: unknown; createdAt?: unknown; errorReason?: unknown };\n if (!isAgentboxName(dto.name)) continue;\n snapshots.push({\n name: dto.name as string,\n state: typeof dto.state === 'string' ? dto.state : undefined,\n sizeGb: typeof dto.size === 'number' ? dto.size : undefined,\n createdAt: typeof dto.createdAt === 'string' ? dto.createdAt : undefined,\n errorReason: typeof dto.errorReason === 'string' ? dto.errorReason : undefined,\n });\n }\n } catch (err) {\n reasons.push(\n `snapshot list failed: ${err instanceof Error ? err.message.split('\\n')[0] : String(err)}`,\n );\n }\n };\n\n const listVolumes = async (): Promise<void> => {\n try {\n const list = await withStatusTimeout(client.volume.list(), 'volume list');\n const items: unknown[] = Array.isArray(list)\n ? list\n : ((list as { items?: unknown[] }).items ?? []);\n for (const v of items) {\n const dto = v as { name?: unknown; id?: unknown; state?: unknown; createdAt?: unknown; lastUsedAt?: unknown };\n if (!isAgentboxName(dto.name)) continue;\n volumes.push({\n name: dto.name as string,\n id: typeof dto.id === 'string' ? dto.id : '',\n state: typeof dto.state === 'string' ? dto.state : undefined,\n createdAt: typeof dto.createdAt === 'string' ? dto.createdAt : undefined,\n lastUsedAt: typeof dto.lastUsedAt === 'string' ? dto.lastUsedAt : undefined,\n });\n }\n } catch (err) {\n reasons.push(\n `volume list failed: ${err instanceof Error ? err.message.split('\\n')[0] : String(err)}`,\n );\n }\n };\n\n await Promise.all(wantVolumes ? [listSnapshots(), listVolumes()] : [listSnapshots()]);\n const reason = reasons.length > 0 ? reasons.join('; ') : undefined;\n\n return {\n configured: true,\n snapshots: snapshots.sort((a, b) => (b.createdAt ?? '').localeCompare(a.createdAt ?? '')),\n volumes: volumes.sort((a, b) => a.name.localeCompare(b.name)),\n reason,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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oBAAoB,gBAAgB;EACxD,kBAAkB,EAAE,GAAG,0BAA0B;AACnD,CAAC;AAEM,IAAM,kBAA4B;EACvC,GAAG;EACH,SAAS;;;;EAIT,YAAY,sBAAsB,aAAa;EAC/C,iBAAiB,CAAC,kBAAkB,kCAAkC,aAAa;AACrF;AAGO,IAAM,iBAAiC;EAC5C,UAAU;EACV,SAAS;EACT,mBAAmB;EACnB,gBAAgB;EAChB,gBAAgB;EAChB,4BAA4B,CAAC,kBAAkB,kCAAkC,aAAa;EAC9F;EACA;AACF;","names":["cloudProvider"]}
|
|
1
|
+
{"version":3,"sources":["../../../packages/sandbox-daytona/src/index.ts","../../../packages/sandbox-daytona/src/checkpoint.ts","../../../packages/sandbox-daytona/src/prepare.ts","../../../packages/sandbox-daytona/src/prepare-vm.ts","../../../packages/sandbox-daytona/src/provider-module.ts","../../../packages/sandbox-daytona/src/status.ts"],"sourcesContent":["/**\n * The Daytona Cloud sandbox provider. A thin `CloudBackend` over\n * `@daytona/sdk`, composed via `@agentbox/sandbox-cloud`'s `createCloudProvider`\n * for everything provider-agnostic (workspace seeding, ctl launch, state).\n */\n\nimport type { Provider } from '@agentbox/core';\nimport type { ProviderModule } from '@agentbox/sandbox-core';\nimport { createCloudProvider } from '@agentbox/sandbox-cloud';\nimport { DAYTONA_DEFAULT_RESOURCES, daytonaBackend, DEFAULT_BOX_IMAGE_REF } from './backend.js';\nimport { makeDaytonaCheckpoint } from './checkpoint.js';\nimport { prepareDaytona } from './prepare.js';\nimport { currentDaytonaBaseFingerprintLive } from './prepared-state.js';\nimport { ensureDaytonaCredentials, setDaytonaCredentials } from './credentials.js';\nimport { doctorChecks, readCredStatusSummary, sizeIgnoredReason } from './provider-module.js';\n\nconst cloudProvider = createCloudProvider(daytonaBackend, {\n defaultResources: { ...DAYTONA_DEFAULT_RESOURCES },\n});\n\nexport const daytonaProvider: Provider = {\n ...cloudProvider,\n prepare: prepareDaytona,\n // Overrides the generic cloud checkpoint: a Daytona cold snapshot needs the\n // sandbox stopped, which kills the in-box daemons, so the capture has to\n // reconnect the box afterwards. See `makeDaytonaCheckpoint`.\n checkpoint: makeDaytonaCheckpoint(cloudProvider),\n baseFingerprint: (claudeInstall) => currentDaytonaBaseFingerprintLive(claudeInstall),\n};\n\n/** Uniform surface the CLI provider loader resolves this package through. */\nexport const providerModule: ProviderModule = {\n provider: daytonaProvider,\n backend: daytonaBackend,\n ensureCredentials: ensureDaytonaCredentials,\n readCredStatus: readCredStatusSummary,\n setCredentials: setDaytonaCredentials,\n currentBaseFingerprintLive: (claudeInstall) => currentDaytonaBaseFingerprintLive(claudeInstall),\n sizeIgnoredReason,\n doctorChecks,\n};\n\nexport { DAYTONA_DEFAULT_RESOURCES, daytonaBackend, DEFAULT_BOX_IMAGE_REF };\nexport { resolveDockerfileContext, type DockerfileContext } from './dockerfile-context.js';\nexport { ensureDaytonaEnvLoaded } from './env-loader.js';\nexport { currentDaytonaBaseFingerprintLive } from './prepared-state.js';\n// Called by the CLI provider registry to gate first-run interactive setup.\n// Plain async function — no commander surface — so adding it here doesn't\n// pull commander/clack into consumers' type graphs. The full CLI command\n// lives at the `./cli` subpath export.\nexport { ensureDaytonaCredentials, setDaytonaCredentials } from './credentials.js';\nexport type { EnsureDaytonaCredentialsOptions } from './credentials.js';\nexport {\n getDaytonaStatus,\n type DaytonaStatus,\n type DaytonaSnapshotSummary,\n type DaytonaVolumeSummary,\n} from './status.js';\n","/**\n * Daytona cloud checkpoints.\n *\n * Overrides the generic cloud checkpoint (`makeCloudCheckpoint`) because\n * Daytona's capture has two properties the generic one doesn't model:\n *\n * 1. **A cold snapshot requires the sandbox STOPPED, and Daytona will not stop\n * it for you.** (The hot, filesystem+memory variant needs `includeMemory`,\n * which the published TS SDK silently drops — so it's out of reach until\n * upstream fixes the wrapper.) So we stop, capture, and start again. The\n * stop kills the in-box `ctl` daemon, dockerd, VNC and the agent's tmux\n * session, so the box must be *reconnected* afterwards or the user is left\n * with a running sandbox whose services are all dead.\n *\n * 2. **A snapshot name must never be reused.** Recreating a snapshot under a\n * recently-deleted name yields one that reports `active` but cannot boot\n * (\"Sandbox failed to start: internal error\") — Daytona's delete is async\n * and racing it corrupts the new snapshot. `agentbox checkpoint rm <name>`\n * followed by a re-create with the same name would walk straight into that,\n * so the Daytona-side name carries a nonce while the user-facing checkpoint\n * name stays whatever they typed. The manifest maps one to the other.\n */\nimport type { BoxRecord, Provider, ProviderCheckpoint } from '@agentbox/core';\nimport {\n cloudSnapshotName,\n currentCloudBaseFingerprint,\n listCloudCheckpoints,\n removeCloudCheckpointDir,\n resolveCloudCheckpoint,\n writeCloudCheckpointManifest,\n} from '@agentbox/sandbox-cloud';\nimport { readCliStamp } from '@agentbox/sandbox-core';\nimport { daytonaBackend } from './backend.js';\n\nconst BACKEND_NAME = 'daytona';\n\nexport function makeDaytonaCheckpoint(cloudProvider: Provider): ProviderCheckpoint {\n return {\n async create(box: BoxRecord, name: string) {\n if (!box.projectRoot) {\n throw new Error(\n 'cloud checkpoint requires the box to have a project root (run `agentbox checkpoint` from inside the project)',\n );\n }\n const sandboxId = box.cloud?.sandboxId;\n if (!sandboxId) {\n throw new Error(`daytona box ${box.name} has no sandboxId — record is malformed`);\n }\n const handle = { sandboxId, sandboxClass: box.cloud?.sandboxClass };\n // Unique per capture — see the name-reuse note above.\n const snapshotName = `${cloudSnapshotName(box.projectRoot, name)}-${Math.floor(Date.now() / 1000).toString(36)}`;\n\n await daytonaBackend.createSnapshot?.(handle, snapshotName);\n\n // The capture stopped and restarted the sandbox, so everything the box was\n // running is gone. `reconnect` re-runs the bootstrap (ctl, dockerd, VNC,\n // preview URLs) — without it the box looks up but answers nothing.\n await cloudProvider.reconnect(box);\n\n const info = await writeCloudCheckpointManifest(box.projectRoot, BACKEND_NAME, name, {\n snapshotName,\n sourceBoxId: box.id,\n sourceBoxName: box.name,\n baseProvider: BACKEND_NAME,\n baseFingerprint: currentCloudBaseFingerprint(BACKEND_NAME),\n cliVersion: readCliStamp().cliVersion,\n });\n return { ref: info.name };\n },\n\n async list(projectRoot: string) {\n const entries = await listCloudCheckpoints(projectRoot, BACKEND_NAME);\n return entries.map((e) => ({ ref: e.name, createdAt: e.manifest.createdAt }));\n },\n\n async remove(projectRoot: string, ref: string) {\n const entry = await resolveCloudCheckpoint(projectRoot, BACKEND_NAME, ref);\n if (!entry) return;\n try {\n await daytonaBackend.deleteSnapshot?.(entry.manifest.snapshotName);\n } catch {\n // Best-effort: drop the local manifest even when the remote delete fails,\n // so the user isn't left holding a pointer to nothing.\n }\n await removeCloudCheckpointDir(projectRoot, BACKEND_NAME, ref);\n },\n };\n}\n","/**\n * Daytona-side implementation of the `Provider.prepare` hook (`agentbox\n * prepare --provider daytona`). One-time, user-triggered:\n *\n * 1. Stage filtered tarballs of the host's `~/.claude`, `~/.codex`, and\n * `~/.local/share/opencode` static config (no auth tokens — those go on\n * the per-org `agentbox-credentials` volume at create time).\n * 2. Build a layered Daytona `Image`: start from `Dockerfile.box`, then\n * `.addLocalFile()` each staged tarball + `.runCommands()` to extract\n * them into the right paths inside the image.\n * 3. Call `daytona.snapshot.create({ name, image }, { onLogs })` — Daytona\n * runs the build server-side, registers the result as an org-scoped\n * named snapshot, and returns when it's `active`.\n *\n * Replaces the old `agentbox daytona publish-snapshot` flow that\n * provisioned a sandbox + ran an in-sandbox bake + called the broken\n * `_experimental_createSnapshot`. The new path never provisions a sandbox.\n *\n * Source of truth for the public API:\n * https://www.daytona.io/docs/en/snapshots/\n */\n\nimport { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { Image } from '@daytona/sdk';\nimport type { PrepareOptions, PrepareResult } from '@agentbox/core';\nimport { DAYTONA_VM_REGION, type DaytonaSandboxClass } from '@agentbox/config';\nimport {\n claudeInstallFingerprint,\n stageAllAgentStatic,\n type AgentStaticStage,\n} from '@agentbox/sandbox-core';\nimport {\n DAYTONA_DEFAULT_RESOURCES,\n daytonaBackend,\n getClient,\n parseDaytonaSize,\n} from './backend.js';\nimport { resolveDaytonaCustomClaudeMd, resolveDockerfileContext } from './dockerfile-context.js';\nimport { ensureDaytonaEnvLoaded } from './env-loader.js';\nimport {\n bakeDaytonaVmBase,\n deleteSnapshotQuietly,\n VmBaseImageUnavailableError,\n} from './prepare-vm.js';\nimport {\n computeDaytonaContextFingerprint,\n computeDockerBaseSha,\n preparedMatches,\n readPreparedDaytonaState,\n writePreparedDaytonaState,\n} from './prepared-state.js';\n\n/**\n * Default snapshot name. Keyed on the first 12 chars of the build-context\n * fingerprint so identical content produces the same snapshot name across\n * machines / CLI runs (idempotent): if the named snapshot already exists\n * on Daytona, prepare can short-circuit without uploading the build\n * context again. Falls back to a timestamp when fingerprinting fails\n * (partial dev rebuild).\n */\nexport function defaultSnapshotName(\n fingerprint: string | null,\n sizeKey?: string,\n sandboxClass?: DaytonaSandboxClass,\n): string {\n // The size suffix keeps re-sized bakes from colliding on one name, so a\n // `--size 2-4-8` snapshot doesn't overwrite the `4-8-20` one. Same for the\n // class: a VM and a container snapshot of the same context are different\n // artifacts and cannot substitute for each other. Container stays unsuffixed\n // so existing snapshot names keep resolving.\n const suffix = `${sizeKey ? `-${sizeKey}` : ''}${sandboxClass === 'linux-vm' ? '-vm' : ''}`;\n if (fingerprint) return `agentbox-base-${fingerprint.slice(0, 12)}${suffix}`;\n return `agentbox-base-${Math.floor(Date.now() / 1000).toString()}${suffix}`;\n}\n\n/**\n * Daytona build paths for a staged tool. The tarball is copied into the seed\n * build-context dir under `contextRel` (a RELATIVE name — the Daytona builder\n * only resolves COPY sources that map to a relative archive entry; an absolute\n * `addLocalFile` COPY silently fails to land), then COPYed to `remoteTar`.\n */\nfunction daytonaSeedPaths(kind: AgentStaticStage['kind']): {\n contextRel: string;\n remoteTar: string;\n} {\n return {\n contextRel: `agentbox-seed-${kind}.tar.gz`,\n remoteTar: `/tmp/agentbox-seed-${kind}.tar.gz`,\n };\n}\n\n/** Relative name the daytona CLAUDE.md overlay is staged under in the seed context dir. */\nconst DAYTONA_CLAUDE_MD_REL = 'agentbox-custom-CLAUDE.md';\n\n/**\n * Build the appended Dockerfile commands for the seed bake. Every `COPY` source\n * is a RELATIVE name resolved against the seed build-context dir — the Daytona\n * builder drops absolute-source COPYs (they archive to a stripped relative entry\n * that the absolute source can't reference), so relative names are mandatory.\n * Runs as root (COPY drops files root-owned; chown -R + /etc/claude-code need\n * root), then restores `USER vscode` so the image keeps its default-user invariant.\n * Pure + exported for the regression test.\n */\nexport function buildDaytonaSeedCommands(\n usable: ReadonlyArray<Pick<AgentStaticStage, 'kind' | 'extractDir'>>,\n): string[] {\n const cmds: string[] = [\n 'USER root',\n `COPY ${DAYTONA_CLAUDE_MD_REL} /tmp/agentbox-custom-CLAUDE.md`,\n ...usable.map(\n (s) => `COPY ${daytonaSeedPaths(s.kind).contextRel} ${daytonaSeedPaths(s.kind).remoteTar}`,\n ),\n 'RUN install -m 0644 /tmp/agentbox-custom-CLAUDE.md /etc/claude-code/CLAUDE.md && rm -f /tmp/agentbox-custom-CLAUDE.md',\n ...usable.map(\n (s) =>\n `RUN mkdir -p ${s.extractDir} && tar -xzf ${daytonaSeedPaths(s.kind).remoteTar} -C ${s.extractDir} --no-same-permissions --no-same-owner -m`,\n ),\n ];\n if (usable.length > 0) {\n // Own the extracted trees as the box user, then drop the staging tarballs.\n // ~/.agents is only present when the host had one (skills dir); guard it.\n cmds.push(\n 'RUN chown -R vscode:vscode /home/vscode/.claude /home/vscode/.codex /home/vscode/.local' +\n ' && ( [ -d /home/vscode/.agents ] && chown -R vscode:vscode /home/vscode/.agents || true )' +\n ' && rm -f /tmp/agentbox-seed-*.tar.gz',\n );\n }\n cmds.push('USER vscode');\n return cmds;\n}\n\n/**\n * Run `agentbox prepare --provider daytona`. Returns `{ snapshotName }` on\n * success so the CLI can pin it into the project config.\n */\nexport async function prepareDaytona(opts: PrepareOptions): Promise<PrepareResult> {\n ensureDaytonaEnvLoaded();\n const log = opts.onLog ?? (() => {});\n\n // Fingerprint the build context first so we can (a) name the snapshot\n // deterministically and (b) detect cache hits against the recorded\n // prepared state. Computed before staging so an early `null` (partial\n // dev rebuild) doesn't waste a tar staging cycle.\n const claudeInstall = opts.claudeInstall ?? 'native';\n\n // Bake-time resources. A `--size` / `box.sizeDaytona` like `4-8-20` sets the\n // snapshot's baked CPU/memory/disk (Daytona rejects resources on the create\n // snapshot path, so it MUST be set here). Normalize to a canonical\n // `cpu-memory-disk` string for the snapshot-name suffix + prepared-state so\n // `04-08-20` and `4-8-20` don't fork the cache.\n const sizeSpec = opts.size?.trim() || undefined;\n const sizeResources = sizeSpec ? parseDaytonaSize(sizeSpec) : undefined;\n if (sizeSpec && !sizeResources) {\n throw new Error(\n `invalid --size '${sizeSpec}' for daytona: expected 'cpu-memory-disk' GB, e.g. '4-8-20'.`,\n );\n }\n const sizeKey = sizeResources\n ? `${String(sizeResources.cpu)}-${String(sizeResources.memory)}-${String(sizeResources.disk)}`\n : undefined;\n\n // The class is fixed at bake time — a snapshot of one class cannot create a\n // sandbox of the other — so it belongs in the snapshot name and the cache key.\n let sandboxClass: DaytonaSandboxClass =\n opts.sandboxClass === 'container' ? 'container' : 'linux-vm';\n const rawFingerprint = await computeDaytonaContextFingerprint();\n // Fold the install mode into the sha so native↔npm are distinct cache\n // identities (`native` leaves the hash unchanged) — the snapshot name and the\n // prepared-state match both derive from it.\n const fingerprint = rawFingerprint\n ? {\n ...rawFingerprint,\n contextSha256: claudeInstallFingerprint(rawFingerprint.contextSha256, claudeInstall),\n }\n : rawFingerprint;\n // Not const: a linux-vm bake that finds no published base image downgrades to\n // container below, and must then drop the `-vm` suffix from its name.\n let snapshotName =\n opts.name ?? defaultSnapshotName(fingerprint?.contextSha256 ?? null, sizeKey, sandboxClass);\n\n const prepared = readPreparedDaytonaState();\n if (\n !opts.force &&\n fingerprint &&\n preparedMatches(prepared, fingerprint.contextSha256, sizeKey, sandboxClass)\n ) {\n // Confirm the snapshot still exists on Daytona before short-circuiting.\n // A \"yes locally, no on the server\" mismatch must rebuild.\n try {\n const existing = await getClient().snapshot.get(prepared?.base?.imageRef ?? snapshotName);\n if (existing?.name) {\n log(\n `daytona snapshot '${existing.name}' up to date ` +\n `(fingerprint ${fingerprint.contextSha256.slice(0, 12)}) — skipping rebuild ` +\n `(pass --force to override)`,\n );\n return { snapshotName: existing.name };\n }\n log(\n `recorded snapshot '${prepared?.base?.imageRef ?? snapshotName}' not found on Daytona; rebuilding`,\n );\n } catch {\n log(`recorded snapshot lookup failed; rebuilding (pass --force to silence)`);\n }\n } else if (!opts.force && fingerprint && prepared?.base?.contextSha256) {\n const bakedSize = prepared.extras?.size;\n const bakedClass = prepared.extras?.class ?? 'container';\n const sameContext = prepared.base.contextSha256 === fingerprint.contextSha256;\n if (sameContext && bakedClass !== sandboxClass) {\n log(\n `daytona sandbox class changed (was ${bakedClass}, now ${sandboxClass}); rebuilding snapshot`,\n );\n } else if (sameContext && bakedSize !== sizeKey) {\n log(\n `daytona size changed (was ${bakedSize ?? 'default'}, now ${sizeKey ?? 'default'}); ` +\n `rebuilding snapshot`,\n );\n } else {\n log(\n `daytona build context changed (was ${prepared.base.contextSha256.slice(0, 12)}, ` +\n `now ${fingerprint.contextSha256.slice(0, 12)}); rebuilding snapshot`,\n );\n }\n }\n\n const ctx = resolveDockerfileContext();\n if (!ctx) {\n throw new Error(\n 'could not locate AgentBox Dockerfile.box build context for the Daytona snapshot. ' +\n 'Set AGENTBOX_DOCKER_CONTEXT to the directory containing Dockerfile.box.',\n );\n }\n\n const daytonaClaudeMd = resolveDaytonaCustomClaudeMd();\n if (!daytonaClaudeMd) {\n throw new Error(\n 'could not locate packages/sandbox-daytona/scripts/custom-system-CLAUDE.md ' +\n '(or its staged runtime/daytona/ copy). Ensure `pnpm -w build` ran so the ' +\n 'CLI staging populated runtime/daytona/.',\n );\n }\n\n if (sandboxClass === 'linux-vm') {\n const dockerBaseSha = await computeDockerBaseSha(claudeInstall);\n if (!dockerBaseSha) {\n throw new Error(\n 'could not fingerprint the docker build context, which names the published box image ' +\n 'a linux-vm base must boot from. Ensure `pnpm -w build` ran, or set ' +\n '`agentbox config set box.daytonaClass container`.',\n );\n }\n try {\n const baked = await bakeDaytonaVmBase({\n client: getClient(opts.location ?? DAYTONA_VM_REGION),\n backend: daytonaBackend,\n regionId: opts.location ?? DAYTONA_VM_REGION,\n snapshotName,\n dockerBaseSha,\n registry: opts.registry,\n baseImage: opts.vmBaseImage,\n // Always explicit: a snapshot created with no `resources` gets Daytona's\n // 1 vCPU / 1 GiB / 3 GiB default, and the box image does not fit in 3 GiB\n // (the build dies mid-pull with a bare \"internal error\").\n resources: sizeResources ?? { ...DAYTONA_DEFAULT_RESOURCES },\n hostWorkspace: opts.hostWorkspace,\n claudeMdOverlay: daytonaClaudeMd,\n onLog: log,\n });\n if (fingerprint) {\n writePreparedDaytonaState({\n snapshotName: baked.snapshotName,\n contextSha256: fingerprint.contextSha256,\n size: sizeKey,\n // This path always sends explicit resources (see the `resources:` line\n // above), so the effective size is exactly what we asked for.\n effectiveSize: sizeKey ?? formatDaytonaSize(DAYTONA_DEFAULT_RESOURCES),\n class: 'linux-vm',\n env: baked.env,\n });\n log(\n `recorded daytona-prepared.json (fingerprint ${fingerprint.contextSha256.slice(0, 12)})`,\n );\n }\n // Reap the snapshot this bake replaces. Only after the new one is recorded\n // — a failed bake must never leave the user with no base at all. Never the\n // one we just made, and never a container snapshot (a user who flips the\n // class back would want it).\n const superseded = prepared?.base?.imageRef;\n if (\n superseded &&\n superseded !== baked.snapshotName &&\n prepared?.extras?.class === 'linux-vm'\n ) {\n log(`removing superseded snapshot '${superseded}'`);\n await deleteSnapshotQuietly(getClient(opts.location ?? DAYTONA_VM_REGION), superseded);\n }\n return { snapshotName: baked.snapshotName };\n } catch (err) {\n if (!(err instanceof VmBaseImageUnavailableError)) throw err;\n // No published image for this context (a locally edited Dockerfile.box is\n // the usual cause — a contributor, not an end user). Daytona cannot build\n // a VM from a Dockerfile, so the only thing we *can* bake is a container.\n log(\n `daytona: ${err.message} This usually means a locally modified Dockerfile.box. ` +\n `Daytona can't build a linux-vm base from a Dockerfile, so falling back to a ` +\n `container snapshot (no pause/resume).`,\n );\n sandboxClass = 'container';\n // Re-derive the name without the `-vm` suffix, or we'd register a\n // container snapshot under a name that advertises a VM.\n snapshotName =\n opts.name ?? defaultSnapshotName(fingerprint?.contextSha256 ?? null, sizeKey, sandboxClass);\n }\n }\n\n const stages = await stageAllAgentStatic({ hostWorkspace: opts.hostWorkspace });\n // Surface staging warnings (codex Keychain landmine, etc.) before the\n // longer build kicks off.\n for (const s of stages) {\n for (const w of s.staged.warnings) log(w);\n }\n\n // The Daytona SDK's `Image.fromDockerfile` takes only a path — no build args —\n // and appended `.env()`/`.runCommands()` land *after* the base Dockerfile's\n // Claude RUN (too late, and a native 403 would already have failed the build).\n // So for npm mode we build from a sibling temp Dockerfile with the\n // `AGENTBOX_CLAUDE_INSTALL` ARG default flipped to `npm`. It must live in the\n // original's directory so the Dockerfile's relative COPY sources still resolve.\n let tempDockerfile: string | null = null;\n const dockerfilePath =\n claudeInstall === 'npm'\n ? (tempDockerfile = writeNpmDockerfile(ctx.dockerfile))\n : ctx.dockerfile;\n\n // Seed build-context dir: the daytona CLAUDE.md + each staged tarball are\n // copied here under RELATIVE names so the appended `COPY <name>` sources map\n // to relative archive entries the Daytona builder actually reconstructs.\n // (An absolute `addLocalFile` COPY emits `COPY /abs/tmp/x` but archives the\n // entry as the stripped `abs/tmp/x` — the mismatch silently drops the layer.)\n let seedContextDir: string | null = null;\n try {\n // git-lfs (binary + `git lfs install --system`) is inherited for free from\n // Dockerfile.box, so an in-box checkout of an LFS repo smudges real content.\n // No daytona-specific overlay step is needed; the host-side object seeding\n // lives in sandbox-cloud's workspace-seed (seedCloneLfsObjects).\n let image: Image = Image.fromDockerfile(dockerfilePath);\n\n seedContextDir = mkdtempSync(join(tmpdir(), 'agentbox-daytona-seed-'));\n // Overlay the daytona-specific /etc/claude-code/CLAUDE.md on top of the\n // docker-shaped one baked by Dockerfile.box (daytona boxes have no host\n // .git/ bind-mount, so the in-box hint needs daytona-specific git wording).\n copyFileSync(daytonaClaudeMd, join(seedContextDir, DAYTONA_CLAUDE_MD_REL));\n\n const usable = stages.filter((s) => s.staged.tarballPath !== null);\n for (const s of usable) {\n copyFileSync(\n s.staged.tarballPath as string,\n join(seedContextDir, daytonaSeedPaths(s.kind).contextRel),\n );\n }\n\n image = image.dockerfileCommands(buildDaytonaSeedCommands(usable), seedContextDir);\n\n // Region: a container snapshot registers wherever the client points (the\n // account default unless the user pinned `box.daytonaRegion`).\n const client = getClient(opts.location ?? '');\n log(`creating Daytona snapshot '${snapshotName}'${sizeResources ? ` (${sizeKey})` : ''}…`);\n const snapshot = await client.snapshot.create(\n {\n name: snapshotName,\n image,\n ...(sizeResources ? { resources: sizeResources } : {}),\n ...(opts.location ? { regionId: opts.location } : {}),\n },\n {\n onLogs: (chunk: string) => log(String(chunk).split('\\n').filter(Boolean).join(' ')),\n },\n );\n log(`snapshot '${snapshot.name}' is ${snapshot.state ?? 'created'}`);\n if (fingerprint) {\n writePreparedDaytonaState({\n snapshotName: snapshot.name ?? snapshotName,\n contextSha256: fingerprint.contextSha256,\n size: sizeKey,\n // Without an explicit size this path lets Daytona pick, so read the\n // resources back off the created snapshot. Absent when the SDK doesn't\n // report them — better silent than a guessed number in a warning.\n effectiveSize: sizeKey ?? snapshotResourceKey(snapshot),\n class: 'container',\n });\n log(`recorded daytona-prepared.json (fingerprint ${fingerprint.contextSha256.slice(0, 12)})`);\n }\n return { snapshotName: snapshot.name ?? snapshotName };\n } finally {\n await Promise.all(stages.map((s) => s.staged.cleanup()));\n if (tempDockerfile) rmSync(tempDockerfile, { force: true });\n if (seedContextDir) rmSync(seedContextDir, { recursive: true, force: true });\n }\n}\n\n/**\n * Write a sibling copy of `Dockerfile.box` with the `AGENTBOX_CLAUDE_INSTALL`\n * ARG default flipped from `native` to `npm`, and return its path. A sibling\n * (same directory) keeps the Dockerfile's relative COPY sources resolvable.\n * Throws if the ARG line isn't found (Dockerfile drifted from this expectation).\n */\nfunction writeNpmDockerfile(originalPath: string): string {\n const original = readFileSync(originalPath, 'utf8');\n const flipped = original.replace(\n 'ARG AGENTBOX_CLAUDE_INSTALL=native',\n 'ARG AGENTBOX_CLAUDE_INSTALL=npm',\n );\n if (flipped === original) {\n throw new Error(\n `could not enable npm Claude install for Daytona: 'ARG AGENTBOX_CLAUDE_INSTALL=native' ` +\n `not found in ${originalPath}. The Dockerfile.box drifted from the expected shape.`,\n );\n }\n const target = join(dirname(originalPath), '.agentbox-claude-npm.Dockerfile');\n writeFileSync(target, flipped);\n return target;\n}\n\n/** `cpu-memory-disk` key for a resource triple, the form `extras.size` uses. */\nfunction formatDaytonaSize(r: { cpu: number; memory: number; disk: number }): string {\n return `${String(r.cpu)}-${String(r.memory)}-${String(r.disk)}`;\n}\n\n/**\n * Resources of a snapshot Daytona sized itself. Defensive: the SDK's snapshot\n * shape is not guaranteed to carry them, and this only feeds a warning string.\n */\nfunction snapshotResourceKey(snapshot: unknown): string | undefined {\n const r = (snapshot as { resources?: { cpu?: number; memory?: number; disk?: number } })\n ?.resources;\n if (!r || typeof r.cpu !== 'number' || typeof r.memory !== 'number' || typeof r.disk !== 'number')\n return undefined;\n return formatDaytonaSize({ cpu: r.cpu, memory: r.memory, disk: r.disk });\n}\n","/**\n * The `linux-vm` half of `agentbox prepare --provider daytona`.\n *\n * The container path builds its base with Daytona's declarative builder\n * (`Image.fromDockerfile` + layered seed commands). **That is not available for\n * VMs** — Daytona builds a VM snapshot only from a prebuilt registry image\n * (verified 2026-07-12: passing an `Image` with `sandboxClass: LINUX_VM` fails\n * with `build snapshot: rpc error: code = Unauthenticated`). So the VM bake is\n * shaped like Hetzner's and Vercel's instead — boot once, provision in-place,\n * snapshot the result:\n *\n * 1. `snapshot.create` a VM snapshot straight from the published GHCR box\n * image (`ghcr.io/madarco/agentbox/box:sha-<docker-context-sha>`), which\n * CI already builds and publishes. ~66s, vs ~7 min for a Dockerfile build.\n * 2. Boot one throwaway sandbox from it and, in-place:\n * a. repair `sudo` (see below),\n * b. seed the host's agent static config + the daytona CLAUDE.md overlay.\n * 3. Stop it and cold-snapshot it as the real base, then delete it.\n *\n * ## Why sudo needs repairing\n *\n * Converting the container image into a VM rootfs strips setuid bits: `sudo`\n * lands as mode 0755 and cannot escalate (\"must be owned by uid 0 and have the\n * setuid bit set\"). Only mount/umount/su keep theirs. That breaks the seed\n * (installing `/etc/claude-code/CLAUDE.md` needs root) and breaks the\n * passwordless sudo the in-box agent is told it has. `create({ user: 'root' })`\n * is not a way out — the sandbox then fails to start.\n *\n * The escape hatch is the docker socket, which the image already gives us:\n * dockerd runs at boot and `vscode` is in the `docker` group, so a privileged\n * container can write the host VM's filesystem. The repair persists into the\n * snapshot, so every box booted from this base has working sudo from the start.\n */\nimport { createHash } from 'node:crypto';\nimport type { CloudBackend, CloudHandle } from '@agentbox/core';\nimport type { Daytona } from '@daytona/sdk';\nimport { SandboxClass } from '@daytona/sdk';\nimport { seedAgentStaticIntoCloudBox } from '@agentbox/sandbox-cloud';\nimport { BOX_IMAGE_REGISTRY, registryRefForSha } from '@agentbox/sandbox-core';\nimport { waitForSnapshotActive } from './snapshot-wait.js';\n\n/**\n * Restore sudo's setuid bit (and quiet its hostname warning) from inside the\n * box, by borrowing root from the docker daemon. Exported for the unit test.\n *\n * `--privileged -v /:/host` is what lets an unprivileged `vscode` write a\n * root-owned file: the container runs as root and sees the VM's rootfs at\n * /host. This is not a privilege escalation we are introducing — `vscode` is\n * already in the `docker` group, which is root-equivalent by construction.\n */\nexport function buildSudoRepairCommand(): string {\n return (\n 'docker run --rm --privileged -v /:/host alpine sh -c ' +\n `'chown root:root /host/usr/bin/sudo && chmod 4755 /host/usr/bin/sudo && ` +\n // sudo emits \"unable to resolve host <name>\" on every call when the box's\n // hostname has no /etc/hosts entry. Noisy, and it costs a DNS timeout.\n `grep -q \"\\\\b$(cat /host/etc/hostname)\\\\b\" /host/etc/hosts || ` +\n `echo \"127.0.0.1 $(cat /host/etc/hostname)\" >> /host/etc/hosts'`\n );\n}\n\n/** Poll until dockerd answers — it starts at boot, but not instantly. */\nexport function buildDockerWaitCommand(): string {\n return 'for i in $(seq 1 30); do docker info >/dev/null 2>&1 && exit 0; sleep 2; done; exit 1';\n}\n\nexport interface VmBaseBakeOptions {\n client: Daytona;\n backend: CloudBackend;\n /** Region the VM snapshot is registered in — only us-east-1 has VM runners. */\n regionId: string;\n /** Final base-snapshot name, pinned into `box.imageDaytona`. */\n snapshotName: string;\n /** Raw docker build-context sha — names the published GHCR image. */\n dockerBaseSha: string;\n /** Registry override (`box.imageRegistry`); empty = the public default. */\n registry?: string;\n /**\n * Explicit base image (`box.daytonaVmBaseImage`), bypassing the\n * fingerprint-tagged lookup. The escape hatch for a build context with no\n * published image — chiefly a locally modified `Dockerfile.box`, i.e. anyone\n * developing on the monorepo, since a local `pnpm build` regenerates\n * `packages/ctl/dist/bin.cjs` and shifts the context sha off CI's.\n */\n baseImage?: string;\n resources?: { cpu: number; memory: number; disk: number };\n hostWorkspace?: string;\n /** Host path to the daytona `/etc/claude-code/CLAUDE.md` overlay. */\n claudeMdOverlay: string;\n onLog?: (line: string) => void;\n}\n\n/**\n * Thrown when the GHCR image the VM base must boot from doesn't exist for this\n * build context — a locally edited `Dockerfile.box`, or an npm Claude install\n * (CI publishes only the native variant). The caller degrades to the container\n * class rather than dead-ending the user.\n */\nexport class VmBaseImageUnavailableError extends Error {}\n\n/** Does the registry actually have this tag? Anonymous HEAD — no docker needed. */\nexport async function ghcrTagExists(ref: string): Promise<boolean> {\n // ghcr.io/<owner>/<path>:<tag>\n const m = /^ghcr\\.io\\/(.+):([^:]+)$/.exec(ref);\n if (!m) return true; // non-GHCR registry: don't pretend to know; let the bake try.\n const [, repo, tag] = m;\n try {\n const tokenRes = await fetch(\n `https://ghcr.io/token?scope=repository:${repo}:pull&service=ghcr.io`,\n );\n if (!tokenRes.ok) return false;\n const { token } = (await tokenRes.json()) as { token?: string };\n if (!token) return false;\n const res = await fetch(`https://ghcr.io/v2/${repo}/manifests/${tag}`, {\n method: 'HEAD',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: [\n 'application/vnd.oci.image.index.v1+json',\n 'application/vnd.oci.image.manifest.v1+json',\n 'application/vnd.docker.distribution.manifest.list.v2+json',\n 'application/vnd.docker.distribution.manifest.v2+json',\n ].join(','),\n },\n });\n return res.ok;\n } catch {\n // Network trouble is not \"the tag is missing\" — let the bake surface the\n // real error rather than silently downgrading the user to a container.\n return true;\n }\n}\n\n/**\n * The image's declared environment (`ENV` in Dockerfile.box, plus PATH), read\n * from its config blob in the registry.\n *\n * A container inherits `ENV` from the image's *metadata*. A linux-vm does not:\n * the conversion turns the image into a rootfs, and metadata is not a file, so\n * every `ENV` silently disappears — `DISPLAY=:1` above all, which is why the\n * in-box browser died with \"Missing X server or $DISPLAY\" on a VM box while\n * working fine on docker and container-class daytona. (Same family as the\n * setuid-stripping the sudo repair works around.)\n *\n * Read rather than hardcoded: Dockerfile.box owns these values, and a copy here\n * would rot the first time someone adds an ENV. The config blob is a few hundred\n * bytes — no image pull.\n *\n * Returns null when the env can't be read (non-GHCR override, network trouble):\n * the caller warns and bakes anyway rather than failing the whole prepare.\n */\nexport async function fetchImageEnv(ref: string): Promise<string[] | null> {\n const m = /^ghcr\\.io\\/(.+):([^:]+)$/.exec(ref);\n if (!m) return null;\n const [, repo, tag] = m;\n const accept = [\n 'application/vnd.oci.image.index.v1+json',\n 'application/vnd.oci.image.manifest.v1+json',\n 'application/vnd.docker.distribution.manifest.list.v2+json',\n 'application/vnd.docker.distribution.manifest.v2+json',\n ].join(',');\n try {\n const tokenRes = await fetch(\n `https://ghcr.io/token?scope=repository:${repo}:pull&service=ghcr.io`,\n );\n if (!tokenRes.ok) return null;\n const { token } = (await tokenRes.json()) as { token?: string };\n if (!token) return null;\n const headers = { Authorization: `Bearer ${token}`, Accept: accept };\n\n const get = async (r: string): Promise<Record<string, unknown> | null> => {\n const res = await fetch(`https://ghcr.io/v2/${repo}/${r}`, { headers });\n return res.ok ? ((await res.json()) as Record<string, unknown>) : null;\n };\n\n let manifest = await get(`manifests/${tag}`);\n // Multi-arch index -> pick the linux/amd64 child (Daytona is x86_64 only).\n const children = manifest?.manifests as\n | Array<{ digest: string; platform?: { os?: string; architecture?: string } }>\n | undefined;\n if (children) {\n const amd64 = children.find(\n (c) => c.platform?.os === 'linux' && c.platform.architecture === 'amd64',\n );\n if (!amd64) return null;\n manifest = await get(`manifests/${amd64.digest}`);\n }\n const configDigest = (manifest?.config as { digest?: string } | undefined)?.digest;\n if (!configDigest) return null;\n const config = await get(`blobs/${configDigest}`);\n const env = (config?.config as { Env?: unknown } | undefined)?.Env;\n if (!Array.isArray(env)) return null;\n return env.filter((e): e is string => typeof e === 'string' && e.includes('='));\n } catch {\n return null;\n }\n}\n\n/**\n * Put the image's `ENV` back on disk in the VM, where a rootfs can carry it.\n *\n * Two files, because two kinds of process need it and neither reads the other's:\n * - `/etc/profile.d/` — login shells (the ssh attach, any `bash -lc`).\n * - `/etc/environment` — PAM, and it's the conventional home for these.\n *\n * The values are also handed to `create` as sandbox env vars (see the backend),\n * which is what covers plain non-login `exec` — the path `agent-browser` runs on.\n */\nexport function buildEnvRestoreCommand(env: string[]): string {\n const shQuote = (v: string): string => `'${v.replace(/'/g, `'\\\\''`)}'`;\n const profile = env\n .map((e) => {\n const i = e.indexOf('=');\n return `export ${e.slice(0, i)}=${shQuote(e.slice(i + 1))}`;\n })\n .join('\\n');\n const envFile = env.join('\\n');\n const b64 = (s: string): string => Buffer.from(`${s}\\n`, 'utf8').toString('base64');\n // base64 through a pipe: the values contain quotes and colons, and this command\n // is itself shipped through a shell.\n return (\n `printf %s '${b64(profile)}' | base64 -d | sudo tee /etc/profile.d/agentbox-image-env.sh >/dev/null && ` +\n `sudo chmod 644 /etc/profile.d/agentbox-image-env.sh && ` +\n `printf %s '${b64(envFile)}' | base64 -d | sudo tee -a /etc/environment >/dev/null`\n );\n}\n\n/** What a VM bake produced: the snapshot, and the image env it had to restore. */\nexport interface VmBaseBakeResult {\n snapshotName: string;\n /**\n * The image's `ENV`, recorded so `create` can also hand it to the sandbox.\n * The on-disk copy covers login shells; sandbox env vars cover the plain\n * non-login `exec` that `agent-browser` (and every other host-driven command)\n * runs on. Empty when the registry couldn't be read.\n */\n env: string[];\n}\n\n/**\n * Bake the linux-vm base snapshot.\n */\nexport async function bakeDaytonaVmBase(opts: VmBaseBakeOptions): Promise<VmBaseBakeResult> {\n const log = opts.onLog ?? (() => {});\n let imageEnv: string[] = [];\n const override = opts.baseImage?.trim();\n const registry = opts.registry && opts.registry.length > 0 ? opts.registry : BOX_IMAGE_REGISTRY;\n const imageRef = override || registryRefForSha(opts.dockerBaseSha, registry);\n\n // An explicit override is the user's problem to get right — if it doesn't\n // exist, Daytona's own error is clearer than a guess from us, and silently\n // downgrading them to a container would ignore what they asked for.\n if (!override && !(await ghcrTagExists(imageRef))) {\n throw new VmBaseImageUnavailableError(\n `the linux-vm base needs a published box image, and '${imageRef}' isn't in the registry.`,\n );\n }\n if (override) log(`using box.daytonaVmBaseImage override: ${imageRef}`);\n\n // Tier 1: the plain box image as a VM snapshot. Content-addressed by the\n // docker sha, so a re-bake with different agent config reuses it (this is the\n // expensive step — it pulls a ~2 GB image). An overridden image gets its own\n // name so it can't collide with a fingerprint-derived one.\n const vmBaseStem = override\n ? `agentbox-vmbase-x${sha12(override)}`\n : `agentbox-vmbase-${opts.dockerBaseSha.slice(0, 12)}`;\n\n let vmBaseName = vmBaseStem;\n if (await snapshotIsActive(opts.client, vmBaseName)) {\n log(`reusing linux-vm base image snapshot '${vmBaseName}'`);\n } else {\n vmBaseName = await createVmBaseSnapshot(opts, vmBaseStem, imageRef, log);\n }\n\n // Tier 2: boot it, provision in-place, snapshot the result.\n log('booting a throwaway sandbox to seed the base…');\n let sandbox;\n try {\n sandbox = await opts.client.create({ snapshot: vmBaseName }, { timeout: 900 });\n } catch {\n // A snapshot recreated under a recently-deleted name reports `active` but\n // cannot boot (\"Sandbox failed to start: internal error\") — Daytona's delete\n // is async and racing it corrupts the new snapshot. Nothing distinguishes\n // this from a healthy snapshot until you try to boot it, so treat a boot\n // failure as \"the base is poisoned\", rebuild under a name that has never\n // existed, and retry once.\n log(`linux-vm base '${vmBaseName}' failed to boot; rebuilding it under a fresh name…`);\n await deleteSnapshotQuietly(opts.client, vmBaseName);\n vmBaseName = await createVmBaseSnapshot(opts, `${vmBaseStem}-${nonce()}`, imageRef, log);\n sandbox = await opts.client.create({ snapshot: vmBaseName }, { timeout: 900 });\n }\n const handle: CloudHandle = { sandboxId: sandbox.id, sandboxClass: 'linux-vm' };\n try {\n // These two run BEFORE the repair, so they must stay as root. `exec`\n // otherwise drops to the box user via `sudo -n -u vscode`, and sudo is\n // exactly what is broken here: the rootfs conversion left it non-setuid, so\n // it refuses to run at all — even for root — until the repair below. Asking\n // sudo to fix sudo would deadlock the bake.\n const asRoot = { user: 'root' } as const;\n const wait = await opts.backend.exec(handle, buildDockerWaitCommand(), asRoot);\n if (wait.exitCode !== 0) {\n throw new Error(\n 'dockerd never came up in the VM base, so sudo cannot be repaired ' +\n '(the repair borrows root from the docker socket).',\n );\n }\n log('repairing sudo (the VM rootfs conversion strips setuid bits)…');\n const repair = await opts.backend.exec(handle, buildSudoRepairCommand(), asRoot);\n if (repair.exitCode !== 0) {\n throw new Error(\n `failed to restore sudo in the VM base (exit ${String(repair.exitCode)}): ` +\n `${repair.stdout}${repair.stderr}`,\n );\n }\n\n // The conversion drops the image's ENV along with the setuid bits. Put it\n // back on disk (needs the sudo we just repaired). Without it a VM box has no\n // DISPLAY, and the in-box browser dies with \"Missing X server or $DISPLAY\".\n imageEnv = (await fetchImageEnv(imageRef)) ?? [];\n if (imageEnv.length > 0) {\n log(\n `restoring the image's ${String(imageEnv.length)} env vars (the VM conversion drops them)…`,\n );\n const envFix = await opts.backend.exec(handle, buildEnvRestoreCommand(imageEnv));\n if (envFix.exitCode !== 0) {\n throw new Error(\n `failed to restore the image environment in the VM base (exit ${String(envFix.exitCode)}): ` +\n `${envFix.stdout}${envFix.stderr}`,\n );\n }\n } else {\n log(\n `warning: could not read the environment of '${imageRef}' from the registry — ` +\n `a VM box may come up without DISPLAY (no in-box browser).`,\n );\n }\n\n await seedAgentStaticIntoCloudBox(opts.backend, handle, {\n hostWorkspace: opts.hostWorkspace,\n claudeMdOverlay: opts.claudeMdOverlay,\n onLog: log,\n });\n\n // Cold snapshot: filesystem only, and Daytona requires the sandbox STOPPED.\n // It does not stop for you.\n log('stopping the sandbox to capture a cold snapshot…');\n await sandbox.stop();\n // Never reuse a name (see the boot-failure comment above): a re-bake gets a\n // fresh one and the snapshot it replaces is deleted afterwards. The name\n // doesn't need to be deterministic — prepared state records whatever we\n // pinned, and that's what the skip-rebuild check reads.\n const finalName = `${opts.snapshotName}-${nonce()}`;\n log(`capturing base snapshot '${finalName}'…`);\n await sandbox._experimental_createSnapshot(finalName, 900);\n await waitForSnapshotActive(opts.client, finalName);\n log(`snapshot '${finalName}' is active`);\n return { snapshotName: finalName, env: imageEnv };\n } finally {\n // Always reap the throwaway — an orphan VM bills by the hour.\n try {\n await sandbox.delete(120);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n log(`warning: could not delete the temporary bake sandbox ${sandbox.id}: ${msg}`);\n }\n }\n}\n\n/** Stable 12-hex digest of an image ref, for a collision-free snapshot name. */\nfunction sha12(s: string): string {\n return createHash('sha256').update(s).digest('hex').slice(0, 12);\n}\n\n/** Short, monotonic, never-reused token for a snapshot name. */\nfunction nonce(): string {\n return Math.floor(Date.now() / 1000).toString(36);\n}\n\nasync function createVmBaseSnapshot(\n opts: VmBaseBakeOptions,\n name: string,\n imageRef: string,\n log: (line: string) => void,\n): Promise<string> {\n log(`creating linux-vm base image snapshot '${name}' from ${imageRef}…`);\n try {\n await opts.client.snapshot.create(\n {\n name,\n image: imageRef,\n sandboxClass: SandboxClass.LINUX_VM,\n regionId: opts.regionId,\n // Always explicit: a snapshot with no `resources` gets Daytona's 1 vCPU /\n // 1 GiB / 3 GiB default, and the box image does not fit in 3 GiB — the\n // build dies mid-pull with a bare \"internal error\".\n resources: opts.resources ?? { cpu: 2, memory: 4, disk: 8 },\n },\n { onLogs: (c: string) => log(String(c).split('\\n').filter(Boolean).join(' ')) },\n );\n } catch (err) {\n if (isRegionNotFound(err)) {\n throw new Error(vmRegionUnavailableMessage(opts.regionId));\n }\n throw err;\n }\n return name;\n}\n\n/**\n * Daytona's \"region not found\" for the region the linux-vm class requires.\n *\n * `us-east-1` is a *dedicated* region, so it exists only for organizations that\n * have one provisioned — every other account sees just the shared `us`/`eu`.\n * The raw SDK error is a bare `DaytonaNotFoundError` with a stack, which reads\n * as \"AgentBox is broken\" rather than \"this class needs a region your org does\n * not have\".\n *\n * Match on the two words, NOT on `Region <id> not found`: the API returns the id\n * for some regions and a bare `Region not found` for others (both observed on\n * 2026-08-29, same SDK, different keys), so pinning the id let the bare form\n * fall through to the stack trace this exists to replace. `region` + `not found`\n * together still can't collide with the neighbouring `Snapshot not found`.\n */\nexport function isRegionNotFound(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err);\n return /\\bregion\\b/i.test(msg) && /\\bnot found\\b/i.test(msg);\n}\n\n/**\n * Name the real constraint, and do NOT dress the container class up as the fix.\n *\n * `box.daytonaClass=container` is the only other value, but container sandboxes\n * support neither snapshots nor base images, so a user sent down that path gets\n * a Daytona that cannot bake or checkpoint — a worse dead end than this error,\n * reached one long bake later. The honest answer is that this provider needs an\n * organization with a VM region.\n *\n * `curl -H \"Authorization: Bearer $DAYTONA_API_KEY\" https://app.daytona.io/api/regions`\n * is the check for what an account actually has; the SDK exposes no region API,\n * so we point at the endpoint rather than guessing.\n */\nexport function vmRegionUnavailableMessage(regionId: string): string {\n return (\n `your Daytona organization has no '${regionId}' region, and linux-vm boxes run only there.\\n` +\n ` A VM region is *dedicated* — it is not enabled for every account — so a key from an\\n` +\n ` organization with only the shared 'us'/'eu' regions cannot bake a Daytona base at all.\\n` +\n ` Check what yours has:\\n` +\n ` curl -H \"Authorization: Bearer $DAYTONA_API_KEY\" https://app.daytona.io/api/regions\\n` +\n ` Use an API key from an organization that has a VM region (or ask Daytona to enable one). If\\n` +\n ` Daytona has since added a VM region for your org, name it with\\n` +\n ` \\`agentbox config set box.daytonaRegion <id>\\`.`\n );\n}\n\nasync function snapshotIsActive(client: Daytona, name: string): Promise<boolean> {\n try {\n const snap = await client.snapshot.get(name);\n return snap?.state === 'active';\n } catch {\n return false;\n }\n}\n\n/** Best-effort delete — used to reap a superseded or poisoned snapshot. */\nexport async function deleteSnapshotQuietly(client: Daytona, name: string): Promise<void> {\n try {\n const snap = await client.snapshot.get(name);\n await client.snapshot.delete(snap);\n } catch {\n /* already gone, or never existed */\n }\n}\n","/**\n * Doctor probes + normalized credential status for the daytona provider,\n * assembled into `providerModule` in `index.ts`. Moved out of apps/cli so the\n * CLI dispatches to it generically (see `@agentbox/sandbox-core`'s `ProviderModule`).\n */\n\nimport { loadEffectiveConfig, resolveDaytonaClass } from '@agentbox/config';\nimport { errSummary, type CheckResult, type CredStatusSummary } from '@agentbox/sandbox-core';\nimport { parseDaytonaSize } from './backend.js';\nimport { readPreparedDaytonaState } from './prepared-state.js';\nimport { getDaytonaStatus, hasDaytonaCredentials } from './status.js';\n\nexport function readCredStatusSummary(): CredStatusSummary {\n // Credentials only — no network. This runs in the install wizard's provider\n // step just to answer \"logged in?\", and it used to fetch the whole snapshot +\n // volume inventory to do it.\n return { configured: hasDaytonaCredentials().configured };\n}\n\nexport async function doctorChecks(): Promise<CheckResult[]> {\n try {\n // Snapshots only: the rows below render the snapshot count and nothing else,\n // so the volume list was a second API round-trip whose result was discarded.\n const status = await getDaytonaStatus({ volumes: false });\n if (!status.configured) {\n return [\n {\n label: 'credentials',\n status: 'warn',\n // The SDK's reason is a paragraph (env-var enumeration) — doctor just\n // needs the vercel/e2b-style one-liner; `prepare --status` keeps it.\n detail: 'not configured',\n hint: '`agentbox daytona login`',\n },\n ];\n }\n const credRes: CheckResult = { label: 'credentials', status: 'ok', detail: 'configured' };\n return [credRes, await baseSnapshotCheck(status.snapshots.length)];\n } catch (err) {\n return [{ label: 'credentials', status: 'warn', detail: errSummary(err) }];\n }\n}\n\n/**\n * A snapshot existing isn't enough: a snapshot's class is immutable and can only\n * create sandboxes of that same class, so a container base with\n * `box.daytonaClass: linux-vm` configured is unusable — every create would fail.\n * Counting snapshots would report that as healthy, so compare the class too.\n */\nasync function baseSnapshotCheck(snapshotCount: number): Promise<CheckResult> {\n if (snapshotCount === 0) {\n return {\n label: 'base snapshot',\n status: 'warn',\n detail: 'none',\n hint: '`agentbox prepare --provider daytona`',\n };\n }\n const prepared = readPreparedDaytonaState();\n // Absent `class` = a snapshot baked before classes existed, which was\n // necessarily a container.\n const bakedClass = prepared?.base ? (prepared.extras?.class ?? 'container') : undefined;\n\n let wantClass: string | undefined;\n try {\n wantClass = resolveDaytonaClass((await loadEffectiveConfig(process.cwd())).effective);\n } catch {\n // No project config to read (e.g. doctor run outside a project) — the count\n // is still worth reporting; just don't claim anything about the class.\n }\n\n if (bakedClass && wantClass && bakedClass !== wantClass) {\n return {\n label: 'base snapshot',\n status: 'warn',\n detail: `baked as '${bakedClass}' but box.daytonaClass is '${wantClass}' — creates will fail`,\n hint: '`agentbox prepare --provider daytona --force`',\n };\n }\n return {\n label: 'base snapshot',\n status: 'ok',\n detail: `${String(snapshotCount)} agentbox snapshot(s)${bakedClass ? ` (base: ${bakedClass})` : ''}`,\n };\n}\n\n/**\n * Daytona fixes resources when the SNAPSHOT is baked and rejects them on the\n * create call (`backend.ts` deletes `resources` on the snapshot path), so a\n * size that disagrees with the bake is discarded. Same comparison the backend\n * makes at provision — kept in step so the two can't drift.\n */\nexport function sizeIgnoredReason(size: string): string | null {\n const parsed = parseDaytonaSize(size);\n // A foreign spec (a hetzner server type sitting in the generic `box.size`)\n // isn't ours to judge — `prepare` surfaces that. Stay quiet.\n if (!parsed) return null;\n const requested = `${String(parsed.cpu)}-${String(parsed.memory)}-${String(parsed.disk)}`;\n const prepared = readPreparedDaytonaState();\n // Nothing baked yet: `prepare` will bake AT this size, so there is no\n // mismatch to report. Warning here would tell a first-run user their brand\n // new setting is ignored, which is the opposite of true.\n if (!prepared?.base) return null;\n // `effectiveSize` names real numbers even for a default bake; `size` (the\n // requested spec) is the fallback for snapshots baked before it was recorded.\n const baked = prepared.extras?.effectiveSize ?? prepared.extras?.size;\n if (requested === baked) return null;\n return (\n `daytona: size '${requested}' is ignored on the snapshot path; this snapshot was baked at ` +\n `${baked ?? 'the default size'}. Daytona resources are fixed at bake time — re-bake with ` +\n `\\`agentbox prepare --provider daytona --size ${requested} --force\\` to change them.`\n );\n}\n","/**\n * Read-only status helpers for `agentbox prepare` (no-args mode). Surfaces\n * the user-facing inventory of agentbox-owned base images / snapshots /\n * volumes on the configured Daytona org so the user can see at a glance\n * what's already prepared and what isn't.\n *\n * Daytona-side state lives in two places:\n * - **Snapshots** — built by `agentbox prepare --provider daytona`. Listed\n * filtered to `agentbox*` so we don't surface unrelated org snapshots.\n * - **Volumes** — the per-org `agentbox-credentials` volume created lazily\n * by `ensureAgentVolumesForCloud` on first `agentbox create --provider\n * daytona`.\n *\n * All calls swallow auth/network errors and return an empty section — the\n * status command must work for users who don't have Daytona configured.\n */\n\nimport { ensureDaytonaEnvLoaded } from './env-loader.js';\nimport { getClient } from './backend.js';\n\nexport interface DaytonaSnapshotSummary {\n name: string;\n state?: string;\n /** Snapshot size in GB, as reported by Daytona (may be undefined for non-`active` states). */\n sizeGb?: number;\n createdAt?: string;\n errorReason?: string;\n}\n\nexport interface DaytonaVolumeSummary {\n name: string;\n id: string;\n state?: string;\n createdAt?: string;\n lastUsedAt?: string;\n}\n\nexport interface DaytonaStatus {\n /** True when Daytona credentials are present + the SDK could connect. */\n configured: boolean;\n /** Snapshots whose name starts with `agentbox` (case-insensitive). */\n snapshots: DaytonaSnapshotSummary[];\n /** Volumes whose name starts with `agentbox` (case-insensitive). */\n volumes: DaytonaVolumeSummary[];\n /** Non-fatal explanation when `configured` is false. */\n reason?: string;\n}\n\nfunction isAgentboxName(name: unknown): boolean {\n return typeof name === 'string' && name.toLowerCase().startsWith('agentbox');\n}\n\n/**\n * Upper bound on a status list call. This is a *diagnostic* read — a hung API\n * must degrade to \"couldn't list\" rather than stall the caller. `doctor` in\n * particular prints no spinner, so an unbounded await just looks like a freeze.\n * Mirrors the bound the cloud-state probes already use host-side.\n */\nconst STATUS_PROBE_TIMEOUT_MS = 8000;\n\nfunction withStatusTimeout<T>(p: Promise<T>, what: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const t = setTimeout(\n () => reject(new Error(`${what} timed out after ${String(STATUS_PROBE_TIMEOUT_MS)}ms`)),\n STATUS_PROBE_TIMEOUT_MS,\n );\n // The SDK call keeps running; we just stop waiting on it. unref so a pending\n // timer can't hold the process open after the CLI is done.\n t.unref?.();\n p.then(\n (v) => {\n clearTimeout(t);\n resolve(v);\n },\n (e: unknown) => {\n clearTimeout(t);\n reject(e instanceof Error ? e : new Error(String(e)));\n },\n );\n });\n}\n\n/**\n * Are Daytona credentials present? Credential-only: constructs the SDK client\n * (which throws when no key/JWT is configured) and makes **no network call**.\n *\n * This is what `configured` in {@link DaytonaStatus} has always meant — the\n * status helper sets it as soon as the client is built, before any list. Callers\n * that only want that answer (the install wizard's provider picker, doctor's\n * \"credentials\" row) should ask here rather than pay for two API round-trips.\n */\nexport function hasDaytonaCredentials(): { configured: boolean; reason?: string } {\n try {\n ensureDaytonaEnvLoaded();\n getClient();\n return { configured: true };\n } catch (err) {\n return {\n configured: false,\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n}\n\nexport interface DaytonaStatusOptions {\n /**\n * Fetch the volume list. Each list is a separate round-trip to the Daytona\n * API, and `doctor` renders only the snapshot count — so it asks for snapshots\n * alone and halves the network cost of the check. `prepare --status`, which\n * prints the volume inventory, leaves this on. Default true (the full picture).\n */\n volumes?: boolean;\n}\n\n/**\n * Collect a read-only summary of agentbox-owned snapshots + volumes on the\n * Daytona org. Never throws — failure paths return `configured: false` with\n * a one-line reason.\n *\n * Only reaches the network when credentials are present: with no key `getClient()`\n * throws and we return `configured: false` before any request — so an unconfigured\n * machine pays nothing.\n */\nexport async function getDaytonaStatus(opts: DaytonaStatusOptions = {}): Promise<DaytonaStatus> {\n const wantVolumes = opts.volumes !== false;\n try {\n ensureDaytonaEnvLoaded();\n } catch (err) {\n return {\n configured: false,\n snapshots: [],\n volumes: [],\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n\n let client;\n try {\n client = getClient();\n } catch (err) {\n return {\n configured: false,\n snapshots: [],\n volumes: [],\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n\n const snapshots: DaytonaSnapshotSummary[] = [];\n const volumes: DaytonaVolumeSummary[] = [];\n const reasons: string[] = [];\n\n // Both lists are independent round-trips; issue them together rather than\n // back to back. Each is bounded — an unreachable/slow Daytona must degrade to\n // \"couldn't list\" rather than hang `doctor` (which has no spinner at all, so a\n // stall just looks like a freeze).\n const listSnapshots = async (): Promise<void> => {\n try {\n const list = await withStatusTimeout(client.snapshot.list(), 'snapshot list');\n const items = (list as { items?: unknown[] }).items ?? (Array.isArray(list) ? list : []);\n for (const s of items) {\n const dto = s as { name?: unknown; state?: unknown; size?: unknown; createdAt?: unknown; errorReason?: unknown };\n if (!isAgentboxName(dto.name)) continue;\n snapshots.push({\n name: dto.name as string,\n state: typeof dto.state === 'string' ? dto.state : undefined,\n sizeGb: typeof dto.size === 'number' ? dto.size : undefined,\n createdAt: typeof dto.createdAt === 'string' ? dto.createdAt : undefined,\n errorReason: typeof dto.errorReason === 'string' ? dto.errorReason : undefined,\n });\n }\n } catch (err) {\n reasons.push(\n `snapshot list failed: ${err instanceof Error ? err.message.split('\\n')[0] : String(err)}`,\n );\n }\n };\n\n const listVolumes = async (): Promise<void> => {\n try {\n const list = await withStatusTimeout(client.volume.list(), 'volume list');\n const items: unknown[] = Array.isArray(list)\n ? list\n : ((list as { items?: unknown[] }).items ?? []);\n for (const v of items) {\n const dto = v as { name?: unknown; id?: unknown; state?: unknown; createdAt?: unknown; lastUsedAt?: unknown };\n if (!isAgentboxName(dto.name)) continue;\n volumes.push({\n name: dto.name as string,\n id: typeof dto.id === 'string' ? dto.id : '',\n state: typeof dto.state === 'string' ? dto.state : undefined,\n createdAt: typeof dto.createdAt === 'string' ? dto.createdAt : undefined,\n lastUsedAt: typeof dto.lastUsedAt === 'string' ? dto.lastUsedAt : undefined,\n });\n }\n } catch (err) {\n reasons.push(\n `volume list failed: ${err instanceof Error ? err.message.split('\\n')[0] : String(err)}`,\n );\n }\n };\n\n await Promise.all(wantVolumes ? [listSnapshots(), listVolumes()] : [listSnapshots()]);\n const reason = reasons.length > 0 ? reasons.join('; ') : undefined;\n\n return {\n configured: true,\n snapshots: snapshots.sort((a, b) => (b.createdAt ?? '').localeCompare(a.createdAt ?? '')),\n volumes: volumes.sort((a, b) => a.name.localeCompare(b.name)),\n reason,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEsBA,SAAS,cAAc,aAAa,cAAc,QAAQ,qBAAqB;AAC/E,SAAS,cAAc;AACvB,SAAS,SAAS,YAAY;AAC9B,SAAS,aAAa;ACQtB,SAAS,kBAAkB;AAG3B,SAAS,oBAAoB;AFF7B,IAAM,eAAe;AAEd,SAAS,sBAAsBA,gBAA6C;AACjF,SAAO;IACL,MAAM,OAAO,KAAgB,MAAc;AACzC,UAAI,CAAC,IAAI,aAAa;AACpB,cAAM,IAAI;UACR;QACF;MACF;AACA,YAAM,YAAY,IAAI,OAAO;AAC7B,UAAI,CAAC,WAAW;AACd,cAAM,IAAI,MAAM,eAAe,IAAI,IAAI,8CAAyC;MAClF;AACA,YAAM,SAAS,EAAE,WAAW,cAAc,IAAI,OAAO,aAAa;AAElE,YAAM,e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,GAAG;EACH,SAAS;;;;EAIT,YAAY,sBAAsB,aAAa;EAC/C,iBAAiB,CAAC,kBAAkB,kCAAkC,aAAa;AACrF;AAGO,IAAM,iBAAiC;EAC5C,UAAU;EACV,SAAS;EACT,mBAAmB;EACnB,gBAAgB;EAChB,gBAAgB;EAChB,4BAA4B,CAAC,kBAAkB,kCAAkC,aAAa;EAC9F;EACA;AACF;","names":["cloudProvider"]}
|
|
@@ -48,8 +48,8 @@ import {
|
|
|
48
48
|
validateServerChoice,
|
|
49
49
|
withHetznerRetry,
|
|
50
50
|
writePreparedState
|
|
51
|
-
} from "./chunk-
|
|
52
|
-
import "./chunk-
|
|
51
|
+
} from "./chunk-5NVHJS7D.js";
|
|
52
|
+
import "./chunk-JLVUNDUB.js";
|
|
53
53
|
import "./chunk-I2DEYQLZ.js";
|
|
54
54
|
import "./chunk-THKVKVRF.js";
|
|
55
55
|
import "./chunk-CZPVVFCF.js";
|
|
@@ -122,4 +122,4 @@ export {
|
|
|
122
122
|
withHetznerRetry,
|
|
123
123
|
writePreparedState
|
|
124
124
|
};
|
|
125
|
-
//# sourceMappingURL=dist-
|
|
125
|
+
//# sourceMappingURL=dist-JSEXGLYK.js.map
|
|
@@ -70,7 +70,7 @@ import {
|
|
|
70
70
|
verifyDetachedSession,
|
|
71
71
|
writeCloudCheckpointManifest,
|
|
72
72
|
writePreparedToCustodyStore
|
|
73
|
-
} from "./chunk-
|
|
73
|
+
} from "./chunk-JLVUNDUB.js";
|
|
74
74
|
import {
|
|
75
75
|
CODEX_CREDENTIALS_BACKUP_FILE,
|
|
76
76
|
CREDENTIALS_BACKUP_FILE,
|
|
@@ -210,4 +210,4 @@ export {
|
|
|
210
210
|
writeCloudCheckpointManifest,
|
|
211
211
|
writePreparedToCustodyStore
|
|
212
212
|
};
|
|
213
|
-
//# sourceMappingURL=dist-
|
|
213
|
+
//# sourceMappingURL=dist-RWFKW4IU.js.map
|
|
@@ -34,8 +34,8 @@ import {
|
|
|
34
34
|
vercelBackend,
|
|
35
35
|
vercelProvider,
|
|
36
36
|
writePreparedState
|
|
37
|
-
} from "./chunk-
|
|
38
|
-
import "./chunk-
|
|
37
|
+
} from "./chunk-TPHSVKMX.js";
|
|
38
|
+
import "./chunk-JLVUNDUB.js";
|
|
39
39
|
import "./chunk-I2DEYQLZ.js";
|
|
40
40
|
import "./chunk-THKVKVRF.js";
|
|
41
41
|
import "./chunk-CZPVVFCF.js";
|
|
@@ -81,4 +81,4 @@ export {
|
|
|
81
81
|
vercelProvider,
|
|
82
82
|
writePreparedState
|
|
83
83
|
};
|
|
84
|
-
//# sourceMappingURL=dist-
|
|
84
|
+
//# sourceMappingURL=dist-XV77P3RW.js.map
|
|
@@ -31,7 +31,7 @@ import {
|
|
|
31
31
|
renderInnerCommand,
|
|
32
32
|
resolveCloudCheckpoint,
|
|
33
33
|
writeCloudCheckpointManifest
|
|
34
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-JLVUNDUB.js";
|
|
35
35
|
import "./chunk-I2DEYQLZ.js";
|
|
36
36
|
import "./chunk-THKVKVRF.js";
|
|
37
37
|
import "./chunk-CZPVVFCF.js";
|
|
@@ -847,4 +847,4 @@ export {
|
|
|
847
847
|
updatePreparedState,
|
|
848
848
|
writePreparedState
|
|
849
849
|
};
|
|
850
|
-
//# sourceMappingURL=dist-
|
|
850
|
+
//# sourceMappingURL=dist-Y2GCMA6N.js.map
|
|
@@ -3,25 +3,25 @@ import {
|
|
|
3
3
|
describeRemoteHubBuild,
|
|
4
4
|
hubCommand,
|
|
5
5
|
resolveHubTarget
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-F77AZT2M.js";
|
|
7
7
|
import "./chunk-AUHYXXCA.js";
|
|
8
|
-
import "./chunk-
|
|
8
|
+
import "./chunk-SXXN7JOC.js";
|
|
9
9
|
import "./chunk-PAWAGULH.js";
|
|
10
|
-
import "./chunk-
|
|
11
|
-
import "./chunk-
|
|
12
|
-
import "./chunk-
|
|
10
|
+
import "./chunk-ZCHWZYIN.js";
|
|
11
|
+
import "./chunk-JTYWZJIU.js";
|
|
12
|
+
import "./chunk-5I7IFACI.js";
|
|
13
13
|
import "./chunk-VPBE72HG.js";
|
|
14
14
|
import "./chunk-WHFCJBMO.js";
|
|
15
|
-
import "./chunk-
|
|
15
|
+
import "./chunk-LEVYTABB.js";
|
|
16
16
|
import "./chunk-5F34YIRI.js";
|
|
17
17
|
import "./chunk-WDBDFLH3.js";
|
|
18
18
|
import "./chunk-6YSYQZRH.js";
|
|
19
|
-
import "./chunk-
|
|
20
|
-
import "./chunk-
|
|
21
|
-
import "./chunk-
|
|
19
|
+
import "./chunk-5NVHJS7D.js";
|
|
20
|
+
import "./chunk-TPHSVKMX.js";
|
|
21
|
+
import "./chunk-JLVUNDUB.js";
|
|
22
22
|
import "./chunk-I2DEYQLZ.js";
|
|
23
23
|
import "./chunk-THKVKVRF.js";
|
|
24
|
-
import "./chunk-
|
|
24
|
+
import "./chunk-P5A6MT75.js";
|
|
25
25
|
import "./chunk-CZPVVFCF.js";
|
|
26
26
|
import "./chunk-XENTK32L.js";
|
|
27
27
|
import "./chunk-7LNXTPEE.js";
|
|
@@ -34,4 +34,4 @@ export {
|
|
|
34
34
|
hubCommand,
|
|
35
35
|
resolveHubTarget
|
|
36
36
|
};
|
|
37
|
-
//# sourceMappingURL=hub-
|
|
37
|
+
//# sourceMappingURL=hub-53E6EFZB.js.map
|
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
controlBoxIsThisMachine
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-FCMBVJFQ.js";
|
|
5
5
|
import {
|
|
6
6
|
controlBoxKnowsHost
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-OUOV4OM2.js";
|
|
8
8
|
import "./chunk-VPBE72HG.js";
|
|
9
9
|
import {
|
|
10
10
|
getHostAlias,
|
|
11
11
|
removeHostAlias,
|
|
12
12
|
upsertHostAlias
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-MS4NWRXN.js";
|
|
14
14
|
import "./chunk-WHFCJBMO.js";
|
|
15
15
|
import {
|
|
16
16
|
readDeployRecord
|
|
17
|
-
} from "./chunk-
|
|
18
|
-
import "./chunk-
|
|
19
|
-
import "./chunk-
|
|
17
|
+
} from "./chunk-LEVYTABB.js";
|
|
18
|
+
import "./chunk-5NVHJS7D.js";
|
|
19
|
+
import "./chunk-JLVUNDUB.js";
|
|
20
20
|
import "./chunk-I2DEYQLZ.js";
|
|
21
21
|
import "./chunk-THKVKVRF.js";
|
|
22
22
|
import "./chunk-CZPVVFCF.js";
|
|
@@ -83,4 +83,4 @@ export {
|
|
|
83
83
|
ensureHubDockerTarget,
|
|
84
84
|
removeHubDockerTarget
|
|
85
85
|
};
|
|
86
|
-
//# sourceMappingURL=hub-docker-target-
|
|
86
|
+
//# sourceMappingURL=hub-docker-target-CS5XHSSA.js.map
|