@madarco/agentbox 0.23.2 → 0.23.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/dist/{_cloud-attach-LP5CIO7S.js → _cloud-attach-BQRWX3J2.js} +3 -3
- package/dist/chunk-G3H2L3O2.js +0 -0
- package/dist/chunk-GGRZ3GZO.js +0 -0
- package/dist/{chunk-C47ZA42C.js → chunk-I6ZRWTPR.js} +25 -3
- package/dist/chunk-I6ZRWTPR.js.map +1 -0
- package/dist/{chunk-AGSLJ3NE.js → chunk-LA4JMS27.js} +10 -2
- package/dist/{chunk-AGSLJ3NE.js.map → chunk-LA4JMS27.js.map} +1 -1
- package/dist/chunk-LK2JT2OO.js +0 -0
- package/dist/chunk-LSQXT5WZ.js +0 -0
- package/dist/{chunk-J3GSZ33V.js → chunk-QEQFZLYR.js} +7 -7
- package/dist/chunk-QT3SHMLY.js +0 -0
- package/dist/{chunk-7D7K4UXW.js → chunk-SFA57TGX.js} +3 -3
- package/dist/{chunk-TZLNJBIM.js → chunk-W3FQPFP7.js} +2 -2
- package/dist/chunk-WJFZJZIM.js +0 -0
- package/dist/cloud-poller-SUNA6ZQC-7M5LJHHE.js +0 -0
- package/dist/dist-2BTJQUJS.js +0 -0
- package/dist/{dist-VMR6UEP2.js → dist-CUKBKS3N.js} +4 -4
- package/dist/{dist-HENU2IVK.js → dist-FXQFTT75.js} +3 -3
- package/dist/{dist-UIOWLT3C.js → dist-QO4CTLAX.js} +4 -4
- package/dist/{dist-OTSXYV6X.js → dist-V235KVEX.js} +3 -3
- package/dist/{dist-NUZ2RMOP.js → dist-Z2NEVV55.js} +4 -2
- package/dist/index.js +44 -53
- package/dist/index.js.map +1 -1
- package/dist/prepared-state-BUO75YLZ-CDTISC2C.js +0 -0
- package/package.json +28 -27
- package/runtime/_shared/agentbox-checkpoint-cleanup +0 -0
- package/runtime/_shared/agentbox-dockerd-start +0 -0
- package/runtime/_shared/agentbox-open +0 -0
- package/runtime/_shared/agentbox-portless-trust +0 -0
- package/runtime/_shared/agentbox-vnc-start +0 -0
- package/runtime/_shared/ctl.cjs +0 -0
- package/runtime/_shared/gh-shim +0 -0
- package/runtime/_shared/git-shim +0 -0
- package/runtime/_shared/linear-shim +0 -0
- package/runtime/_shared/ntn-shim +0 -0
- package/runtime/docker/packages/ctl/dist/bin.cjs +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-dockerd-start +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-open +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-portless-trust +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-sshd-start +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-vnc-start +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/chromium-resolver +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/gh-shim +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/git-shim +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/linear-shim +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/ntn-shim +0 -0
- package/runtime/e2b/agentbox-checkpoint-cleanup +0 -0
- package/runtime/e2b/agentbox-dockerd-start +0 -0
- package/runtime/e2b/agentbox-open +0 -0
- package/runtime/e2b/agentbox-vnc-start +0 -0
- package/runtime/e2b/ctl.cjs +0 -0
- package/runtime/e2b/gh-shim +0 -0
- package/runtime/e2b/git-shim +0 -0
- package/runtime/e2b/linear-shim +0 -0
- package/runtime/e2b/ntn-shim +0 -0
- package/runtime/e2b/scripts/build-template.sh +0 -0
- package/runtime/hetzner/agentbox-checkpoint-cleanup +0 -0
- package/runtime/hetzner/agentbox-dockerd-start +0 -0
- package/runtime/hetzner/agentbox-open +0 -0
- package/runtime/hetzner/agentbox-portless-trust +0 -0
- package/runtime/hetzner/agentbox-vnc-start +0 -0
- package/runtime/hetzner/ctl.cjs +0 -0
- package/runtime/hetzner/gh-shim +0 -0
- package/runtime/hetzner/git-shim +0 -0
- package/runtime/hetzner/linear-shim +0 -0
- package/runtime/hetzner/ntn-shim +0 -0
- package/runtime/hetzner/scripts/install-box.sh +0 -0
- 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/(auth)/signin/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- 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/app/_not-found/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bqbkd5._.js +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qa4a0v._.js +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/{09xn_next_dist_0iwlo01._.js → 09xn_next_dist_1uccfbf._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0vdzfiw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/{[root-of-the-server]__0cpdgd0._.js → [root-of-the-server]__1bd_5o3._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_boxes_[id]_page_tsx_1-j_972._.js +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/.next/static/chunks/000a1sa7te1h8.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/20hq7-0depjid.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/3dfjrxx-dy644.css +3 -0
- package/runtime/hub/apps/hub/{chunk-TS3DHXYG.js → chunk-2Z74R6ZT.js} +9 -1
- package/runtime/hub/apps/hub/{chunk-5C7T5LX3.js → chunk-AR7CEZ2G.js} +24 -2
- package/runtime/hub/apps/hub/{dist-3ILQQGCH.js → dist-LNHEG5P4.js} +2 -2
- package/runtime/hub/apps/hub/{dist-CJHZ37LW.js → dist-LZNRLUYY.js} +2 -2
- package/runtime/hub/apps/hub/{dist-PKOFN4OD.js → dist-Q6G66Z57.js} +2 -2
- package/runtime/hub/apps/hub/{dist-WRKJHF6W.js → dist-SD4G36EP.js} +2 -2
- package/runtime/hub/apps/hub/{dist-6R5YPL5S.js → dist-VV6Z2CQX.js} +3 -1
- package/runtime/hub/apps/hub/package.json +1 -0
- package/runtime/hub/apps/hub/server.js +22 -9
- package/runtime/relay/bin.cjs +0 -0
- package/runtime/vercel/agentbox-checkpoint-cleanup +0 -0
- package/runtime/vercel/agentbox-dockerd-start +0 -0
- package/runtime/vercel/agentbox-open +0 -0
- package/runtime/vercel/agentbox-vnc-start +0 -0
- package/runtime/vercel/ctl.cjs +0 -0
- package/runtime/vercel/gh-shim +0 -0
- package/runtime/vercel/git-shim +0 -0
- package/runtime/vercel/linear-shim +0 -0
- package/runtime/vercel/ntn-shim +0 -0
- package/runtime/vercel/scripts/provision.sh +0 -0
- package/LICENSE +0 -21
- package/dist/chunk-C47ZA42C.js.map +0 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1bq2f8q._.js +0 -3
- package/runtime/hub/apps/hub/.next/static/chunks/1py5tlz57h7ra.js +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/3rm29i8e-lb25.css +0 -3
- /package/dist/{_cloud-attach-LP5CIO7S.js.map → _cloud-attach-BQRWX3J2.js.map} +0 -0
- /package/dist/{chunk-J3GSZ33V.js.map → chunk-QEQFZLYR.js.map} +0 -0
- /package/dist/{chunk-7D7K4UXW.js.map → chunk-SFA57TGX.js.map} +0 -0
- /package/dist/{chunk-TZLNJBIM.js.map → chunk-W3FQPFP7.js.map} +0 -0
- /package/dist/{dist-NUZ2RMOP.js.map → dist-CUKBKS3N.js.map} +0 -0
- /package/dist/{dist-HENU2IVK.js.map → dist-FXQFTT75.js.map} +0 -0
- /package/dist/{dist-UIOWLT3C.js.map → dist-QO4CTLAX.js.map} +0 -0
- /package/dist/{dist-OTSXYV6X.js.map → dist-V235KVEX.js.map} +0 -0
- /package/dist/{dist-VMR6UEP2.js.map → dist-Z2NEVV55.js.map} +0 -0
- /package/runtime/hub/apps/hub/.next/static/{W7Oc_BUsChvL4rrhfKZRY → eVq-z4zld_8DGQudbYogV}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{W7Oc_BUsChvL4rrhfKZRY → eVq-z4zld_8DGQudbYogV}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{W7Oc_BUsChvL4rrhfKZRY → eVq-z4zld_8DGQudbYogV}/_ssgManifest.js +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/sandbox-cloud/src/cloud-provider.ts","../../../packages/sandbox-cloud/src/sync/cloud-sync.ts","../../../packages/sandbox-cloud/src/sync/workspace-resync.ts","../../../packages/sandbox-cloud/src/shell.ts","../../../packages/sandbox-cloud/src/sync/agent-credentials.ts","../../../packages/sandbox-cloud/src/sync/sync-transport.ts","../../../packages/sandbox-cloud/src/sync/dynamic-sync.ts","../../../packages/sandbox-cloud/src/sync/codex-agents-override.ts","../../../packages/sandbox-cloud/src/sync/claude-json-overlay.ts","../../../packages/sandbox-cloud/src/sync/git-identity.ts","../../../packages/sandbox-cloud/src/sync/env-files.ts","../../../packages/sandbox-cloud/src/sync/carry.ts","../../../packages/sandbox-cloud/src/checkpoint.ts","../../../packages/sandbox-cloud/src/snapshot-error.ts","../../../packages/sandbox-cloud/src/expose-ports.ts","../../../packages/sandbox-cloud/src/cloud-cp.ts","../../../packages/sandbox-cloud/src/bootstrap-launch.ts","../../../packages/sandbox-cloud/src/plane-register.ts","../../../packages/sandbox-cloud/src/sync/workspace-seed.ts","../../../packages/sandbox-cloud/src/mock-backend.ts","../../../packages/sandbox-cloud/src/index.ts"],"sourcesContent":["/**\n * `createCloudProvider(backend)` — composes a full `Provider` from a thin\n * `CloudBackend`. Every cloud backend (Daytona, future Vercel, …) reuses this\n * scaffolding instead of re-implementing workspace seeding, ctl launch, state\n * persistence, URL resolution, etc.\n *\n * v0 covers create / lifecycle / probe / exec / resolveUrl on top of the\n * `CloudBackend` primitives. The host-poller comms layer (queued git.push,\n * status event mirroring, prompts) is Phase 4 — until then a cloud box's\n * `agentbox-ctl` runs without a relay, and host-only RPCs surface a clear\n * \"no relay configured\" error.\n */\n\nimport { basename, resolve } from 'node:path';\nimport { generateBoxId, resolveSyncTopology } from '@agentbox/core';\nimport type {\n AttachKind,\n AttachSpec,\n BoxRecord,\n BoxResourceStats,\n BoxRuntimeState,\n BuildAttachOptions,\n CloudBackend,\n CloudHandle,\n CreateBoxRequest,\n CreatedBox,\n ExecOptions,\n ExecResult,\n GitWorktreeRecord,\n InspectedBox,\n Provider,\n ProviderCheckpoint,\n ProviderSync,\n ResyncResult,\n} from '@agentbox/core';\nimport {\n allocateProjectIndex,\n detectGitRepos,\n makeSyncContext,\n readCliStamp,\n readState,\n recordBox,\n removeBoxRecord,\n} from '@agentbox/sandbox-core';\nimport { makeCloudSync } from './sync/cloud-sync.js';\nimport {\n buildTmuxConfigShellSnippet,\n ensureRelay,\n forgetBoxFromRelay,\n generateRelayToken,\n generateVncPassword,\n portlessAlias,\n portlessGetUrl,\n portlessUnalias,\n registerBoxWithRelay,\n TERM_FALLBACK_SNIPPET,\n} from '@agentbox/sandbox-docker';\nimport { ensureAgentVolumesForCloud } from './sync/agent-credentials.js';\nimport {\n cloudSnapshotName,\n currentCloudBaseFingerprint,\n listCloudCheckpoints,\n removeCloudCheckpointDir,\n resolveCloudCheckpoint,\n writeCloudCheckpointManifest,\n} from './checkpoint.js';\nimport { loadEffectiveConfig } from '@agentbox/config';\nimport { isSnapshotGoneError } from './snapshot-error.js';\nimport { readExposedServicePorts } from './expose-ports.js';\nimport { downloadFromCloudBox, pullCloudDirContents, uploadToCloudBox } from './cloud-cp.js';\nimport { kickCloudBootstrap } from './bootstrap-launch.js';\nimport { readGitOriginUrl, registerBoxWithPlane } from './plane-register.js';\nimport { quoteShellArgv } from './shell.js';\nimport { seedCloudWorkspace } from './sync/workspace-seed.js';\nimport type { SeedCloudWorkspaceResult } from './sync/workspace-seed.js';\n\n/** Workspace mount path inside every cloud sandbox. Matches the Docker model. */\nexport const CLOUD_WORKSPACE_DIR = '/workspace';\n/**\n * In-box port the supervisor's WebProxy binds to. Matches `RESERVED_WEB_PORT`\n * in `@agentbox/ctl` (the only container port AgentBox publishes) — node has\n * `cap_net_bind_service` set in both the Docker and Hetzner base images so the\n * bind to <1024 needs no root. Daytona's base image inherits the same setcap\n * via Dockerfile.box.\n */\nexport const CLOUD_WEB_PROXY_PORT = 80;\n/** In-box port the noVNC viewer (websockify) serves on — fixed by Dockerfile.box. */\nexport const CLOUD_VNC_PORT = 6080;\n/**\n * Default expiry for browser-bound signed preview URLs. 1h matches Daytona's\n * docs recommendation: long enough for one CLI invocation + browser session,\n * short enough that a stale link doesn't outlive the box. Override with the\n * CLI `--ttl` flag when sharing or running long-lived sessions.\n */\nexport const DEFAULT_SIGNED_URL_TTL_SECONDS = 3600;\n\n/**\n * Provider-neutral image selector. Cloud backends typically resolve it to a\n * snapshot ref (Daytona) or a registry image. Backends may translate it via\n * `provisionImage` (see `CreateCloudProviderOptions`).\n */\nexport interface CreateCloudProviderOptions {\n /**\n * Translate the request's image to a backend-specific image / snapshot ref.\n * When omitted the backend is handed `req.image` verbatim (or the v0 default\n * `agentbox/box:dev`, which most cloud backends won't be able to resolve —\n * Daytona uses its snapshot helper here).\n */\n provisionImage?(req: CreateBoxRequest): Promise<string>;\n /**\n * Per-create cloud resource ceiling. Default: 2 cpu / 4 GiB / 8 GiB disk.\n */\n defaultResources?: { cpu?: number; memory?: number; disk?: number };\n /**\n * Whether to launch the in-box `dockerd` daemon on create/start. Default\n * true (Daytona/Hetzner support nested containers). Vercel Sandbox blocks the\n * namespace syscalls a container runtime needs, so its provider sets this\n * false — otherwise every create/start logs a spurious dockerd failure.\n */\n launchDockerd?: boolean;\n}\n\nconst FALLBACK_IMAGE = 'agentbox/box:dev';\n\n/** Default Portless no-TLS proxy port — matches the host wizard's choice. */\nconst DEFAULT_PORTLESS_PROXY_PORT = 1355;\n\n/**\n * Parse a host portless preview URL like `http://my-box.localhost:1355` /\n * `https://my-box.localhost` into the proxy mode the in-VPS mirror should\n * match. Returns `undefined` when the URL isn't a `*.localhost` portless URL\n * (e.g. portless isn't installed and we fell back to a loopback URL).\n */\nfunction parsePortlessUrl(url: string): { proxyPort: number; tls: boolean } | undefined {\n try {\n const u = new URL(url);\n if (!u.hostname.endsWith('.localhost')) return undefined;\n const tls = u.protocol === 'https:';\n const proxyPort = u.port ? Number.parseInt(u.port, 10) : tls ? 443 : 80;\n if (!Number.isFinite(proxyPort)) return undefined;\n return { proxyPort, tls };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Parse a loopback `http://127.0.0.1:<N>` URL into its port. Returns\n * `undefined` for any non-loopback URL (Daytona-style public URLs naturally\n * skip the Portless alias path).\n */\nfunction parseLoopbackPort(url: string): number | undefined {\n try {\n const u = new URL(url);\n if (u.hostname !== '127.0.0.1' && u.hostname !== 'localhost') return undefined;\n const port = Number.parseInt(u.port, 10);\n return Number.isFinite(port) ? port : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The bare host (no scheme) that `AGENTBOX_BOX_HOST` should advertise inside the\n * box. Portless backends return a loopback `http://127.0.0.1:<port>` web preview\n * (the host-side `ssh -L` forward) — meaningless inside the box, where the\n * portless mirror serves `<box-name>.localhost`, so we use that. Public-URL\n * backends (Vercel/Daytona/E2B) return a real preview whose host (e.g.\n * `<sub>.vercel.run`) is the reachable host. Returns `undefined` when no preview\n * resolved, letting the in-box engine derive `<box-name>.localhost` itself.\n */\nexport function deriveCloudBoxHost(\n boxName: string,\n webPreviewUrl: string | undefined,\n): string | undefined {\n if (!webPreviewUrl) return undefined;\n if (parseLoopbackPort(webPreviewUrl) !== undefined) return `${boxName}.localhost`;\n try {\n return new URL(webPreviewUrl).host;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Register a single host Portless alias `<alias>.localhost -> <previewUrl>`\n * when `previewUrl` resolves to a loopback `http://127.0.0.1:<port>` (Hetzner's\n * `ssh -L` forward). For backends that return a public URL (Daytona's signed\n * preview) the alias is naturally skipped. Best-effort: every Portless call\n * already swallows; we never throw from here. Returns the resolved URL on\n * success.\n */\nasync function registerHostPortlessAlias(args: {\n alias: string;\n previewUrl: string;\n label: string;\n onLog: (line: string) => void;\n}): Promise<string | undefined> {\n const localPort = parseLoopbackPort(args.previewUrl);\n if (localPort === undefined) return undefined;\n const ok = await portlessAlias(args.alias, localPort);\n if (!ok) {\n args.onLog(\n `portless: ${args.label} alias not registered (portless CLI missing or not running) — host URL stays http://127.0.0.1:${String(localPort)}`,\n );\n return undefined;\n }\n const url = await portlessGetUrl(args.alias);\n args.onLog(`portless alias ${url} -> 127.0.0.1:${String(localPort)}`);\n return url;\n}\n\n/**\n * Register the host Portless alias for `<boxName>.localhost -> <webPreviewUrl>`\n * and bring up the in-VPS mirror proxy so the same URL works from inside the\n * box. Best-effort: every step is gated on a previous step's success, and any\n * failure logs but doesn't throw. Returns `{ alias, url }` when the host alias\n * landed (so the caller can persist it on the BoxRecord), `undefined` otherwise.\n */\nasync function bootstrapPortlessForCloudBox(\n backend: CloudBackend,\n handle: CloudHandle,\n args: { boxName: string; webPreviewUrl: string; webPort: number; onLog: (line: string) => void },\n): Promise<{ alias: string; url: string } | undefined> {\n const url = await registerHostPortlessAlias({\n alias: args.boxName,\n previewUrl: args.webPreviewUrl,\n label: 'web',\n onLog: args.onLog,\n });\n if (!url) return undefined;\n if (backend.startInBoxPortless) {\n const mode = parsePortlessUrl(url) ?? { proxyPort: DEFAULT_PORTLESS_PROXY_PORT, tls: false };\n try {\n await backend.startInBoxPortless(handle, {\n boxName: args.boxName,\n proxyPort: mode.proxyPort,\n tls: mode.tls,\n webPort: args.webPort,\n });\n args.onLog(\n `portless: in-box mirror up on 127.0.0.1:${String(mode.proxyPort)} (${mode.tls ? 'https' : 'http'})`,\n );\n } catch (err) {\n args.onLog(\n `portless: in-box mirror failed (continuing): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n return { alias: args.boxName, url };\n}\n\nexport function createCloudProvider(\n backend: CloudBackend,\n opts: CreateCloudProviderOptions = {},\n): Provider {\n const providerName = backend.name;\n\n function handleFor(box: BoxRecord): CloudHandle {\n const sandboxId = box.cloud?.sandboxId;\n if (!sandboxId) {\n throw new Error(`cloud box ${box.name} has no sandboxId — record is malformed`);\n }\n return { sandboxId };\n }\n\n /** Resolve a fresh per-cloud-box id + name + branch. */\n function mintBox(req: CreateBoxRequest): {\n id: string;\n name: string;\n branch: string;\n } {\n const id = generateBoxId();\n const name = req.name ?? `${basename(req.workspacePath)}-${id}`;\n return {\n id,\n name,\n // --use-branch reuses the named branch directly; otherwise fork a fresh\n // per-box branch. The CLI validated `useBranch` exists host-side.\n branch: req.useBranch ?? `agentbox/${name}`,\n };\n }\n\n async function probe(box: BoxRecord): Promise<BoxRuntimeState> {\n try {\n const h = handleFor(box);\n const state = await backend.state(h);\n // CloudState aligns with BoxRuntimeState by construction.\n return state;\n } catch {\n return 'missing';\n }\n }\n\n /**\n * Persist the last host-driven lifecycle state so `agentbox list`/`top`/the\n * dashboard can show it without a live SDK probe. `pause`/`stop` persist\n * `paused` (matches vercel/hetzner's stopped→paused; daytona's authoritative\n * `stopped` only shows under `--live`). Best-effort — a state-write failure\n * must not fail the lifecycle op itself.\n */\n async function persistLastState(box: BoxRecord, lastState: BoxRuntimeState): Promise<void> {\n if (!box.cloud) return;\n try {\n await recordBox({ ...box, cloud: { ...box.cloud, lastState } });\n } catch {\n // listBoxes falls back to the previous value; not worth failing stop/pause.\n }\n }\n\n // Re-ensure a freshly-woken cloud box. A resumed/restarted sandbox boots\n // fresh: its in-box processes are gone and (on some backends) preview URLs\n // rotate. Refresh the web/service/relay preview URLs, re-register host\n // portless aliases, persist the record, relaunch the in-box daemons\n // (ctl daemon -> in-box bridge + the agentbox.yaml tasks/services, dockerd,\n // VNC), and re-register with the host relay. Shared by `start()` (after\n // `backend.start`), `resume()` (after `backend.resume`), and `reconnect()`\n // (no power-cycle) so EVERY wake/recover path brings the box fully back, not\n // just attach. Idempotent — the in-box `agentbox-ctl bootstrap` (ctl/dockerd/\n // VNC) skips the spawn when a healthy instance is already serving (so a\n // host-only `reconnect` on a\n // live box doesn't pile up duplicate daemons).\n async function reEnsureCloudBox(box: BoxRecord, h: CloudHandle): Promise<BoxRecord> {\n // Preview URLs (and their tokens) can rotate across stop/start — refresh\n // the web + relay preview URLs and persist so `agentbox url` and the\n // host poller see the live values.\n const webPort = box.cloud?.webPort ?? backend.webProxyPort ?? CLOUD_WEB_PROXY_PORT;\n let webPreview: { url: string; token?: string } | undefined;\n try {\n webPreview = await backend.previewUrl(h, webPort);\n } catch {\n const cached = box.cloud?.previewUrls?.[webPort];\n webPreview = cached ? { url: cached } : undefined;\n }\n // Re-mint per-service preview URLs from `agentbox.yaml`. Daytona's\n // preview URLs rotate when a sandbox restarts, so any cached ports\n // need to be re-resolved against the live handle.\n const servicePreviews: Record<number, string> = {};\n try {\n const ports = await readExposedServicePorts(box.workspacePath);\n for (const port of ports) {\n if (port === webPort) continue;\n try {\n const p = await backend.previewUrl(h, port);\n servicePreviews[port] = p.url;\n } catch {\n // skip — falls back to cached value below if any\n }\n }\n } catch {\n // workspace path missing / yaml unreadable: keep cached previewUrls\n }\n let relayPreview: { url: string; token?: string } | undefined;\n try {\n relayPreview = await backend.previewUrl(h, 8788);\n } catch {\n relayPreview = box.cloud?.relayPreviewUrl\n ? { url: box.cloud.relayPreviewUrl, token: box.cloud.relayPreviewToken }\n : undefined;\n }\n // Build the refreshed preview map: keep cached values for ports we\n // couldn't re-resolve, overlay fresh URLs from this start.\n const mergedPreviews: Record<number, string> = {\n ...(box.cloud?.previewUrls ?? {}),\n ...servicePreviews,\n };\n if (webPreview !== undefined) mergedPreviews[webPort] = webPreview.url;\n\n // Portless: the `ssh -L` local port is fresh after `agentbox start`\n // (pickFreePort picks again), and the in-VPS portless proxy died with\n // the VPS. Re-register the host alias against the new local port and\n // bring the in-box mirror back up. Skipped when no host portless alias\n // was set originally (user opted out at create) or when the URL is\n // non-loopback (Daytona).\n let portlessAliasName: string | undefined = box.portlessAlias;\n let portlessUrlResolved: string | undefined = box.portlessUrl;\n if (box.portlessAlias && webPreview) {\n const r = await bootstrapPortlessForCloudBox(backend, h, {\n boxName: box.name,\n webPreviewUrl: webPreview.url,\n webPort,\n onLog: () => {},\n });\n if (r) {\n portlessAliasName = r.alias;\n portlessUrlResolved = r.url;\n }\n }\n // Same story for the VNC alias — the ssh -L port for 6080 is fresh.\n // Best-effort, silent (startBox has no onLog). Skipped when no VNC\n // alias was set at create.\n let portlessVncAliasName: string | undefined = box.portlessVncAlias;\n let portlessVncUrlResolved: string | undefined = box.portlessVncUrl;\n if (box.portlessVncAlias && box.vncEnabled) {\n try {\n const vncPreview = await backend.previewUrl(h, CLOUD_VNC_PORT);\n const url = await registerHostPortlessAlias({\n alias: box.portlessVncAlias,\n previewUrl: vncPreview.url,\n label: 'vnc',\n onLog: () => {},\n });\n if (url) {\n portlessVncAliasName = box.portlessVncAlias;\n portlessVncUrlResolved = url;\n }\n } catch {\n /* best-effort */\n }\n }\n\n const next: BoxRecord = {\n ...box,\n portlessAlias: portlessAliasName,\n portlessUrl: portlessUrlResolved,\n portlessVncAlias: portlessVncAliasName,\n portlessVncUrl: portlessVncUrlResolved,\n cloud: {\n ...(box.cloud ?? { backend: providerName, sandboxId: h.sandboxId }),\n webPort,\n previewUrls: Object.keys(mergedPreviews).length > 0 ? mergedPreviews : undefined,\n relayPreviewUrl: relayPreview?.url ?? box.cloud?.relayPreviewUrl,\n relayPreviewToken: relayPreview?.token ?? box.cloud?.relayPreviewToken,\n // reEnsureCloudBox only runs on a freshly-woken box (start/resume), so\n // the box is now running — persist it for the fast `agentbox list` path.\n lastState: 'running',\n },\n };\n await recordBox(next);\n // Re-run the single in-box bootstrap — daemons die with the sandbox on\n // stop/start. It's idempotent: it relaunches only what's dead (so Vercel's\n // persistent snapshots, which keep daemons alive across resume, don't get\n // duplicates). dockerd is started before the supervisor inside the bootstrap\n // so a docker-based service doesn't race a not-yet-ready socket. No clone on\n // resume — /workspace already exists. dockerd/VNC are best-effort inside the\n // bootstrap; a dead ctl daemon throws and fails start (matching the previous\n // behavior, where the ctl relaunch was the one un-caught step).\n await kickCloudBootstrap({\n backend,\n handle: h,\n boxId: box.id,\n boxName: box.name,\n relayUrl: `http://127.0.0.1:${String(8788)}`,\n relayToken: box.relayToken ?? '',\n bridgeToken: box.cloud?.bridgeToken,\n webProxyPort: backend.webProxyPort,\n launchDockerd: opts.launchDockerd !== false,\n vncPassword: box.vncEnabled ? box.vncPassword : undefined,\n controlPlaneUrl: box.cloud?.controlPlaneUrl,\n gitPushMode: box.cloud?.gitPushMode,\n boxHost: deriveCloudBoxHost(box.name, webPreview?.url),\n });\n // Re-register on resume. A control-plane box registers on the plane (with\n // its origin URL, needed for lease minting); a classic-cloud box registers\n // on the host relay so its CloudBoxPoller picks up the fresh preview\n // URL/token. Both best-effort.\n if (box.cloud?.controlPlaneUrl && box.relayToken) {\n const adminToken = process.env.AGENTBOX_RELAY_ADMIN_TOKEN;\n const originUrl = await readGitOriginUrl(box.workspacePath).catch(() => undefined);\n if (adminToken && originUrl) {\n try {\n await registerBoxWithPlane({\n controlPlaneUrl: box.cloud.controlPlaneUrl,\n adminToken,\n boxId: box.id,\n token: box.relayToken,\n name: box.name,\n originUrl,\n backend: backend.name,\n bridgeToken: box.cloud.bridgeToken,\n previewUrl: relayPreview?.url,\n previewToken: relayPreview?.token,\n createdAt: box.createdAt,\n projectIndex: box.projectIndex,\n autoApproveHostActions: box.autoApproveHostActions,\n autoApproveSafeHostActions: box.autoApproveSafeHostActions,\n });\n } catch {\n // best-effort\n }\n }\n } else if (relayPreview && box.relayToken && box.cloud?.bridgeToken) {\n try {\n await registerBoxWithRelay({\n boxId: box.id,\n token: box.relayToken,\n name: box.name,\n kind: 'cloud',\n backend: backend.name,\n previewUrl: relayPreview.url,\n previewToken: relayPreview.token,\n bridgeToken: box.cloud.bridgeToken,\n createdAt: box.createdAt,\n projectIndex: box.projectIndex,\n autoApproveHostActions: box.autoApproveHostActions,\n autoApproveSafeHostActions: box.autoApproveSafeHostActions,\n });\n } catch {\n // best-effort\n }\n }\n return next;\n }\n\n return {\n name: providerName,\n\n async create(reqRaw: CreateBoxRequest): Promise<CreatedBox> {\n // Resolve the host workspace path to absolute up front, mirroring the\n // docker provider (`resolve(opts.workspacePath)` in sandbox-docker's\n // create). A relative `-w ../repo` would otherwise flow into the\n // git-clone seed as `git clone file://../repo` — `file://` needs an\n // absolute path, so git reads it as host `/repo` and fails with \"does\n // not appear to be a git repository\". Resolving here also keeps the\n // box record's workspacePath stable regardless of the caller's cwd.\n const req: CreateBoxRequest = reqRaw.workspacePath\n ? { ...reqRaw, workspacePath: resolve(reqRaw.workspacePath) }\n : reqRaw;\n const log = req.onLog ?? (() => {});\n const { id, name, branch } = mintBox(req);\n const image = opts.provisionImage\n ? await opts.provisionImage(req)\n : (req.image ?? FALLBACK_IMAGE);\n // Per-create overrides (currently vercel's box.vercelVcpus / vercelTimeoutMs,\n // threaded through providerOptions). Fall back to the provider's static\n // defaults so daytona/hetzner are unaffected.\n const baseResources = opts.defaultResources ?? { cpu: 2, memory: 4, disk: 8 };\n const vcpuOverride = req.providerOptions?.['vcpus'];\n const resources =\n typeof vcpuOverride === 'number' && vcpuOverride > 0\n ? { ...baseResources, cpu: vcpuOverride }\n : baseResources;\n const timeoutOverride = req.providerOptions?.['timeoutMs'];\n const timeoutMs =\n typeof timeoutOverride === 'number' && timeoutOverride > 0 ? timeoutOverride : undefined;\n const networkPolicyOpt = req.providerOptions?.['networkPolicy'];\n const networkPolicy =\n typeof networkPolicyOpt === 'string' && networkPolicyOpt.trim() !== ''\n ? networkPolicyOpt.trim()\n : undefined;\n // Generic VM-size string, resolved per-provider by the call site\n // (`resolveBoxSize` + `--size` flag). Each backend interprets it natively\n // (hetzner: server type; daytona: cpu-mem-disk GB); empty/undefined ⇒\n // backend uses its built-in default.\n const sizeOpt = req.providerOptions?.['size'];\n const size =\n typeof sizeOpt === 'string' && sizeOpt.trim() !== '' ? sizeOpt.trim() : undefined;\n\n // Per-box tokens: `relayToken` authenticates the in-box agent to its\n // in-sandbox relay (`/events`, `/rpc` bearer); `bridgeToken` separately\n // authenticates the HOST poller to the in-sandbox relay's `/bridge/*`\n // routes. Distinct so a compromised agent can't impersonate the host.\n const relayToken = generateRelayToken();\n const bridgeToken = generateRelayToken();\n\n // Bring the host relay up before we provision — registering the box\n // (and starting its CloudBoxPoller) happens at the bottom of this\n // function, and the loop wants the host relay reachable.\n try {\n await ensureRelay({ onLog: log });\n } catch (err) {\n log(\n `relay ensure failed (continuing): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n // Resolve any cloud checkpoint the caller requested. When found, we\n // boot from the snapshot (which already carries /workspace + any\n // installed deps) instead of from the base image, and skip the\n // workspace-seeding step below. A `checkpointRef` set for a checkpoint\n // that doesn't exist for THIS backend is logged and silently dropped —\n // matches the wizard's provider-aware behavior (the user may have a\n // Docker checkpoint with the same name; that's not our store).\n let snapshotName: string | undefined;\n let resolvedCheckpointRef: string | undefined;\n if (req.checkpointRef && req.projectRoot) {\n const found = await resolveCloudCheckpoint(\n req.projectRoot,\n backend.name,\n req.checkpointRef,\n );\n if (found) {\n snapshotName = found.manifest.snapshotName;\n resolvedCheckpointRef = found.name;\n log(`provisioning from cloud checkpoint '${found.name}' (snapshot ${snapshotName})`);\n } else {\n log(\n `cloud checkpoint '${req.checkpointRef}' not found for ${backend.name}; provisioning from base image`,\n );\n }\n }\n\n // Reserve per-agent credential volumes (Claude / Codex / OpenCode)\n // before provision so we can pass them as mounts in the same SDK call —\n // Daytona only attaches volumes at create time, not after. Backends\n // without a volume primitive return an empty list and we degrade to\n // \"user logs in inside the box\" the way cloud worked before.\n const agentVolumes = await ensureAgentVolumesForCloud(backend, { onLog: log });\n\n // Read the `expose:` service ports up front so port-capped backends\n // (vercel) can declare them at create time — a preview URL only routes to\n // a port that was exposed when the sandbox was created. Reused below for\n // the per-service preview-URL map. Best-effort: [] when there's no yaml.\n const exposeServicePorts = await readExposedServicePorts(req.workspacePath);\n\n const provisionEnv = {\n AGENTBOX_BOX_ID: id,\n AGENTBOX_BOX_NAME: name,\n AGENTBOX_BOX_KIND: 'cloud',\n // In-sandbox relay is on the box's loopback at the in-box port.\n // 8788 is distinct from the host relay's 8787 so a nested agentbox\n // run inside the box can claim :8787 without colliding.\n AGENTBOX_RELAY_URL: `http://127.0.0.1:${String(8788)}`,\n AGENTBOX_RELAY_TOKEN: relayToken,\n AGENTBOX_BRIDGE_TOKEN: bridgeToken,\n ...agentVolumes.env,\n };\n const provisionFrom = async (snapshot: string | undefined): Promise<CloudHandle> => {\n log(\n snapshot\n ? `provisioning ${providerName} sandbox from snapshot`\n : `provisioning ${providerName} sandbox`,\n );\n return backend.provision({\n name,\n image,\n snapshot,\n resources,\n size,\n timeoutMs,\n exposePorts: exposeServicePorts,\n networkPolicy,\n env: provisionEnv,\n volumes: agentVolumes.mounts,\n onLog: log,\n });\n };\n\n let handle: CloudHandle;\n try {\n handle = await provisionFrom(snapshotName);\n } catch (err) {\n // The checkpoint snapshot we tried to boot from is gone (expired or\n // deleted out-of-band). Rather than crash, prune the dangling local\n // manifest and fall back to a from-scratch box on the base image —\n // the workspace seed below then runs as if no checkpoint existed.\n // (No fallback for a base-image boot: there's nothing left to retry.)\n if (snapshotName && isSnapshotGoneError(err)) {\n log(\n `checkpoint snapshot '${resolvedCheckpointRef ?? snapshotName}' has expired or been deleted; ` +\n 'starting a fresh box from the base image instead',\n );\n if (req.projectRoot && resolvedCheckpointRef) {\n try {\n await removeCloudCheckpointDir(req.projectRoot, backend.name, resolvedCheckpointRef);\n } catch {\n // best-effort: a stale manifest left behind only re-triggers this\n // same fallback next time, which is still safe.\n }\n }\n snapshotName = undefined;\n resolvedCheckpointRef = undefined;\n handle = await provisionFrom(undefined);\n } else {\n throw err;\n }\n }\n\n // Optional in-box clone: when the caller passes a leased, token-bearing\n // URL (the plane / cloud-IDE path), the box clones /workspace itself at\n // bootstrap instead of the host seeding it. The laptop path omits this and\n // host-seeds below (carrying local uncommitted state).\n const inBoxClone = req.inBoxClone\n ? {\n authedUrl: req.inBoxClone.authedUrl,\n originUrl: req.inBoxClone.originUrl,\n branch: req.inBoxClone.branch,\n depth: req.bundleDepth,\n }\n : undefined;\n\n try {\n // Checkpoint-restore conflicts (overlay): surface to the CLI so it\n // injects the same \"conflicting host changes SKIPPED … agentbox-ctl\n // reload\" prompt into the agent that docker does. Undefined on a fresh\n // create (no overlay), an in-box clone, or when nothing conflicted.\n let resync: SeedCloudWorkspaceResult['resync'];\n if (inBoxClone) {\n // The box clones itself at bootstrap; no host-side seed.\n log('skipping host workspace seed — box will clone in-box at bootstrap');\n } else {\n // The snapshot carries /workspace from the SOURCE box — including its\n // (now stale) per-box branch and none of this box's uncommitted work.\n // Booting from it verbatim would leave every checkpoint-derived box on\n // the same frozen branch with the wrong files. So we re-seed in OVERLAY\n // mode: keep the snapshot's gitignored warm artifacts (node_modules,\n // build caches — the checkpoint's value), but swap `.git` for a fresh\n // host clone, move onto this box's fresh `agentbox/<box>` branch at the\n // host base ref, and apply the host's uncommitted/untracked carry-over.\n // Mirrors docker's `regenerateRestoredWorktrees` + `resyncWorkspaceFromHost`.\n const seedResult = await seedCloudWorkspace({\n backend,\n handle,\n workspacePath: req.workspacePath,\n branch,\n workspaceDir: CLOUD_WORKSPACE_DIR,\n bundleDepth: req.bundleDepth,\n fromBranch: req.fromBranch,\n useBranch: req.useBranch,\n overlay: Boolean(snapshotName),\n // `--no-resync` (resyncOnStart === false): re-branch the box to the\n // host tip but skip replaying the host's uncommitted/untracked state\n // onto the warm checkpoint tree — matches docker's gated resync.\n skipCarryOver: Boolean(snapshotName) && req.resyncOnStart === false,\n onLog: log,\n });\n resync =\n seedResult.resync && seedResult.resync.hadConflicts ? seedResult.resync : undefined;\n }\n\n // Walk the cloud ProviderSync facade (see sync/cloud-sync.ts for the full\n // per-op picture). Order preserved from the pre-facade sequence:\n // seedCredentials = refresh host backups (best-effort, expiry-gated) +\n // seed the per-agent credentials for the agents that\n // have a volume/dir (`agentVolumes.agents`).\n // seedAgentConfig = normalize agent home-dir ownership → codex\n // AGENTS.override box-facts → OpenCode model →\n // _claude.json overlay → dynamic workflows/memory.\n // seedGitIdentity = git committer identity (cloud has no ~/.gitconfig).\n // Workspace *seed* (above, via seedCloudWorkspace) + static config (baked\n // at prepare) stay outside the facade.\n const syncCtx = makeSyncContext({\n boxName: name,\n boxId: id,\n provider: 'cloud',\n hostWorkspace: req.workspacePath,\n projectRoot: req.projectRoot,\n boxWorkspace: CLOUD_WORKSPACE_DIR,\n onLog: log,\n });\n const sync = makeCloudSync(backend, handle, { agents: agentVolumes.agents });\n await sync.seedCredentials(syncCtx);\n await sync.seedAgentConfig(syncCtx);\n await sync.seedGitIdentity(syncCtx);\n\n // Copy the env/config files the setup wizard collected (`.env`,\n // `secrets.toml`, `agentbox.yaml`, …) into `/workspace`.\n if (req.envFilesToImport && req.envFilesToImport.length > 0) {\n const { copied } = await sync.seedEnvFiles(syncCtx, req.envFilesToImport);\n if (copied > 0) log(`copied ${String(copied)} env/config file(s) into /workspace`);\n }\n\n // carry: from agentbox.yaml — runs after the env-file copies and before\n // the supervisor launches. The host CLI already resolved + approved req.carry.\n let carrySummary:\n | { count: number; entries: Array<{ src: string; dest: string; bytes: number }> }\n | undefined;\n if (req.carry && req.carry.length > 0) {\n log(`carry: copying ${String(req.carry.length)} host path(s) into the box`);\n const result = await sync.applyCarry(syncCtx, req.carry);\n log(`carry: copied ${String(result.copied)}/${String(req.carry.length)} entry/entries`);\n for (const err of result.errors) log(`carry: ${err}`);\n if (result.applied.length > 0) {\n carrySummary = { count: result.applied.length, entries: result.applied };\n }\n }\n\n // Per-box VNC password (default-on, matching Docker). Threaded into the\n // bootstrap below; reused later for the record + preview URLs.\n const vncEnabled = req.vnc?.enabled !== false;\n const vncPassword = vncEnabled ? generateVncPassword() : undefined;\n\n // The box's \"web\" port: the in-box WebProxy port the provider exposes.\n // Defaults to 80; Vercel uses 8080 (it can't expose privileged ports).\n const wp = backend.webProxyPort ?? CLOUD_WEB_PROXY_PORT;\n\n // Resolve the web preview URL BEFORE the bootstrap so the box's reachable\n // host (AGENTBOX_BOX_HOST) is wired into the supervisor's env — a\n // first-boot `agentbox-ctl render` task must see the real host, not the\n // `<name>.localhost` fallback. Best-effort: most boxes won't have a\n // service on the WebProxy port yet, but the provider resolves the routing\n // URL regardless of whether anything listens. Reused below for portless\n // bootstrap and previewUrls persistence. `agentbox url` re-resolves.\n let webPreview: { url: string; token?: string } | undefined;\n try {\n webPreview = await backend.previewUrl(handle, wp);\n } catch {\n webPreview = undefined;\n }\n\n // Hand off to the single in-box bootstrap: it (optionally) clones the\n // workspace, then launches dockerd → the ctl supervisor → VNC, each only\n // if not already live. One exec replaces the three previous host-driven\n // launches; the same kick serves resume (idempotent). dockerd is started\n // before the supervisor (inside the bootstrap) so a docker-based\n // agentbox.yaml service doesn't race a not-yet-ready socket. dockerd/VNC\n // are best-effort there; only a failed ctl daemon throws. Vercel sets\n // launchDockerd:false (no nested containers).\n log('running in-box bootstrap (clone? + dockerd + ctl + vnc)');\n await kickCloudBootstrap({\n backend,\n handle,\n boxId: id,\n boxName: name,\n relayUrl: `http://127.0.0.1:${String(8788)}`,\n relayToken,\n bridgeToken,\n webProxyPort: backend.webProxyPort,\n launchDockerd: opts.launchDockerd !== false,\n vncPassword,\n clone: inBoxClone,\n controlPlaneUrl: req.controlPlaneUrl,\n gitPushMode: req.gitPushMode,\n boxHost: deriveCloudBoxHost(name, webPreview?.url),\n onLog: log,\n });\n\n // Portless host alias + in-VPS mirror. Default-on for backends whose\n // `previewUrl()` returns a loopback URL (Hetzner); naturally skipped\n // for public-URL backends (Daytona) because the URL doesn't parse as\n // 127.0.0.1. Caller can opt out via `providerOptions.portless: false`.\n // Best-effort: every step logs + continues on failure.\n const portlessOpt = (req.providerOptions?.['portless'] as boolean | undefined) ?? true;\n let portlessAliasName: string | undefined;\n let portlessUrlResolved: string | undefined;\n if (portlessOpt && webPreview) {\n const r = await bootstrapPortlessForCloudBox(backend, handle, {\n boxName: name,\n webPreviewUrl: webPreview.url,\n webPort: wp,\n onLog: log,\n });\n if (r) {\n portlessAliasName = r.alias;\n portlessUrlResolved = r.url;\n }\n }\n // Parallel `vnc-<box-name>.localhost` alias against the in-box noVNC\n // port. Host-only — no in-box mirror; an agent inside the box opening\n // its own VNC view is a degenerate self-loop. Same loopback-URL gate\n // as the web path, so Daytona naturally skips and Hetzner registers.\n let vncPreview: { url: string; token?: string } | undefined;\n if (portlessOpt && vncEnabled) {\n try {\n vncPreview = await backend.previewUrl(handle, CLOUD_VNC_PORT);\n } catch {\n vncPreview = undefined;\n }\n }\n let portlessVncAliasName: string | undefined;\n let portlessVncUrlResolved: string | undefined;\n if (portlessOpt && vncPreview) {\n const vncAlias = `vnc-${name}`;\n const url = await registerHostPortlessAlias({\n alias: vncAlias,\n previewUrl: vncPreview.url,\n label: 'vnc',\n onLog: log,\n });\n if (url) {\n portlessVncAliasName = vncAlias;\n portlessVncUrlResolved = url;\n }\n }\n // Per-service preview URLs. Each `services.*.expose.port` from\n // `agentbox.yaml` gets a direct preview URL alongside the main\n // WebProxy URL — lets users hit services without going through the\n // WebProxy. Best-effort: a failed `previewUrl` for a given port\n // just omits it from the map.\n const servicePorts = exposeServicePorts;\n const servicePreviews: Record<number, string> = {};\n for (const port of servicePorts) {\n if (port === wp) continue;\n try {\n const p = await backend.previewUrl(handle, port);\n servicePreviews[port] = p.url;\n } catch {\n // skip this port; the user can still hit the service via the\n // WebProxy if the YAML wires `expose.as: 80`.\n }\n }\n\n // The bridge preview URL is critical: it's how the host CloudBoxPoller\n // reaches the in-sandbox relay. The ctl daemon binds 0.0.0.0:8788 in\n // box mode (cloud), so the Daytona preview proxy can route to it.\n let relayPreview: { url: string; token?: string } | undefined;\n try {\n relayPreview = await backend.previewUrl(handle, 8788);\n } catch {\n relayPreview = undefined;\n }\n\n // Allocate the per-project index BEFORE registering with the relay: the\n // relay keys the status.json path on the projectIndex it's registered\n // with (`<id>-<N>-<mnemonic>`), and the host reader (list / footer /\n // readBoxStatus) derives the same path from the box record. Registering\n // first (projectIndex undefined) made the relay write to the legacy\n // no-index path while the record had `projectIndex: N` — so the reader\n // looked at the `-N-` path, found nothing, and `agentbox list` showed\n // no AGENT status for cloud boxes.\n const state = await readState();\n const projectIndex = req.projectRoot\n ? allocateProjectIndex(state, req.projectRoot)\n : undefined;\n\n // Per-box host-action auto-approve policy (workspace > project > global).\n const effectiveBoxForApprove = (\n await loadEffectiveConfig(req.projectRoot ?? req.workspacePath)\n ).effective.box;\n const autoApproveHostActions = effectiveBoxForApprove.autoApproveHostActions;\n const autoApproveSafeHostActions = effectiveBoxForApprove.autoApproveSafeHostActions;\n\n // Register the box so its RPCs (status, git.lease-token) are recognized.\n // Control-plane box → register on the PLANE with its origin URL (the\n // plane mints push tokens from the registered origin); it forwards /rpc\n // to the plane and needs no host poller. Classic-cloud box → register on\n // the host relay so it spawns a CloudBoxPoller for /bridge. Both\n // best-effort: a failed register doesn't break create.\n if (req.controlPlaneUrl) {\n const adminToken = process.env.AGENTBOX_RELAY_ADMIN_TOKEN;\n const originUrl = req.inBoxClone\n ? req.inBoxClone.originUrl\n : await readGitOriginUrl(req.workspacePath).catch(() => undefined);\n if (!adminToken) {\n log(\n 'control-plane URL configured but AGENTBOX_RELAY_ADMIN_TOKEN is unset; ' +\n 'box git push (lease) will fail until the box is registered on the plane',\n );\n } else if (!originUrl) {\n log(\n 'control-plane box: could not resolve the workspace origin URL; ' +\n 'lease-push will fail until the box is registered on the plane with an origin',\n );\n } else {\n try {\n await registerBoxWithPlane({\n controlPlaneUrl: req.controlPlaneUrl,\n adminToken,\n boxId: id,\n token: relayToken,\n name,\n originUrl,\n backend: backend.name,\n bridgeToken,\n previewUrl: relayPreview?.url,\n previewToken: relayPreview?.token,\n createdAt: new Date().toISOString(),\n projectIndex,\n autoApproveHostActions,\n autoApproveSafeHostActions,\n });\n } catch (err) {\n log(\n `register with control plane failed (continuing): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n } else if (relayPreview) {\n try {\n await registerBoxWithRelay({\n boxId: id,\n token: relayToken,\n name,\n projectIndex,\n kind: 'cloud',\n backend: backend.name,\n previewUrl: relayPreview.url,\n previewToken: relayPreview.token,\n bridgeToken,\n createdAt: new Date().toISOString(),\n autoApproveHostActions,\n autoApproveSafeHostActions,\n });\n } catch (err) {\n log(\n `register with host relay failed (continuing): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n const record: BoxRecord = {\n id,\n name,\n provider: providerName,\n // `container` carries the sandbox id with a `cloud:` prefix —\n // unique within state, never collides with a real docker\n // container, and grepping for `agentbox-cloud-*` (the old\n // synthetic value) finds nothing now. `image` mirrors the\n // resolved cloud image so `BoxRecord.image: string` stays\n // required without docker-internal readers seeing `undefined`.\n container: `cloud:${handle.sandboxId}`,\n image,\n workspacePath: req.workspacePath,\n projectRoot: req.projectRoot,\n projectIndex,\n relayToken,\n withPlaywright: req.withPlaywright,\n withEnv: req.withEnv,\n autoApproveHostActions: autoApproveHostActions ? true : undefined,\n autoApproveSafeHostActions: autoApproveSafeHostActions === false ? false : undefined,\n carry: carrySummary,\n portlessAlias: portlessAliasName,\n portlessUrl: portlessUrlResolved,\n portlessVncAlias: portlessVncAliasName,\n portlessVncUrl: portlessVncUrlResolved,\n vncEnabled,\n vncPassword,\n vncContainerPort: vncEnabled ? CLOUD_VNC_PORT : undefined,\n resourceLimits: req.limits\n ? {\n memoryBytes: req.limits.memoryBytes ?? undefined,\n cpus: req.limits.cpus ?? undefined,\n pidsLimit: req.limits.pidsLimit ?? undefined,\n disk: req.limits.disk ?? undefined,\n }\n : undefined,\n cloud: {\n backend: backend.name,\n sandboxId: handle.sandboxId,\n image,\n webPort: wp,\n previewUrls: ((): Record<number, string> | undefined => {\n const m: Record<number, string> = { ...servicePreviews };\n if (webPreview) m[wp] = webPreview.url;\n return Object.keys(m).length > 0 ? m : undefined;\n })(),\n relayPreviewUrl: relayPreview?.url,\n relayPreviewToken: relayPreview?.token,\n bridgeToken,\n snapshotRef: resolvedCheckpointRef,\n lastState: 'running',\n sessionTimeoutMs: timeoutMs,\n // Only host-seeded boxes share a fork base with the host, so only\n // they can be resynced back to the host tip on session start (7.5).\n // inBoxClone / plane boxes clone from a leased URL — left unset.\n hostSeeded: inBoxClone ? undefined : true,\n workspaceBranch: branch,\n topology: resolveSyncTopology(backend.name, req.controlPlaneUrl),\n controlPlaneUrl: req.controlPlaneUrl,\n gitPushMode: req.gitPushMode,\n },\n createdAt: new Date().toISOString(),\n };\n await recordBox(record);\n return { record, imageBuilt: false, resync };\n } catch (err) {\n // Best-effort teardown of the half-provisioned sandbox so a failed\n // create doesn't leave the user paying for an inert box.\n try {\n await backend.destroy(handle);\n } catch {\n // The user is going to see the original error; suppressing this\n // secondary failure keeps the message clean.\n }\n throw err;\n }\n },\n\n async start(box: BoxRecord): Promise<BoxRecord> {\n const h = handleFor(box);\n await backend.start(h);\n return reEnsureCloudBox(box, h);\n },\n\n async reconnect(box: BoxRecord): Promise<BoxRecord> {\n // Re-establish host connectivity WITHOUT a power-cycle when the sandbox is\n // already up: `reEnsureCloudBox` re-resolves preview URLs, re-opens the\n // Hetzner tunnel (lazily, on its first `previewUrl`), re-registers\n // portless + the relay poller, and relaunches the in-box daemons. If the\n // box is actually paused/stopped, fall back to the power-cycling paths.\n const h = handleFor(box);\n const state = await probe(box);\n if (state === 'running') return reEnsureCloudBox(box, h);\n if (state === 'paused') {\n await backend.resume(h);\n return reEnsureCloudBox(box, h);\n }\n if (state === 'stopped') {\n await backend.start(h);\n return reEnsureCloudBox(box, h);\n }\n throw new Error(\n `cannot recover ${box.name}: sandbox ${box.cloud?.sandboxId ?? box.id} is ${state}`,\n );\n },\n\n async repairReachability(box: BoxRecord): Promise<{ changed: boolean; detail?: string }> {\n // Delegate to the backend (only Hetzner self-heals its firewall); other\n // backends have no host transport to repair.\n return (await backend.repairReachability?.(handleFor(box))) ?? { changed: false };\n },\n\n async pause(box: BoxRecord): Promise<void> {\n await backend.pause(handleFor(box));\n await persistLastState(box, 'paused');\n },\n\n async resume(box: BoxRecord): Promise<void> {\n const h = handleFor(box);\n await backend.resume(h);\n // A resumed sandbox boots fresh — ctl/bridge (-> the agentbox.yaml\n // tasks/services), VNC and dockerd are gone. Re-ensure everything\n // `start()` does so non-attach resume paths (`agentbox unpause`/`url`/\n // `checkpoint`/dashboard) don't strand a box with dead daemons. The\n // returned record is persisted inside `reEnsureCloudBox` (recordBox).\n await reEnsureCloudBox(box, h);\n },\n\n async stop(box: BoxRecord): Promise<void> {\n await backend.stop(handleFor(box));\n await persistLastState(box, 'paused');\n },\n\n async destroy(box: BoxRecord): Promise<void> {\n try {\n await backend.destroy(handleFor(box));\n } catch (err) {\n // Surface but don't block state cleanup — a \"missing\" sandbox should\n // still let `agentbox destroy` drop the local record.\n const msg = err instanceof Error ? err.message : String(err);\n if (!/not.?found|missing/i.test(msg)) throw err;\n }\n // Best-effort: drop the host Portless aliases (web + vnc) so neither\n // `<box>.localhost` nor `vnc-<box>.localhost` keeps pointing at a dead\n // ssh -L. The in-VPS portless dies with the VPS.\n if (box.portlessAlias) {\n try {\n await portlessUnalias(box.portlessAlias);\n } catch {\n // portlessUnalias swallows already; paranoid catch in case.\n }\n }\n if (box.portlessVncAlias) {\n try {\n await portlessUnalias(box.portlessVncAlias);\n } catch {\n // best-effort\n }\n }\n // Best-effort: stop the host poller and drop the registration.\n try {\n await forgetBoxFromRelay(box.id);\n } catch {\n // forgetBoxFromRelay already swallows; this catch is paranoid.\n }\n await removeBoxRecord(box.id);\n },\n\n async probeState(box: BoxRecord): Promise<BoxRuntimeState> {\n return probe(box);\n },\n\n async inspect(box: BoxRecord): Promise<InspectedBox> {\n const state = await probe(box);\n const webPort = box.cloud?.webPort ?? backend.webProxyPort ?? CLOUD_WEB_PROXY_PORT;\n // Prefer the stable Portless URL for the `web` endpoint when one was\n // registered — matches Docker's endpoint shape (sandbox-docker/src/\n // endpoints.ts:108-117) so `<name>.localhost` shows up uniformly in\n // `agentbox list` / `inspect`. Falls back to the ephemeral preview URL\n // when Portless wasn't enabled or didn't take.\n const portlessWebUrl =\n box.portlessAlias !== undefined\n ? (box.portlessUrl ?? `https://${box.portlessAlias}.localhost`)\n : undefined;\n const cachedWebUrl = box.cloud?.previewUrls?.[webPort];\n const webUrl = portlessWebUrl ?? cachedWebUrl;\n // Surface each per-service preview URL alongside the main WebProxy.\n // Naming is `service-<port>` because we don't track the YAML name\n // -> port map on the record (avoids extra wire shape just for\n // display).\n const endpoints: Array<{\n kind: 'web';\n name: string;\n containerPort: number;\n url: string;\n reachable: boolean;\n }> = [];\n if (webUrl) {\n endpoints.push({\n kind: 'web',\n name: 'web',\n containerPort: webPort,\n url: webUrl,\n reachable: true,\n });\n }\n for (const [portStr, url] of Object.entries(box.cloud?.previewUrls ?? {})) {\n const port = Number.parseInt(portStr, 10);\n if (!Number.isFinite(port) || port === webPort) continue;\n endpoints.push({\n kind: 'web',\n name: `service-${String(port)}`,\n containerPort: port,\n url,\n reachable: true,\n });\n }\n return {\n record: box,\n state,\n endpoints: {\n domain: webUrl ? new URL(webUrl).host : '',\n domainIsOrb: false,\n endpoints,\n },\n raw: undefined,\n };\n },\n\n async exec(box: BoxRecord, argv: string[], opts?: ExecOptions): Promise<ExecResult> {\n const r = await backend.exec(handleFor(box), quoteShellArgv(argv), {\n cwd: opts?.cwd,\n env: opts?.env,\n user: opts?.user,\n });\n return { exitCode: r.exitCode, stdout: r.stdout, stderr: r.stderr };\n },\n\n async buildAttach(\n box: BoxRecord,\n kind: AttachKind,\n opts?: BuildAttachOptions,\n ): Promise<AttachSpec> {\n if (!backend.attachArgv) {\n throw new Error(\n `cloud backend '${backend.name}' does not implement attachArgv — interactive attach not supported`,\n );\n }\n const handle = handleFor(box);\n const baseArgv = await backend.attachArgv(handle);\n const inner = renderInnerCommand(kind, opts);\n // -t forces TTY allocation on the remote side (the SSH default of\n // skipping TTY when a command is provided would break tmux + readline).\n // A `detached` build only creates the session (no `exec tmux attach`), so\n // it runs as a plain non-interactive exec — no TTY needed.\n const argv = opts?.detached\n ? [...baseArgv.slice(1), inner]\n : [...baseArgv.slice(1), '-t', inner];\n // Keep argv[0] = the program name (ssh) so callers can split.\n const fullArgv = [baseArgv[0]!, ...argv];\n const cleanup = backend.revokeAttachToken\n ? async (): Promise<void> => {\n await backend.revokeAttachToken!(handle, baseArgv);\n }\n : undefined;\n return { argv: fullArgv, cleanup };\n },\n\n async uploadPath(\n box: BoxRecord,\n hostSrcs: string[],\n boxDst: string,\n exclude?: string[],\n ): Promise<{ finalPath: string }> {\n return uploadToCloudBox(backend, handleFor(box), hostSrcs, boxDst, exclude);\n },\n\n async downloadPath(\n box: BoxRecord,\n boxSrcs: string[],\n hostDst: string,\n exclude?: string[],\n ): Promise<{ finalPath: string }> {\n return downloadFromCloudBox(backend, handleFor(box), boxSrcs, hostDst, exclude);\n },\n\n async downloadDirContents(\n box: BoxRecord,\n boxSrc: string,\n hostDst: string,\n ): Promise<{ finalPath: string }> {\n return pullCloudDirContents(backend, handleFor(box), boxSrc, hostDst);\n },\n\n async resolveUrl(\n box: BoxRecord,\n opts?: { loopback?: boolean; kind?: 'web' | 'vnc'; ttl?: number },\n ): Promise<string> {\n const h = handleFor(box);\n const kind = opts?.kind ?? 'web';\n // Prefer the stable Portless URL when one was registered (Hetzner gets\n // both; Daytona naturally skips since previewUrl is non-loopback). The\n // `--loopback` flag forces the raw signed/loopback path instead.\n if (!opts?.loopback) {\n if (kind === 'web' && box.portlessAlias) {\n return box.portlessUrl ?? `https://${box.portlessAlias}.localhost`;\n }\n if (kind === 'vnc' && box.portlessVncAlias) {\n return box.portlessVncUrl ?? `https://${box.portlessVncAlias}.localhost`;\n }\n }\n // VNC port is fixed by Dockerfile.box (websockify serves noVNC on :6080).\n const port =\n kind === 'vnc'\n ? CLOUD_VNC_PORT\n : (box.cloud?.webPort ?? backend.webProxyPort ?? CLOUD_WEB_PROXY_PORT);\n // Always re-resolve through the SDK — cached URLs on the record may be\n // from a previous start whose token has rotated. Prefer signed URLs\n // because the user is about to hand the URL to a browser (no way to\n // attach an `x-daytona-preview-token` header from a click).\n if (backend.signedPreviewUrl) {\n const ttl = opts?.ttl ?? DEFAULT_SIGNED_URL_TTL_SECONDS;\n try {\n const signed = await backend.signedPreviewUrl(h, port, ttl);\n return signed.url;\n } catch (err) {\n // Web fallback: some backends (Vercel) can't expose the privileged\n // WebProxy port (<1024), so resolving :80 throws \"no route\". Fall back\n // to the first exposed `expose:` service port so `agentbox url` still\n // reaches the app the user actually published. Daytona/Hetzner expose\n // :80 directly, so this branch never runs for them.\n if (kind === 'web') {\n const fallbackPort = await firstExposedServicePort(box);\n if (fallbackPort !== undefined && fallbackPort !== port) {\n const signed = await backend.signedPreviewUrl(h, fallbackPort, ttl);\n return signed.url;\n }\n }\n throw err;\n }\n }\n // No signed-URL primitive: fall back to the header-token URL, but fail\n // loudly so the caller sees this isn't usable in a browser as-is.\n const p = await backend.previewUrl(h, port);\n throw new Error(\n `cloud backend '${backend.name}' does not support signed preview URLs; ` +\n `the standard URL (${p.url}) requires a header token (e.g. x-daytona-preview-token: ${p.token ?? '<unset>'}) ` +\n `that browsers can't attach from a click. Use a programmatic client or wait for backend support.`,\n );\n },\n\n // Cloud checkpoint capability. Backends without `createSnapshot` get a\n // capability stub whose methods throw — the CLI's `agentbox checkpoint\n // create` then surfaces a clean \"not supported\" error rather than a\n // silent no-op.\n checkpoint: makeCloudCheckpoint(backend),\n\n sync(box: BoxRecord): ProviderSync {\n return makeCloudSync(backend, handleFor(box));\n },\n\n // Session-start live-box resync (Phase 7.5): merge the host's current state\n // back into the box, box-wins on conflict. Gated on `hostSeeded` so\n // inBoxClone / plane boxes (no host fork base) are left untouched. The box\n // layout is re-derived host-side (`detectGitRepos`) rather than recorded.\n async resyncWorkspace(box: BoxRecord, onLog?: (line: string) => void): Promise<ResyncResult> {\n if (box.cloud?.hostSeeded !== true) return { repos: [], hadConflicts: false };\n const repos = await detectGitRepos(box.workspacePath);\n if (repos.length === 0) return { repos: [], hadConflicts: false };\n const branch = box.cloud.workspaceBranch ?? `agentbox/${box.name}`;\n const worktrees: GitWorktreeRecord[] = repos.map((r) => {\n const containerPath = r.relPathFromWorkspace\n ? `${CLOUD_WORKSPACE_DIR}/${r.relPathFromWorkspace}`\n : CLOUD_WORKSPACE_DIR;\n return {\n kind: r.kind,\n hostMainRepo: r.hostMainRepo,\n containerPath,\n // Cloud boxes clone in place, so the worktree lives at its mount path.\n gitWorktreePath: containerPath,\n branch,\n relPathFromWorkspace: r.relPathFromWorkspace,\n };\n });\n const ctx = makeSyncContext({\n boxName: box.name,\n boxId: box.id,\n provider: 'cloud',\n hostWorkspace: box.workspacePath,\n boxWorkspace: CLOUD_WORKSPACE_DIR,\n onLog,\n });\n return makeCloudSync(backend, handleFor(box)).resyncWorkspace(ctx, worktrees);\n },\n\n // Extract the box's agent login(s) back to the host (~/.agentbox) so the\n // next box inherits the login. Lives on the base cloud provider (not inside\n // `checkpoint.create`) so it works even for providers that override the\n // whole `checkpoint` capability (vercel). The CLI calls this on\n // `checkpoint create --set-default`, while the box is guaranteed running.\n async extractAgentCredentials(box: BoxRecord): Promise<string[]> {\n if (!box.cloud?.sandboxId) return [];\n // Delegate to the co-located facade — the same op as a peer method.\n // `extractCredentials` ignores the ctx (box→host capture uses backend +\n // handle), but the ProviderSync signature takes one.\n const ctx = makeSyncContext({\n boxName: box.name,\n boxId: box.id,\n provider: 'cloud',\n hostWorkspace: box.workspacePath,\n });\n return makeCloudSync(backend, handleFor(box)).extractCredentials(ctx);\n },\n\n // stats is provider-optional; cloud backends without a metrics API just\n // omit it. Backends that have one can decorate the returned provider.\n };\n}\n\n/** Reserved cloud ports that are never a user-facing web service. */\nconst RESERVED_CLOUD_PORTS = new Set<number>([CLOUD_WEB_PROXY_PORT, CLOUD_VNC_PORT, 8788]);\n\n/**\n * The lowest exposed `expose:` service port for a box, used as the web URL\n * fallback when the WebProxy port itself can't be exposed (Vercel). Prefers the\n * box record's `previewUrls` map (only ports that actually got a preview URL\n * land there), then falls back to re-reading `agentbox.yaml`. Returns undefined\n * when the box exposes no non-reserved service port.\n */\nasync function firstExposedServicePort(box: BoxRecord): Promise<number | undefined> {\n // The box's own WebProxy port (e.g. Vercel's 8080) is reserved too — it's the\n // web aggregator, not a user service port.\n const reserved = (p: number): boolean => RESERVED_CLOUD_PORTS.has(p) || p === box.cloud?.webPort;\n const fromRecord = Object.keys(box.cloud?.previewUrls ?? {})\n .map(Number)\n .filter((p) => Number.isInteger(p) && !reserved(p));\n if (fromRecord.length > 0) return Math.min(...fromRecord);\n try {\n const fromYaml = (await readExposedServicePorts(box.workspacePath)).filter((p) => !reserved(p));\n if (fromYaml.length > 0) return Math.min(...fromYaml);\n } catch {\n // workspace path missing / yaml unreadable — no fallback available\n }\n return undefined;\n}\n\n/**\n * Build the `Provider.checkpoint` capability for a cloud backend.\n *\n * - `create(box, name)` captures the live sandbox via `backend.createSnapshot`\n * and persists a thin manifest on the host (`~/.agentbox/cloud-checkpoints/…`).\n * - `list(projectRoot)` reads the on-disk manifest store.\n * - `remove(projectRoot, ref)` deletes the Daytona snapshot best-effort and\n * removes the local manifest unconditionally so a remote-only failure\n * doesn't leave the user with a dead pointer.\n */\nfunction makeCloudCheckpoint(backend: CloudBackend): ProviderCheckpoint {\n return {\n async create(box: BoxRecord, name: string) {\n if (!backend.createSnapshot) {\n throw new Error(\n `cloud backend '${backend.name}' doesn't support snapshots — \\`agentbox checkpoint\\` unavailable`,\n );\n }\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 if (!box.cloud?.sandboxId) {\n throw new Error(`cloud box ${box.name} has no sandboxId — record is malformed`);\n }\n const snapshotName = cloudSnapshotName(box.projectRoot, name);\n await backend.createSnapshot({ sandboxId: box.cloud.sandboxId }, snapshotName);\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 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 async remove(projectRoot: string, ref: string) {\n const entry = await resolveCloudCheckpoint(projectRoot, backend.name, ref);\n if (!entry) return;\n if (backend.deleteSnapshot) {\n try {\n await backend.deleteSnapshot(entry.manifest.snapshotName);\n } catch {\n // Best-effort: even if the remote delete fails (network, perms,\n // or already-gone), drop the local manifest so the user isn't\n // stuck with a pointer to nothing. They can clean up the orphan\n // snapshot from the Daytona dashboard.\n }\n }\n await removeCloudCheckpointDir(projectRoot, backend.name, ref);\n },\n };\n}\n\n/**\n * Build the inner shell command tmux runs inside the cloud sandbox for an\n * attach. The string is later embedded in `ssh ... -t '<cmd>'`, so it must\n * be a single shell-safe phrase (the SSH client passes it to the remote\n * `sshd` which feeds it to the user's login shell).\n *\n * Three-stage: ensure the session exists (idempotent), apply the same\n * tmux configuration the docker provider uses (prefix remap, extended-keys,\n * `status off` to hide the inner status bar so it doesn't double up with\n * the wrapped-pty footer — see {@link buildTmuxConfigShellSnippet}), then\n * `exec tmux attach`. We can't use `tmux new-session -A` here because it\n * would attach before the `set` commands run; `has-session || new-session -d`\n * keeps the session detached long enough to configure it. `-c /workspace`\n * starts the session in the box's workspace dir so claude/codex/opencode\n * see /workspace as their cwd (otherwise tmux inherits the SSH login\n * shell's $HOME and the agents prompt for workspace-trust).\n *\n * The command is prefixed with the shared {@link TERM_FALLBACK_SNIPPET} (same\n * guard the docker provider applies): hetzner/daytona forward the host TERM\n * over `ssh -t`, and vercel/e2b forward it via their attach builders, so a\n * host TERM the box's terminfo doesn't carry (e.g. xterm-ghostty on Ubuntu)\n * would otherwise make `tmux attach` exit immediately (\"missing or unsuitable\n * terminal\"). The guard downgrades the unknown case to xterm-256color before\n * tmux runs, and is a no-op (`infocmp` missing → also downgrades) when the box\n * lacks `infocmp`, so it never regresses the providers that hardcoded TERM.\n */\n/**\n * The host TERM to forward into a cloud box, sanitized to a safe terminfo\n * name. A terminal name is `[A-Za-z0-9][A-Za-z0-9._+-]*`; anything else (a\n * space, a shell metacharacter) is rejected to `xterm-256color` because the\n * vercel provider interpolates this into a `bash -lc` prelude — an unquoted,\n * attacker-shaped TERM could otherwise split the export or inject a command.\n * The box's terminfo is the real filter anyway: renderInnerCommand's guard\n * downgrades any forwarded TERM the box doesn't actually carry.\n */\nexport function hostTermForCloud(): string {\n const t = process.env['TERM'];\n return t && /^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(t) ? t : 'xterm-256color';\n}\n\nexport function renderInnerCommand(kind: AttachKind, opts?: BuildAttachOptions): string {\n const sessionName = opts?.sessionName ?? defaultSessionName(kind);\n const fallback = opts?.command ?? defaultCommand(kind, opts);\n if (kind === 'logs') {\n // logs always tails; tmux makes no sense here.\n return fallback;\n }\n if (opts?.noTmux) {\n return fallback;\n }\n const sessionQ = shellSingle(sessionName);\n const cwdQ = shellSingle(CLOUD_WORKSPACE_DIR);\n const fallbackQ = shellSingle(fallback);\n const configSnippet = buildTmuxConfigShellSnippet(sessionName);\n const lines = [\n `command -v tmux >/dev/null || { echo \"tmux not installed in sandbox\"; exit 127; }`,\n `tmux has-session -t ${sessionQ} 2>/dev/null || tmux new-session -d -c ${cwdQ} -s ${sessionQ} ${fallbackQ}`,\n configSnippet,\n ];\n // `detached`: create + configure the session but don't attach. Used to\n // pre-start a session with its full launch command before a new-tab attach\n // re-invokes `agentbox <agent> attach` (which carries no launch args).\n if (opts?.detached) return TERM_FALLBACK_SNIPPET + lines.join('; ');\n return TERM_FALLBACK_SNIPPET + [...lines, `exec tmux attach -t ${sessionQ}`].join('; ');\n}\n\nfunction defaultSessionName(kind: AttachKind): string {\n switch (kind) {\n case 'shell':\n return 'shell';\n case 'agent':\n return 'agent';\n case 'logs':\n return 'logs';\n }\n}\n\nfunction defaultCommand(kind: AttachKind, opts?: BuildAttachOptions): string {\n switch (kind) {\n case 'shell':\n return 'bash -l';\n case 'agent':\n // Caller didn't tell us which agent — fall back to a login shell;\n // claude/codex/opencode wrappers pass an explicit `command`.\n return 'bash -l';\n case 'logs': {\n if (!opts?.service) {\n return 'echo \"no service specified — set BuildAttachOptions.service\"';\n }\n // Prefer `agentbox-ctl logs` so the cloud follow stream matches the\n // docker format (timestamps + stream marker, ring-buffered tail). The\n // ctl daemon binds the unix socket regardless of how we exec in.\n const tail = opts.tail !== undefined ? String(opts.tail) : '200';\n const args = [`--tail ${shellSingle(tail)}`];\n if (opts.follow !== false) args.push('--follow');\n return `/usr/local/bin/agentbox-ctl logs ${shellSingle(opts.service)} ${args.join(' ')}`;\n }\n }\n}\n\n/** Wrap an arbitrary string in single quotes for embedding in a shell command. */\nfunction shellSingle(s: string): string {\n return \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n\n/** Helper: returns a BoxResourceStats stub so callers needn't unwrap optional. */\nexport function emptyCloudStats(provider: string): BoxResourceStats {\n return {\n source: provider,\n live: false,\n cpuPercent: null,\n memUsedBytes: null,\n memLimitBytes: null,\n memPercent: null,\n pids: null,\n diskUsedBytes: null,\n snapshotDiskBytes: null,\n checkpointVolumeBytes: null,\n netRxBytes: null,\n netTxBytes: null,\n blockReadBytes: null,\n blockWriteBytes: null,\n limits: { memoryBytes: null, cpus: null, pidsLimit: null, disk: null },\n warnings: [],\n };\n}\n","/**\n * `makeCloudSync` — the co-located `ProviderSync` facade for the cloud providers\n * (one shared default over any `CloudBackend`). THIS FILE is \"everything a cloud\n * box syncs\": one method per shared sync op, each a thin delegation to the\n * existing cloud seed/upload/credential function, byte-identical to the\n * pre-facade `createCloudProvider.create()` path.\n *\n * Handle: the backend is closed over by `createCloudProvider`; `makeCloudSync`\n * additionally closes the per-box `CloudHandle`. The create path passes the\n * resolved credential-volume `agents` (from `ensureAgentVolumesForCloud`) so\n * `seedCredentials` knows which agents have a volume to seed — the cloud analog\n * of docker's handle-carries-specs. Post-create (`provider.sync(box)`) omits it;\n * only `resyncWorkspace` (7.5) + `extractCredentials` run then.\n *\n * NOT here (deliberate carve-outs, mirroring docker): **workspace seed**\n * (`seedCloudWorkspace` — the in-box clone / checkpoint overlay, no facade analog)\n * and the **static agent config** (baked into the snapshot at `prepare`, not a\n * runtime seed). Both are referenced by create() directly. See\n * `docs/sync-architecture.md` §\"Deliberate non-unifications\".\n */\n\nimport type {\n CarryApplyResult,\n CloudBackend,\n CloudHandle,\n GitWorktreeRecord,\n ProviderSync,\n ResolvedCarryEntry,\n ResyncResult,\n SyncContext,\n} from '@agentbox/core';\nimport { dryRunProviderSync, SYNC_DRYRUN_ENV } from '@agentbox/core';\nimport { renderCarryEntries } from '@agentbox/sandbox-core';\nimport { resyncCloudWorkspace } from './workspace-resync.js';\nimport {\n type CloudAgentKind,\n ensureAgentHomeDirsOwned,\n extractCloudAgentCredentials,\n refreshAgentCredentialsBackup,\n seedAgentVolumesIfFresh,\n seedOpencodeModelState,\n} from './agent-credentials.js';\nimport { seedDynamicConfig } from './dynamic-sync.js';\nimport { ensureCodexAgentsOverride } from './codex-agents-override.js';\nimport { seedClaudeJsonAtCreate } from './claude-json-overlay.js';\nimport { seedGitIdentity as seedCloudGitIdentity } from './git-identity.js';\nimport { uploadEnvFiles } from './env-files.js';\nimport { uploadCarryPaths } from './carry.js';\n\nexport interface CloudSyncOptions {\n /**\n * Agent kinds with a credentials volume/dir to seed (create-path). From\n * `ensureAgentVolumesForCloud(...).agents`. Omitted post-create.\n */\n agents?: CloudAgentKind[];\n}\n\nexport function makeCloudSync(\n backend: CloudBackend,\n handle: CloudHandle,\n opts: CloudSyncOptions = {},\n): ProviderSync {\n if (process.env[SYNC_DRYRUN_ENV]) return dryRunProviderSync(backend.name);\n return {\n // Cloud live-box resync: pre-fetch the host commits into the box, then run\n // the shared resync concern (merge + overlay, box wins; never reset --hard).\n // See workspace-resync.ts. The provider's resyncWorkspace(box) re-derives the\n // worktrees (detectGitRepos) + gates on hostSeeded before calling here.\n async resyncWorkspace(\n ctx: SyncContext,\n worktrees: GitWorktreeRecord[],\n ): Promise<ResyncResult> {\n if (worktrees.length === 0) return { repos: [], hadConflicts: false };\n const repos = await resyncCloudWorkspace(backend, handle, worktrees, ctx.onLog);\n const hadConflicts = repos.some(\n (r) => r.mergeConflicts.length > 0 || r.overlaySkipped.length > 0,\n );\n return { repos, hadConflicts };\n },\n\n async seedAgentConfig(ctx: SyncContext): Promise<void> {\n // The runtime agent-config seeds (static config is baked into the snapshot\n // at prepare). In create order:\n // - normalize the agent static-config home dirs to vscode ownership;\n // - fold the box facts into ~/.codex/AGENTS.override.md;\n // - seed the host's OpenCode model into the box state dir;\n // - overlay ~/.claude/_claude.json from the host's ~/.claude.json;\n // - seed the dynamic Claude config (workflows/ + this project's memory/).\n await ensureAgentHomeDirsOwned(backend, handle, { onLog: ctx.onLog });\n await ensureCodexAgentsOverride(backend, handle, { onLog: ctx.onLog });\n await seedOpencodeModelState(backend, handle, { onLog: ctx.onLog });\n await seedClaudeJsonAtCreate(backend, handle, {\n hostWorkspace: ctx.hostWorkspace,\n onLog: ctx.onLog,\n });\n await seedDynamicConfig(backend, handle, {\n workspacePath: ctx.hostWorkspace,\n onLog: ctx.onLog,\n });\n },\n\n async seedCredentials(ctx: SyncContext): Promise<void> {\n // Refresh the host-side backups from the docker shared volumes (best-effort,\n // gated on expiry) BEFORE pushing them into the box, then seed the per-agent\n // credentials (volume backends: idempotent via marker; ephemeral: push fresh).\n await refreshAgentCredentialsBackup({ onLog: ctx.onLog });\n const agents = opts.agents ?? [];\n if (agents.length > 0) {\n await seedAgentVolumesIfFresh(backend, handle, {\n agents,\n hostWorkspace: ctx.hostWorkspace,\n onLog: ctx.onLog,\n });\n }\n },\n\n extractCredentials(): Promise<string[]> {\n // Capture the box's agent login(s) back to the host backups. Cloud-only\n // (the box has no shared host auth path); the CLI calls it on\n // `checkpoint create --set-default`.\n return extractCloudAgentCredentials(backend, handle);\n },\n\n async seedGitIdentity(ctx: SyncContext): Promise<void> {\n // Cloud boxes have no bind-mounted ~/.gitconfig, so configure a committer\n // identity (host user when resolvable, else a generic agentbox identity).\n await seedCloudGitIdentity(backend, handle, {\n hostRepo: ctx.hostWorkspace,\n onLog: ctx.onLog,\n });\n },\n\n async seedEnvFiles(ctx: SyncContext, patterns: string[]): Promise<{ copied: number }> {\n return uploadEnvFiles({\n backend,\n handle,\n workspacePath: ctx.hostWorkspace,\n files: patterns,\n workspaceDir: ctx.boxWorkspace,\n onLog: ctx.onLog,\n });\n },\n\n async applyCarry(ctx: SyncContext, entries: ResolvedCarryEntry[]): Promise<CarryApplyResult> {\n const rendered = await renderCarryEntries(\n entries,\n {\n name: ctx.boxName,\n id: ctx.boxId,\n kind: 'cloud',\n hostWorkspace: ctx.hostWorkspace,\n projectRoot: ctx.projectRoot,\n },\n ctx.onLog,\n );\n return uploadCarryPaths({ backend, handle, entries: rendered, onLog: ctx.onLog });\n },\n };\n}\n","/**\n * Cloud live-box workspace resync — the cloud analog of docker's session-start\n * `resyncWorkspaceFromHost`, closing the \"Phase 2\" gap. A cloud box has no host\n * `.git/` bind mount, so the host branch tip isn't in the box's object store and\n * the concern's central `git merge <hostRef>` can't run directly.\n *\n * Core idea: **pre-fetch, then reuse `resyncWorkspace` UNCHANGED.** For each\n * worktree we (1) find the shared ancestor `P` (the fork base `S`, already in the\n * box), (2) ship `P..H` (host tip) + a `git stash create` object as a git bundle\n * and fetch it into the box under private `refs/agentbox-resync/*`, then (3) run\n * the golden-tested `resyncWorkspace` orchestration with cloud ports:\n * - `resolveHostRef` returns the in-box `refs/agentbox-resync/target` (or null\n * when no shared ancestor → the concern skips the merge, still overlays\n * untracked — non-destructive);\n * - `createHostStash` returns the bundled stash SHA (now an in-box object, so\n * `git stash apply <sha>` resolves);\n * - the other host ports (`listHostUntracked`/`hashHostFile`/`packHostFiles`)\n * are the shared `makeHostGitPorts()`;\n * - the box ports run via `backend.exec`/`uploadFile`.\n *\n * **Never `reset --hard`.** The merge only ADDs a merge commit (box work survives\n * as its first parent); box wins every conflict. Failure modes degrade to a\n * non-destructive untracked overlay or a no-op. This is the only net-new-behaviour\n * piece of the sync refactor — it mutates a live box working dir.\n */\n\nimport { execa } from 'execa';\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport type {\n CloudBackend,\n CloudHandle,\n RepoResyncResult,\n ResyncExecResult,\n ResyncWorktree,\n WorkspaceResyncPorts,\n} from '@agentbox/core';\nimport { makeHostGitPorts, resyncWorkspace } from '@agentbox/sandbox-core';\nimport { bashScript, quoteShellArg, quoteShellArgv } from '../shell.js';\n\n/** Private in-box refs the pre-fetch writes; force-updated each resync, cleaned up after. */\nconst TARGET_REF = 'refs/agentbox-resync/target';\nconst STASH_REF = 'refs/agentbox-resync/stash';\nconst SHA_RE = /^[0-9a-f]{40}$/;\n/** Cap on the box branch walk when searching for the shared ancestor. */\nconst BOX_REVLIST_CAP = 500;\n\ninterface Prefetched {\n /** The in-box merge target ref, or null when no shared ancestor was found (skip merge). */\n targetRef: string | null;\n /** The bundled host stash SHA (now an in-box object), or null when clean/unusable. */\n stashSha: string | null;\n /** The worktree's box branch — the resolveHostRef fallback so untracked overlay still runs. */\n branch: string;\n}\n\n/**\n * Resync each cloud box worktree with the host's current state (merge + overlay,\n * box wins). Pre-fetches the host commits into the box, then drives the\n * provider-neutral `resyncWorkspace` concern through cloud ports.\n */\nexport async function resyncCloudWorkspace(\n backend: CloudBackend,\n handle: CloudHandle,\n worktrees: ResyncWorktree[],\n onLog?: (line: string) => void,\n): Promise<RepoResyncResult[]> {\n const log = onLog ?? (() => {});\n // Vercel/E2B wrap non-root execs in `sudo -u vscode -H bash -lc`, whose extra\n // re-parse mangles the untracked probe's `$(...)`/`$var`/`while` (→ hang). The\n // probe is read-only, so run it as root there (single `bash -lc`, no re-parse).\n const probeAsRoot = backend.name === 'vercel' || backend.name === 'e2b';\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-resync-'));\n const prefetch = new Map<string, Prefetched>();\n try {\n for (const [i, w] of worktrees.entries()) {\n prefetch.set(w.hostMainRepo, await prefetchRepo(backend, handle, w, stage, i, log));\n }\n\n const hostPorts = makeHostGitPorts();\n const ports: WorkspaceResyncPorts = {\n ...hostPorts,\n // Merge target = the in-box temp ref. When no shared ancestor was found we\n // fall back to the box branch: the concern treats `hostRef === boxBranch`\n // as \"merging self\" and skips the merge, but STILL overlays the host's\n // untracked files (non-destructive, box wins) — whereas a null ref would\n // make it skip the whole repo. stashSha is null in that case (no bundle),\n // so the stash overlay is skipped too.\n resolveHostRef: (hostMain) => {\n const pf = prefetch.get(hostMain);\n return Promise.resolve(pf ? (pf.targetRef ?? pf.branch) : null);\n },\n // The stash object is in-box (bundled + fetched); the concern applies by SHA.\n createHostStash: (hostMain) => Promise.resolve(prefetch.get(hostMain)?.stashSha ?? null),\n boxGit: (ct, args) => boxGit(backend, handle, ct, args),\n probeUntrackedTokens: (ct, paths) => probeUntrackedTokens(backend, handle, ct, paths, probeAsRoot),\n applyTarToBox: (ct, tar) => applyTarToBox(backend, handle, stage, ct, tar),\n };\n\n const results = await resyncWorkspace(worktrees, ports, log);\n await cleanupBoxRefs(backend, handle, worktrees, prefetch);\n return results;\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n}\n\n/**\n * Pre-fetch one repo's host commits into the box. Returns the in-box merge\n * target ref + bundled stash SHA, or `{ null, null }` to signal \"no merge\"\n * (overlay-only, non-destructive) on any miss.\n */\nasync function prefetchRepo(\n backend: CloudBackend,\n handle: CloudHandle,\n w: ResyncWorktree,\n stage: string,\n idx: number,\n log: (line: string) => void,\n): Promise<Prefetched> {\n const ct = w.containerPath;\n const hostMain = w.hostMainRepo;\n const none: Prefetched = { targetRef: null, stashSha: null, branch: w.branch };\n\n // 1. The box branch's commits (newest first), capped.\n const rev = await backend.exec(\n handle,\n bashScript(`git -C ${quoteShellArg(ct)} rev-list --max-count=${String(BOX_REVLIST_CAP)} ${quoteShellArg(w.branch)} 2>/dev/null || true`),\n );\n const boxShas = rev.stdout\n .split('\\n')\n .map((s) => s.trim())\n .filter((s) => SHA_RE.test(s));\n if (boxShas.length === 0) {\n log(`resync: ${ct}: box branch has no commits; overlay only`);\n return none;\n }\n\n // 2. Shared ancestor P = the first box commit the host still has (= the fork\n // base S; box-only commits above S don't exist on the host).\n const batch = await execa(\n 'git',\n ['-C', hostMain, 'cat-file', '--batch-check=%(objectname) %(objecttype)'],\n { input: boxShas.join('\\n'), reject: false },\n );\n const present = new Set<string>();\n for (const line of batch.stdout.split('\\n')) {\n const parts = line.trim().split(' ');\n if (parts.length >= 2 && parts[1] === 'commit' && parts[0]) present.add(parts[0]);\n }\n const base = boxShas.find((s) => present.has(s));\n if (!base) {\n log(`resync: ${ct}: no shared ancestor with the host (repo replaced?); overlay only (non-destructive)`);\n return none;\n }\n\n // 3. Host tip H + an uncommitted-changes stash object.\n const hRes = await execa('git', ['-C', hostMain, 'rev-parse', 'HEAD'], { reject: false });\n const hostTip = hRes.stdout.trim();\n if (hRes.exitCode !== 0 || !SHA_RE.test(hostTip)) return none;\n const stashRes = await execa('git', ['-C', hostMain, 'stash', 'create'], { reject: false });\n const stashSha =\n stashRes.exitCode === 0 && SHA_RE.test(stashRes.stdout.trim()) ? stashRes.stdout.trim() : null;\n\n // 4. Bundle P..H (+ the stash object), excluding everything the box already\n // has (`^base`). The box holds `base`, so the prerequisite is satisfiable\n // even though a cloud clone is shallow — no `--unshallow` ever needed.\n // Only ship the target when the host actually advanced (`H !== base`);\n // otherwise `target=H ^H` is an empty range (git makes a ref-less bundle →\n // the in-box fetch can't find it). The stash object is always new content\n // (its tree isn't reachable from `base`), so it's bundled whenever present.\n const needTarget = hostTip !== base;\n const bundleRefs: string[] = [];\n if (needTarget) bundleRefs.push(TARGET_REF);\n if (stashSha) bundleRefs.push(STASH_REF);\n if (bundleRefs.length === 0) {\n log(`resync: ${ct}: already up to date with the host; overlay untracked only`);\n return { targetRef: null, stashSha: null, branch: w.branch };\n }\n\n const bundlePath = join(stage, `resync-${String(idx)}.bundle`);\n try {\n if (needTarget) await execa('git', ['-C', hostMain, 'update-ref', TARGET_REF, hostTip], { reject: false });\n if (stashSha) await execa('git', ['-C', hostMain, 'update-ref', STASH_REF, stashSha], { reject: false });\n const b = await execa(\n 'git',\n ['-C', hostMain, 'bundle', 'create', bundlePath, ...bundleRefs, `^${base}`],\n { reject: false },\n );\n if (b.exitCode !== 0) {\n log(`resync: ${ct}: bundle build failed; overlay only: ${(b.stderr || '').split('\\n')[0]}`);\n return none;\n }\n } finally {\n if (needTarget) await execa('git', ['-C', hostMain, 'update-ref', '-d', TARGET_REF], { reject: false });\n if (stashSha) await execa('git', ['-C', hostMain, 'update-ref', '-d', STASH_REF], { reject: false });\n }\n\n // 5. Upload + fetch the bundle into the worktree's own .git (private refs).\n const remote = `/tmp/agentbox-resync-${String(idx)}.bundle`;\n await backend.uploadFile(handle, bundlePath, remote);\n const refspecs = bundleRefs.map((r) => `+${r}:${r}`);\n const fetch = await backend.exec(\n handle,\n bashScript(\n `git -C ${quoteShellArg(ct)} fetch --no-tags ${quoteShellArg(remote)} ${refspecs\n .map((r) => quoteShellArg(r))\n .join(' ')} && rm -f ${quoteShellArg(remote)}`,\n ),\n );\n if (fetch.exitCode !== 0) {\n log(`resync: ${ct}: in-box bundle fetch failed; overlay only: ${(fetch.stderr || fetch.stdout || '').split('\\n')[0]}`);\n return none;\n }\n log(\n needTarget\n ? `resync: ${ct}: fetched host commits (${base.slice(0, 8)}..${hostTip.slice(0, 8)})${stashSha ? ' + host stash' : ''}`\n : `resync: ${ct}: no new host commits; fetched host stash only`,\n );\n // targetRef null when the host didn't advance → merge skipped, stash + untracked overlay run.\n return { targetRef: needTarget ? TARGET_REF : null, stashSha, branch: w.branch };\n}\n\n/** Box-side git via `backend.exec` (mirrors docker's `execInBox` boxGit port). */\nasync function boxGit(\n backend: CloudBackend,\n handle: CloudHandle,\n ct: string,\n args: string[],\n): Promise<ResyncExecResult> {\n const cmd = `git -C ${quoteShellArg(ct)} ${quoteShellArgv(args)}`;\n const r = await backend.exec(handle, bashScript(cmd));\n return { exitCode: r.exitCode, stdout: r.stdout, stderr: r.stderr };\n}\n\n/**\n * Probe the box for each host-untracked path: sha256 for a regular file, the\n * non-regular sentinel (`-`) for a dir/symlink, omitted when absent. Paths are\n * fed base64-encoded (no stdin to `backend.exec`, and the box lacks `/dev/fd`).\n */\nasync function probeUntrackedTokens(\n backend: CloudBackend,\n handle: CloudHandle,\n ct: string,\n relPaths: string[],\n asRoot: boolean,\n): Promise<Map<string, string>> {\n const tokens = new Map<string, string>();\n if (relPaths.length === 0) return tokens;\n const payload = Buffer.from(relPaths.join('\\0')).toString('base64');\n const script =\n `printf %s ${quoteShellArg(payload)} | base64 -d | ( cd ${quoteShellArg(ct)} && ` +\n `while IFS= read -r -d '' f; do ` +\n `if [ -f \"$f\" ] && [ ! -L \"$f\" ]; then printf '%s\\\\0%s\\\\0' \"$(sha256sum < \"$f\" | cut -d' ' -f1)\" \"$f\"; ` +\n `elif [ -e \"$f\" ]; then printf '%s\\\\0%s\\\\0' '-' \"$f\"; fi; done )`;\n const r = await backend.exec(handle, bashScript(script), asRoot ? { user: 'root' } : undefined);\n if (r.exitCode === 0) {\n const flat = r.stdout.split('\\0').filter((s) => s.length > 0);\n for (let i = 0; i + 1 < flat.length; i += 2) {\n const token = flat[i];\n const path = flat[i + 1];\n if (token !== undefined && path !== undefined) tokens.set(path, token);\n }\n }\n return tokens;\n}\n\n/** Extract a host-packed tar into the box worktree (buffer → temp file → upload → tar -xf). */\nasync function applyTarToBox(\n backend: CloudBackend,\n handle: CloudHandle,\n stage: string,\n ct: string,\n tar: Buffer,\n): Promise<void> {\n const local = join(stage, 'overlay.tar');\n await writeFile(local, tar);\n const remote = '/tmp/agentbox-resync-overlay.tar';\n await backend.uploadFile(handle, local, remote);\n await backend.exec(\n handle,\n bashScript(`tar -C ${quoteShellArg(ct)} -xf ${quoteShellArg(remote)} && rm -f ${quoteShellArg(remote)}`),\n );\n}\n\n/** Best-effort removal of the private in-box refs after the resync. */\nasync function cleanupBoxRefs(\n backend: CloudBackend,\n handle: CloudHandle,\n worktrees: ResyncWorktree[],\n prefetch: Map<string, Prefetched>,\n): Promise<void> {\n for (const w of worktrees) {\n if (!prefetch.get(w.hostMainRepo)?.targetRef) continue;\n const ct = quoteShellArg(w.containerPath);\n await backend\n .exec(\n handle,\n bashScript(\n `git -C ${ct} update-ref -d ${TARGET_REF} 2>/dev/null || true; git -C ${ct} update-ref -d ${STASH_REF} 2>/dev/null || true`,\n ),\n )\n .catch(() => {});\n }\n}\n","/**\n * Build a single shell-safe command string from an argv array. Used everywhere\n * we hand a cloud backend's `exec(handle, cmd, ...)` an argv that originated\n * from CLI input — single-quoting every arg neutralises shell metacharacters.\n */\nexport function quoteShellArgv(argv: readonly string[]): string {\n return argv.map(quoteShellArg).join(' ');\n}\n\nexport function quoteShellArg(arg: string): string {\n if (arg.length === 0) return \"''\";\n // Fast-path for safe identifiers, paths, simple options: avoid quotes for\n // readability in logs. Anything else falls through to single-quoting.\n if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(arg)) return arg;\n return \"'\" + arg.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n\n/**\n * Wrap a multi-line shell script body so it runs under `bash -c` regardless\n * of what `/bin/sh` points at in the sandbox. Necessary on Daytona's images\n * where `executeCommand` shells out via `dash`, which rejects bash idioms\n * like `set -o pipefail`. Use this for any script that isn't trivially\n * POSIX-only.\n */\nexport function bashScript(body: string): string {\n return `bash -c ${quoteShellArg(body)}`;\n}\n","/**\n * Cloud-provider **credentials volume** management — the per-create half of\n * the agent state split. The other half (static config: plugins, skills,\n * settings, marketplaces, codex `config.toml`, opencode `config/`) is\n * layered into the published Daytona snapshot at\n * `agentbox prepare --provider daytona` time via the documented\n * `daytona.snapshot.create({ name, image })` API + `Image.fromDockerfile(...)\n * .addLocalFile(...).runCommands(...)` (see\n * `packages/sandbox-daytona/src/prepare.ts`).\n *\n * What lives here is the runtime side: credentials (`.credentials.json` for\n * claude, `auth.json` for codex/opencode) live on a single per-org\n * `agentbox-credentials` Daytona volume, mounted three times via `subpath`\n * at `/home/vscode/.agentbox-creds/{claude,codex,opencode}/`. Symlinks\n * baked into the box image route the agent-expected paths\n * (`~/.claude/.credentials.json` etc.) through to the volume.\n *\n * `seedAgentVolumesIfFresh` runs at every `agentbox create --provider\n * daytona`: it probes the per-agent marker file in the credentials volume\n * and uploads a tiny credentials-only tarball when missing. Re-seeding is\n * **explicit only** — vanilla create never overwrites credentials it\n * already finds. `agentbox daytona resync` passes `force: true` to refresh\n * after a host re-auth.\n */\n\nimport {\n DEFAULT_BOX_IMAGE,\n SHARED_CLAUDE_VOLUME,\n SHARED_CODEX_VOLUME,\n SHARED_OPENCODE_VOLUME,\n extractCodexCredentials,\n extractOpencodeCredentials,\n syncClaudeCredentials,\n} from '@agentbox/sandbox-docker';\nimport {\n stageClaudeStaticForUpload,\n stageClaudeCredentialsForUpload,\n stageCodexStaticForUpload,\n stageCodexCredentialsForUpload,\n stageOpencodeStaticForUpload,\n stageOpencodeCredentialsForUpload,\n stageOpencodeStateForUpload,\n extractCredentials,\n hostClaudeBackupExpired,\n SEED_MARKER,\n type StageResult,\n} from '@agentbox/sandbox-core';\nimport type { CloudBackend, CloudHandle, CloudVolumeMount } from '@agentbox/core';\nimport { createCloudSyncTransport } from './sync-transport.js';\n\n/** Identifier for one of the three agents we sync into cloud sandboxes. */\nexport type CloudAgentKind = 'claude' | 'codex' | 'opencode';\n\n/**\n * Single per-org volume that holds all three agents' credentials. Mounted\n * three times via `subpath` so each agent's tokens get their own dir without\n * the volumes-API churn of registering three separate volumes.\n */\nconst CREDENTIALS_VOLUME = 'agentbox-credentials';\n\n/**\n * Per-agent metadata. `staticMountPath` is where the snapshot-baked static\n * config lives in the sandbox FS; `credentialsMountPath` is where the\n * credentials volume's per-agent subpath gets attached at runtime.\n * `credentialsSubpath` is the subdir inside the shared volume.\n */\ninterface AgentSpec {\n kind: CloudAgentKind;\n /** Where stage*Static tarballs extract (sandbox FS, snapshot-captured). */\n staticMountPath: string;\n /** Where the credentials-volume subpath gets mounted at runtime. */\n credentialsMountPath: string;\n /** Subdir of the shared credentials volume for this agent. */\n credentialsSubpath: string;\n stageStatic: (opts: { hostWorkspace?: string }) => Promise<StageResult>;\n stageCredentials: () => Promise<StageResult>;\n}\n\nconst AGENT_SPECS: AgentSpec[] = [\n {\n kind: 'claude',\n staticMountPath: '/home/vscode/.claude',\n credentialsMountPath: '/home/vscode/.agentbox-creds/claude',\n credentialsSubpath: 'claude/',\n stageStatic: (opts) => stageClaudeStaticForUpload({ hostWorkspace: opts.hostWorkspace }),\n stageCredentials: () => stageClaudeCredentialsForUpload(),\n },\n {\n kind: 'codex',\n staticMountPath: '/home/vscode/.codex',\n credentialsMountPath: '/home/vscode/.agentbox-creds/codex',\n credentialsSubpath: 'codex/',\n stageStatic: () => stageCodexStaticForUpload(),\n stageCredentials: () => stageCodexCredentialsForUpload(),\n },\n {\n kind: 'opencode',\n staticMountPath: '/home/vscode/.local/share/opencode',\n credentialsMountPath: '/home/vscode/.agentbox-creds/opencode',\n credentialsSubpath: 'opencode/',\n stageStatic: () => stageOpencodeStaticForUpload(),\n stageCredentials: () => stageOpencodeCredentialsForUpload(),\n },\n];\n\nimport {\n CLAUDE_FORWARDED_ENV_KEYS,\n CODEX_FORWARDED_ENV_KEYS,\n OPENCODE_FORWARDED_ENV_KEYS,\n} from '@agentbox/sandbox-docker';\n\n/** Result of `ensureAgentVolumesForCloud` — pass `.mounts` straight into `provision({ volumes })`. */\nexport interface EnsureAgentVolumesResult {\n /** Volume mounts ready for `CloudProvisionRequest.volumes`. */\n mounts: CloudVolumeMount[];\n /**\n * Env vars to merge into the sandbox env at provision time. Includes\n * `OPENCODE_CONFIG_DIR` (so the in-box opencode reads its config from the\n * snapshot-baked `config/` subdir of its data dir) and any forwarded\n * provider API keys present in the host env.\n */\n env: Record<string, string>;\n /**\n * Agents we successfully reserved credentials mounts for. Pass back into\n * `seedAgentVolumesIfFresh` so it doesn't redo the kind list.\n */\n agents: CloudAgentKind[];\n}\n\n/**\n * Reserve the shared `agentbox-credentials` volume and return three subpath\n * mounts ready to thread into `CloudProvisionRequest.volumes`. Backends that\n * don't implement `ensureVolume` get an empty mount list (and a one-line log)\n * — the in-box agents fall back to interactive login.\n *\n * Idempotent: every call is a fast lookup for the already-created volume.\n * Safe to call on every `create`.\n */\nexport async function ensureAgentVolumesForCloud(\n backend: CloudBackend,\n opts: { onLog?: (line: string) => void } = {},\n): Promise<EnsureAgentVolumesResult> {\n const log = opts.onLog ?? (() => {});\n const allAgents = AGENT_SPECS.map((s) => s.kind);\n if (typeof backend.ensureVolume !== 'function') {\n // Non-volume backends (e2b, vercel, hetzner) still get credentials seeded\n // per-create — `seedAgentVolumesIfFresh` falls back to a direct upload+\n // extract into the box-baked `~/.agentbox-creds/<agent>/` dirs. The mounts\n // list stays empty (nothing to persist across boxes) but the agent list is\n // populated so the seed actually runs.\n log(\n `cloud backend '${backend.name}' has no volume primitive — agent credentials seeded per-create only`,\n );\n return { mounts: [], env: buildForwardedEnv(allAgents), agents: allAgents };\n }\n\n let volumeId: string;\n try {\n const ensured = await backend.ensureVolume(CREDENTIALS_VOLUME);\n volumeId = ensured.volumeId;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n log(`ensureVolume(${CREDENTIALS_VOLUME}) failed (skipping credentials seed): ${msg}`);\n return { mounts: [], env: buildForwardedEnv([]), agents: [] };\n }\n\n const mounts: CloudVolumeMount[] = AGENT_SPECS.map((spec) => ({\n volumeId,\n mountPath: spec.credentialsMountPath,\n subpath: spec.credentialsSubpath,\n }));\n return { mounts, env: buildForwardedEnv(allAgents), agents: allAgents };\n}\n\nfunction buildForwardedEnv(agents: CloudAgentKind[]): Record<string, string> {\n const env: Record<string, string> = {};\n // OpenCode reads its config dir from $OPENCODE_CONFIG_DIR; the snapshot\n // bake puts the config files at <data dir>/config/ to match what the\n // Docker provider does (see buildOpencodeMounts).\n if (agents.includes('opencode')) {\n env['OPENCODE_CONFIG_DIR'] = '/home/vscode/.local/share/opencode/config';\n }\n // Forward provider API keys from the host process env into the sandbox.\n // For agents authenticated via env-var (ANTHROPIC_API_KEY etc.) rather\n // than a stored auth file, this is the only way the in-box agent finds\n // its credentials. Mirrors the Docker provider's per-agent forwarding.\n const forwardedKeys = new Set<string>([\n ...CLAUDE_FORWARDED_ENV_KEYS,\n ...CODEX_FORWARDED_ENV_KEYS,\n ...OPENCODE_FORWARDED_ENV_KEYS,\n ]);\n for (const k of forwardedKeys) {\n const v = process.env[k];\n if (typeof v === 'string' && v.length > 0) env[k] = v;\n }\n return env;\n}\n\nexport interface SeedAgentVolumesOptions {\n /** Which agents to consider seeding. Defaults to all three. */\n agents?: CloudAgentKind[];\n /**\n * The host-absolute workspace path being mounted at `/workspace` inside\n * the box. Currently unused by the credentials-only seed (no `_claude.json`\n * involved), but kept on the interface for symmetry with the bake step\n * and forward compat with future credential-side rewrites.\n */\n hostWorkspace?: string;\n /**\n * When true, ignore the in-volume seed marker and re-upload. Used by\n * `agentbox daytona resync` and by the host-login flow. Default: false\n * (vanilla create never overwrites a seeded volume).\n */\n force?: boolean;\n onLog?: (line: string) => void;\n}\n\n/**\n * For each enabled agent: probe the credentials-subpath\n * `<credentialsMountPath>/.agentbox-seeded-at` marker via `backend.exec`. If\n * absent (or `force: true`), stage a credentials-only tarball, upload via\n * `backend.uploadFile`, extract inside the sandbox into the credentials\n * mount.\n *\n * Idempotent and safe to call on every `create`. Warnings from staging (e.g.\n * codex Keychain landmine) are forwarded via `onLog`. The payload is a\n * single small file per agent, so the FUSE-volume pathology that plagues\n * the static seed is irrelevant here.\n */\nexport async function seedAgentVolumesIfFresh(\n backend: CloudBackend,\n handle: CloudHandle,\n opts: SeedAgentVolumesOptions = {},\n): Promise<void> {\n const log = opts.onLog ?? (() => {});\n const wanted = new Set<CloudAgentKind>(opts.agents ?? AGENT_SPECS.map((s) => s.kind));\n const specs = AGENT_SPECS.filter((s) => wanted.has(s.kind));\n // Best-effort per agent: one agent's seed failure (transient SDK error,\n // missing host creds for that agent) must never sink `agentbox create`.\n // Matches the prior vercel/hetzner custom pushers, which caught + warned.\n // The in-box agent then falls back to interactive login.\n await Promise.allSettled(\n specs.map((spec) =>\n seedCredentialsOne(backend, handle, spec, opts).catch((err) => {\n log(\n `${spec.kind}: credentials seed failed (continuing): ${err instanceof Error ? err.message : String(err)}`,\n );\n }),\n ),\n );\n}\n\n/**\n * Force the agent static-config home dirs (`~/.codex`, `~/.claude`,\n * `~/.local/share/opencode`) to be owned by `vscode` on the live box.\n *\n * Why this exists: the agent runs as `vscode`, but a cloud base template can\n * bake these dirs with the wrong owner (E2B's base image ships a `node` user,\n * and the root `npm install -g @openai/codex` step has been observed leaving\n * `~/.codex` as `node:node`). Once we stopped seeding Codex's `state_*.sqlite`\n * index, Codex *creates* it at startup — which fails with EACCES when the dir\n * isn't vscode-writable. A cheap, idempotent chown at create time fixes\n * existing prepared templates without forcing a re-bake.\n *\n * Best-effort: `chown` is rejected on Daytona's S3-backed FUSE volumes, so the\n * command tolerates failure. `chown -R` does not dereference symlinks, so the\n * baked `~/.codex/auth.json -> ~/.agentbox-creds/codex/auth.json` credential\n * symlink (and its peers) are unaffected.\n */\nexport async function ensureAgentHomeDirsOwned(\n backend: CloudBackend,\n handle: CloudHandle,\n opts: { onLog?: (line: string) => void } = {},\n): Promise<void> {\n const log = opts.onLog ?? (() => {});\n const paths = AGENT_SPECS.map((s) => s.staticMountPath).join(' ');\n try {\n await backend.exec(\n handle,\n `sudo -n chown -R vscode:vscode ${paths} 2>/dev/null || true`,\n );\n } catch (err) {\n log(\n `agent home-dir ownership normalize failed (continuing): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Refresh the host-side credential backups (`~/.agentbox/{claude,codex,opencode}-credentials.json`)\n * from the live docker shared volumes BEFORE cloud creates seed from them.\n *\n * Why this exists: `agentbox create --provider <cloud>` reads the host backups\n * to seed cloud boxes, but only the docker create path keeps them current\n * (`syncClaudeCredentials` runs at `packages/sandbox-docker/src/create.ts:593`).\n * Without this refresh, cloud creates push whatever access token the docker\n * volume last extracted — often expired by the time the user actually attaches\n * → in-box `claude` says \"401 Invalid authentication credentials\" even though\n * the box's `.credentials.json` is present.\n *\n * Best-effort: every helper already swallows its own failures (no docker on\n * the host, missing volume, etc.) and returns a noop result. We only nudge —\n * the seed still runs against whatever backup exists.\n *\n * Gated on `hostClaudeBackupExpired`: when the claude backup's `expiresAt` is\n * in the future we skip the docker round-trip entirely (`docker run` against\n * the shared volume is ~1-2s and almost always a noop on fresh tokens).\n */\nexport async function refreshAgentCredentialsBackup(opts: {\n onLog?: (line: string) => void;\n} = {}): Promise<void> {\n const log = opts.onLog ?? (() => {});\n if (!(await hostClaudeBackupExpired())) {\n return;\n }\n log('claude: host credentials backup expired — refreshing from docker shared volume');\n const image = DEFAULT_BOX_IMAGE;\n try {\n const r = await syncClaudeCredentials({ volume: SHARED_CLAUDE_VOLUME }, { image, isolate: false });\n if (r.direction === 'extracted') {\n log('claude: refreshed host credentials backup from docker shared volume');\n } else if (r.direction === 'noop') {\n log('claude: no docker shared volume to refresh from (continuing with existing backup)');\n }\n } catch {\n /* best-effort — syncClaudeCredentials already swallows internally */\n }\n // codex + opencode are extract-only (no docker bind mount of the host's real\n // ~/.codex into the box like claude has), so always try when the docker\n // volume exists. Both helpers return { copied: false } on any error.\n try { await extractCodexCredentials(SHARED_CODEX_VOLUME, image); } catch { /* best-effort */ }\n try { await extractOpencodeCredentials(SHARED_OPENCODE_VOLUME, image); } catch { /* best-effort */ }\n}\n\nasync function seedCredentialsOne(\n backend: CloudBackend,\n handle: CloudHandle,\n spec: AgentSpec,\n opts: SeedAgentVolumesOptions,\n): Promise<void> {\n const log = opts.onLog ?? (() => {});\n // Non-volume backends (e2b, vercel, hetzner) have an ephemeral per-box FS:\n // the `.agentbox-seeded-at` marker can't survive across boxes, and the host\n // tokens are renewable, so we just push fresh every create. Volume backends\n // (daytona) keep the marker-based idempotency so they don't re-upload into\n // a volume already carrying credentials from a previous box.\n const hasVolume = typeof backend.ensureVolume === 'function';\n\n if (hasVolume && !opts.force) {\n const probe = await backend.exec(\n handle,\n `test -f ${spec.credentialsMountPath}/${SEED_MARKER}`,\n );\n if (probe.exitCode === 0) {\n log(`${spec.kind}: credentials already seeded — mounting only`);\n return;\n }\n }\n\n log(`${spec.kind}: staging host credentials`);\n const staged = await spec.stageCredentials();\n for (const w of staged.warnings) log(w);\n try {\n if (staged.tarballPath === null) {\n log(`${spec.kind}: no credentials to seed`);\n return;\n }\n\n let tarSize = 0;\n try {\n const { statSync } = await import('node:fs');\n tarSize = statSync(staged.tarballPath).size;\n } catch {\n /* best-effort */\n }\n const sizeKB = (tarSize / 1024).toFixed(1);\n log(`${spec.kind}: uploading ${sizeKB} KB credentials tarball`);\n const t0 = Date.now();\n const remoteTar = `/tmp/agentbox-${spec.kind}-creds.tar.gz`;\n try {\n await backend.uploadFile(handle, staged.tarballPath, remoteTar);\n } catch (err) {\n // Match the per-agent best-effort the old vercel/hetzner pushers had:\n // a single agent's upload failure (transient SDK error, network blip)\n // must not sink `agentbox create`. Log and fall through; the in-box\n // agent then falls back to interactive login.\n const msg =\n `${spec.kind}: credentials upload failed (${err instanceof Error ? err.message : String(err)}); ` +\n `agent falls back to interactive login`;\n log(msg);\n return;\n }\n const upDt = ((Date.now() - t0) / 1000).toFixed(1);\n log(`${spec.kind}: upload done in ${upDt}s`);\n\n const extractCmd = hasVolume\n ? // Daytona volumes are S3-backed FUSE and reject chmod/utime. The\n // credentials payload is one small file, so we extract straight into\n // the mount with `cp` (not tar — tar would chmod the parent dir during\n // delayed-set-stat and abort with EPERM). Two-step: tar into a local-fs\n // staging dir, then cp the file across. Marker tracks idempotency.\n (() => {\n const stageDir = `/tmp/agentbox-creds-stage-${spec.kind}`;\n return (\n `set -e; ` +\n `rm -rf ${stageDir}; ` +\n `mkdir -p ${stageDir}; ` +\n `tar -xzf ${remoteTar} -C ${stageDir}; ` +\n `cp -r ${stageDir}/. ${spec.credentialsMountPath}/; ` +\n `rm -rf ${stageDir}; ` +\n `date -u +%FT%TZ > ${spec.credentialsMountPath}/${SEED_MARKER}; ` +\n `rm -f ${remoteTar}`\n );\n })()\n : // Ephemeral FS: extract straight into the box-baked `~/.agentbox-creds/\n // <agent>/` dir. `sudo -u vscode` ensures the on-disk file ends up\n // vscode-owned regardless of which user `backend.exec` runs as\n // (e2b: vscode, vercel: vscode, hetzner: vscode via ssh — sudo\n // works on all three because vscode has passwordless sudo). The\n // `--no-same-permissions --no-same-owner -m` flags mirror what\n // vercel/hetzner did in their old custom pushers.\n `set -e; ` +\n `sudo -u vscode mkdir -p ${spec.credentialsMountPath}; ` +\n `sudo -u vscode tar -xzf ${remoteTar} -C ${spec.credentialsMountPath} --no-same-permissions --no-same-owner -m; ` +\n `rm -f ${remoteTar}`;\n const extract = await backend.exec(handle, extractCmd);\n if (extract.exitCode !== 0) {\n const msg =\n `${spec.kind}: credentials extract failed (exit ${String(extract.exitCode)}); ` +\n `agent falls back to interactive login. ` +\n `stdout: ${extract.stdout.slice(-200)} stderr: ${extract.stderr.slice(-200)}`;\n log(msg);\n return;\n }\n log(`${spec.kind}: credentials seeded`);\n } finally {\n await staged.cleanup();\n }\n}\n\n/** Box-side OpenCode state dir (default XDG location; cloud sets no XDG_STATE_HOME). */\nconst OPENCODE_STATE_DIR = '/home/vscode/.local/state/opencode';\n\n/**\n * Seed the host's selected OpenCode model (`~/.local/state/opencode/model.json`)\n * into the box's default state dir, host-authoritative, on **every** create.\n *\n * Unlike credentials (a seed-once volume), the cloud box's state dir is ephemeral\n * — there is no persistent per-box store on either cloud (Daytona's only shared\n * volume holds credentials; Hetzner has none), so the host is authoritative each\n * create and there is no marker to gate on. Without this, OpenCode boots a cloud\n * box with its built-in default model instead of the one the user picked on the\n * host. Provider-agnostic: runs on any `CloudBackend` (`exec` + `uploadFile`).\n *\n * Best-effort: a failure logs and leaves the box on OpenCode's default — it must\n * never fail box creation.\n */\nexport async function seedOpencodeModelState(\n backend: CloudBackend,\n handle: CloudHandle,\n opts: { onLog?: (line: string) => void } = {},\n): Promise<void> {\n const log = opts.onLog ?? (() => {});\n const staged = await stageOpencodeStateForUpload();\n if (staged.tarballPath === null) {\n log('opencode: no host model selection to seed');\n return;\n }\n try {\n const remoteTar = '/tmp/agentbox-opencode-state.tar.gz';\n await backend.uploadFile(handle, staged.tarballPath, remoteTar);\n const res = await backend.exec(\n handle,\n `set -e; mkdir -p ${OPENCODE_STATE_DIR}; ` +\n `tar -xzf ${remoteTar} -C ${OPENCODE_STATE_DIR}; ` +\n `chown -R vscode:vscode ${OPENCODE_STATE_DIR} 2>/dev/null || true; ` +\n `rm -f ${remoteTar}`,\n );\n if (res.exitCode !== 0) {\n log(\n `opencode: model-state seed failed (exit ${String(res.exitCode)}); ` +\n `box falls back to OpenCode's default model. stderr: ${res.stderr.slice(-200)}`,\n );\n return;\n }\n log('opencode: model selection seeded ✓');\n } finally {\n await staged.cleanup();\n }\n}\n\n/**\n * Spec for a single agent — for callers that need the mount path or volume\n * name outside the create flow.\n */\nexport function agentSpecsForCloud(): Array<{\n kind: CloudAgentKind;\n staticMountPath: string;\n credentialsMountPath: string;\n credentialsSubpath: string;\n}> {\n return AGENT_SPECS.map((s) => ({\n kind: s.kind,\n staticMountPath: s.staticMountPath,\n credentialsMountPath: s.credentialsMountPath,\n credentialsSubpath: s.credentialsSubpath,\n }));\n}\n\n/**\n * Extract the agent login credentials from a running cloud box back to the\n * host backups under `~/.agentbox/`, so the next box (seeded by the cloud\n * push) inherits the login. The cloud analogue of docker's\n * `syncClaudeCredentials` extract direction, generalized to codex/opencode —\n * cloud has no shared volume, so a login captured inside a box would otherwise\n * be lost on destroy.\n *\n * Thin wrapper: the provider-neutral `extractCredentials` concern\n * (`@agentbox/sandbox-core`) does the box→host work against the\n * `SyncTransport.readText` seam (registry-driven box paths + host backups + the\n * `isRealAgentCredential` guard); this just injects the `CloudSyncTransport`.\n * `CloudSyncTransport.readText` is `cat <path> 2>/dev/null` with `noRetry`,\n * byte-identical to the extract this used to inline. Best-effort per agent\n * (never throws). Returns the list of agents whose backup was updated.\n */\nexport async function extractCloudAgentCredentials(\n backend: CloudBackend,\n handle: CloudHandle,\n opts: {\n onLog?: (line: string) => void;\n /** Override host backup paths per agent (tests). Defaults to the ~/.agentbox constants. */\n backups?: Partial<Record<CloudAgentKind, string>>;\n } = {},\n): Promise<CloudAgentKind[]> {\n const transport = createCloudSyncTransport({ backend, handle });\n return extractCredentials(transport, { onLog: opts.onLog, backups: opts.backups });\n}\n","/**\n * `CloudSyncTransport` — the cloud implementation of the `SyncTransport` seam\n * (`@agentbox/core`). Wraps a `CloudBackend` + `CloudHandle`: `exec` →\n * `backend.exec`, `applyTarball` → `uploadFile` + `backend.exec(tar -xf …)`,\n * pull → `backend.downloadFile`.\n *\n * `applyTarball` reproduces `uploadEnvFiles`'s extract exactly (`--no-same-\n * permissions --no-same-owner -m`), which also future-proofs against a\n * FUSE-volume `/workspace` tier. `caps.helperContainer` is false — cloud static\n * config is baked into the snapshot at `prepare` time, so `seedVolumeFromHost`\n * is omitted; `ensureVolume` is present only when the backend has a volume API.\n */\n\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type {\n CloudBackend,\n CloudHandle,\n PushOptions,\n SyncExecOptions,\n SyncExecResult,\n SyncTransport,\n TransportCaps,\n} from '@agentbox/core';\nimport { quoteShellArgv } from '../shell.js';\n\nexport interface CloudSyncTransportInit {\n backend: CloudBackend;\n handle: CloudHandle;\n}\n\nexport function createCloudSyncTransport(init: CloudSyncTransportInit): SyncTransport {\n const { backend, handle } = init;\n const hasVolume = typeof backend.ensureVolume === 'function';\n let tarSeq = 0;\n\n const caps: TransportCaps = {\n persistentVolumes: hasVolume,\n helperContainer: false,\n ephemeralFs: !hasVolume,\n };\n\n const transport: SyncTransport = {\n caps,\n\n async exec(cmd: string[], opts?: SyncExecOptions): Promise<SyncExecResult> {\n const r = await backend.exec(handle, quoteShellArgv(cmd), {\n cwd: opts?.cwd,\n env: opts?.env,\n user: opts?.user,\n attemptTimeoutMs: opts?.attemptTimeoutMs,\n noRetry: opts?.noRetry,\n });\n return { exitCode: r.exitCode, stdout: r.stdout, stderr: r.stderr };\n },\n\n async applyTarball(hostTarPath: string, boxDestDir: string): Promise<void> {\n const remoteTar = `/tmp/agentbox-apply-${String(tarSeq++)}.tar`;\n await backend.uploadFile(handle, hostTarPath, remoteTar);\n const r = await backend.exec(\n handle,\n `tar -xf ${remoteTar} -C ${boxDestDir} --no-same-permissions --no-same-owner -m && rm -f ${remoteTar}`,\n );\n if (r.exitCode !== 0) {\n throw new Error(\n `cloud tar extract into ${boxDestDir} failed (exit ${String(r.exitCode)}): ${r.stderr.slice(-200)}`,\n );\n }\n },\n\n async pushTree(hostSrcDir: string, boxDestDir: string, opts?: PushOptions): Promise<void> {\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-pushtree-'));\n const localTar = join(stage, 'tree.tar');\n try {\n const packArgs = ['-C', hostSrcDir];\n for (const ex of opts?.exclude ?? []) packArgs.push(`--exclude=${ex}`);\n packArgs.push('-cf', localTar, '.');\n const packed = await execa('tar', packArgs, { reject: false });\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack of ${hostSrcDir} failed: ${String(packed.stderr).slice(0, 300)}`);\n }\n await transport.applyTarball(localTar, boxDestDir, opts);\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n },\n\n async pushFile(hostSrcPath: string, boxDestPath: string, opts?: PushOptions): Promise<void> {\n await backend.uploadFile(handle, hostSrcPath, boxDestPath);\n if (opts?.uid !== undefined && opts.uid !== 0) {\n await backend.exec(handle, `chown ${String(opts.uid)}:${String(opts.uid)} ${boxDestPath}`);\n }\n if (opts?.mode !== undefined) {\n await backend.exec(handle, `chmod ${opts.mode.toString(8)} ${boxDestPath}`);\n }\n },\n\n async pullTree(boxSrcDir: string, hostDestDir: string, opts?: { exclude?: string[] }): Promise<void> {\n const remoteTar = `/tmp/agentbox-pull-${String(tarSeq++)}.tar`;\n const excludes = (opts?.exclude ?? []).map((e) => `--exclude=${e}`).join(' ');\n const pack = await backend.exec(\n handle,\n `tar -C ${boxSrcDir} ${excludes} -cf ${remoteTar} .`,\n );\n if (pack.exitCode !== 0) {\n throw new Error(`cloud tar of ${boxSrcDir} failed: ${pack.stderr.slice(-200)}`);\n }\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-pulltree-'));\n const localTar = join(stage, 'tree.tar');\n try {\n await backend.downloadFile(handle, remoteTar, localTar);\n await execa('tar', ['-xf', localTar, '-C', hostDestDir], { reject: false });\n } finally {\n await rm(stage, { recursive: true, force: true });\n await backend.exec(handle, `rm -f ${remoteTar}`).catch(() => {});\n }\n },\n\n async pullFile(boxSrcPath: string, hostDestPath: string): Promise<void> {\n await backend.downloadFile(handle, boxSrcPath, hostDestPath);\n },\n\n async readText(boxPath: string): Promise<string | null> {\n const r = await backend.exec(handle, `cat ${boxPath} 2>/dev/null`, { noRetry: true });\n if (r.exitCode !== 0) return null;\n return r.stdout;\n },\n };\n\n if (hasVolume) {\n transport.ensureVolume = async (name: string): Promise<{ volumeId: string }> => {\n const ensured = await backend.ensureVolume!(name);\n return ensured;\n };\n }\n // seedVolumeFromHost intentionally omitted: cloud static config is baked into\n // the snapshot at `prepare` time (caps.helperContainer === false).\n\n return transport;\n}\n","/**\n * Per-box, incremental seed of Claude Code's dynamic config (global\n * `~/.claude/workflows/` + the project's `memory/`) into a cloud sandbox.\n *\n * The static config (plugins/skills/settings) is baked into the prepare-time\n * snapshot; workflows + memory change between runs, so we ship them on every\n * create — like credentials, but diffed per-file so re-creates carry only what\n * changed. The box records what it holds in a manifest at\n * {@link BOX_DYNAMIC_SYNC_MANIFEST}; because that file lives on the box\n * filesystem it rides along in every checkpoint, so a checkpoint boot only\n * syncs files changed on the host since the snapshot.\n *\n * Transport is the credential pattern — `backend.uploadFile` + `backend.exec`\n * (tar over the SDK / scp), no rsync — so it works on daytona, hetzner, and\n * vercel alike. `backend.exec` runs as `vscode` on all three, so extraction\n * into the vscode-owned home needs no chown.\n */\n\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport {\n BOX_DYNAMIC_SYNC_MANIFEST,\n BOX_MEMORY_DIR,\n BOX_WORKFLOWS_DIR,\n buildHostSyncManifest,\n computeSyncDelta,\n stageDynamicSyncTarball,\n type DynamicSyncManifest,\n} from '@agentbox/sandbox-core';\nimport type { CloudBackend, CloudHandle } from '@agentbox/core';\n\nexport interface SeedDynamicConfigOptions {\n /** Host-absolute workspace path (locates the project's memory dir). */\n workspacePath: string;\n onLog?: (line: string) => void;\n}\n\n/** Single-quote a path for safe interpolation into the extract shell command. */\nfunction sq(p: string): string {\n return `'${p.replace(/'/g, `'\\\\''`)}'`;\n}\n\nconst REMOTE_TAR = '/tmp/agentbox-dynsync.tar.gz';\nconst BOX_STAGE = '/tmp/agentbox-dynsync-stage';\n\n/**\n * Diff the host's workflows + memory against the box's manifest and upload only\n * the delta. Best-effort: never throws into box creation. Runs on both fresh\n * and checkpoint boots — the manifest diff makes it a no-op when nothing\n * changed.\n */\nexport async function seedDynamicConfig(\n backend: CloudBackend,\n handle: CloudHandle,\n opts: SeedDynamicConfigOptions,\n): Promise<void> {\n const log = opts.onLog ?? (() => {});\n\n try {\n // 1. Read the manifest the box already carries (absent on a fresh box).\n let boxManifest: DynamicSyncManifest | null = null;\n try {\n const res = await backend.exec(handle, `cat ${BOX_DYNAMIC_SYNC_MANIFEST} 2>/dev/null || true`);\n const out = res.stdout.trim();\n if (res.exitCode === 0 && out.length > 0) {\n boxManifest = JSON.parse(out) as DynamicSyncManifest;\n }\n } catch {\n boxManifest = null; // treat unreadable/corrupt manifest as fresh\n }\n\n // 2. Hash the host sets, 3. diff.\n const host = await buildHostSyncManifest(opts.workspacePath);\n const delta = computeSyncDelta(host, boxManifest);\n if (delta.uploads.length === 0 && delta.deletions.length === 0) {\n log('claude workflows + memory already up to date in box');\n return;\n }\n delta.nextManifest.syncedAt = new Date().toISOString();\n\n // 4. Stage the changed files + the manifest.\n const staged = await stageDynamicSyncTarball(delta.uploads);\n const manifestDir = await mkdtemp(join(tmpdir(), 'agentbox-dynsync-manifest-'));\n const manifestTmp = join(manifestDir, 'dynamic-sync.json');\n await writeFile(manifestTmp, JSON.stringify(delta.nextManifest, null, 2));\n\n try {\n const steps: string[] = [\n 'set -e',\n `mkdir -p /home/vscode/.agentbox ${BOX_WORKFLOWS_DIR} ${BOX_MEMORY_DIR}`,\n ];\n if (staged.tarballPath) {\n await backend.uploadFile(handle, staged.tarballPath, REMOTE_TAR);\n steps.push(\n `rm -rf ${BOX_STAGE}`,\n `mkdir -p ${BOX_STAGE}`,\n `tar -xzf ${REMOTE_TAR} -C ${BOX_STAGE}`,\n `if [ -d ${BOX_STAGE}/workflows ]; then cp -a ${BOX_STAGE}/workflows/. ${BOX_WORKFLOWS_DIR}/; fi`,\n `if [ -d ${BOX_STAGE}/memory ]; then cp -a ${BOX_STAGE}/memory/. ${BOX_MEMORY_DIR}/; fi`,\n `rm -rf ${BOX_STAGE} ${REMOTE_TAR}`,\n );\n }\n for (const d of delta.deletions) {\n steps.push(`rm -f ${sq(d.dst)}`);\n }\n const res = await backend.exec(handle, steps.join('; '));\n if (res.exitCode !== 0) {\n log(\n `dynamic config seed failed (exit ${String(res.exitCode)}): ` +\n `${res.stderr.slice(-200)}`,\n );\n return;\n }\n\n // 5. Record the new manifest last — a failed extract must not record\n // state the box never reached.\n await backend.uploadFile(handle, manifestTmp, BOX_DYNAMIC_SYNC_MANIFEST);\n log(\n `seeded claude workflows + memory: ${String(delta.uploads.length)} file(s) updated, ` +\n `${String(delta.deletions.length)} removed`,\n );\n } finally {\n await staged.cleanup();\n await rm(dirname(manifestTmp), { recursive: true, force: true });\n }\n } catch (err) {\n log(\n `claude workflows + memory seed skipped (non-fatal): ` +\n `${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n","import type { CloudBackend, CloudHandle } from '@agentbox/core';\nimport {\n buildCodexAgentsOverrideScript,\n CODEX_OVERRIDE_WROTE_MARKER,\n} from '@agentbox/sandbox-docker';\n\n/** CODEX_HOME is `/home/vscode/.codex` on every provider (the box user is `vscode`). */\nconst BOX_CODEX_HOME = '/home/vscode/.codex';\n\n/**\n * Cloud counterpart of the docker `seedCodexAgentsOverride`: regenerate\n * `~/.codex/AGENTS.override.md` in-box so the Codex agent reads the box \"system\n * prompt\" (`/etc/claude-code/CLAUDE.md`, installed on every provider). Runs the\n * SAME shared script as docker, in-box via `backend.exec`. The exec user varies\n * (vscode on vercel/e2b, root-then-sudo on hetzner), so target the fixed\n * `/home/vscode/.codex` path and normalize ownership to vscode afterwards rather\n * than relying on `$HOME`. Best-effort: a failure must never fail box creation.\n *\n * Call after the codex config/home is in place (post `ensureAgentHomeDirsOwned`)\n * so a synced user `AGENTS.md` is folded in beneath the facts.\n */\nexport async function ensureCodexAgentsOverride(\n backend: CloudBackend,\n handle: CloudHandle,\n opts: { onLog?: (line: string) => void } = {},\n): Promise<void> {\n const log = opts.onLog ?? (() => {});\n const script =\n buildCodexAgentsOverrideScript(BOX_CODEX_HOME) +\n `\\nchown vscode:vscode \"$OVR\" 2>/dev/null || true` +\n `\\nchmod 0644 \"$OVR\" 2>/dev/null || true`;\n try {\n // Cloud backends signal script failure via a non-zero exitCode rather than\n // throwing, so a `set -e` abort (perms, missing paths) must be read off the\n // result — otherwise we'd log success while the box booted without facts.\n // The script also exits 0 in the no-op case (box-facts file absent) without\n // writing, so gate the \"seeded\" log on the wrote-marker, not just exit 0.\n const res = await backend.exec(handle, script);\n if (res.exitCode !== 0)\n log(\n `codex AGENTS.override seed failed (continuing): exit ${res.exitCode}${\n res.stderr.trim() ? `: ${res.stderr.trim()}` : ''\n }`,\n );\n else if (res.stdout.includes(CODEX_OVERRIDE_WROTE_MARKER))\n log('seeded Codex AGENTS.override.md');\n else log('codex AGENTS.override skipped: box-facts file absent');\n } catch (err) {\n log(\n `codex AGENTS.override seed failed (continuing): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n","/**\n * Per-create overlay of the in-box `~/.claude/_claude.json` from the host's\n * current `~/.claude.json` state.\n *\n * Runs on every cloud create across e2b/vercel/hetzner/daytona. The other\n * cloud providers also bake a `_claude.json` into their snapshot at prepare\n * time, but that baked file becomes stale if the host completes Claude's\n * onboarding (or changes theme) after `agentbox prepare`. E2B doesn't bake\n * `_claude.json` at all — only the symlink `~/.claude.json` ->\n * `~/.claude/_claude.json` — so without this overlay a fresh E2B box has no\n * `_claude.json` and Claude shows the theme picker on first run.\n *\n * The payload is one tiny JSON file; transport is `backend.uploadFile` +\n * `backend.exec`, the same primitive used for credentials/dynamic-sync. The\n * extract runs as `vscode`, so no chown is needed.\n *\n * Best-effort: a failure logs and never sinks `agentbox create`. The in-box\n * Claude will fall back to its baked / first-run behavior.\n */\n\nimport { stageClaudeJsonOnlyForUpload } from '@agentbox/sandbox-core';\nimport type { CloudBackend, CloudHandle } from '@agentbox/core';\n\nexport interface SeedClaudeJsonOptions {\n /** Host-absolute workspace path being mounted at `/workspace` in the box. */\n hostWorkspace?: string;\n onLog?: (line: string) => void;\n}\n\nconst REMOTE_TAR = '/tmp/agentbox-claude-json.tar.gz';\nconst BOX_CLAUDE_DIR = '/home/vscode/.claude';\n\n/**\n * Stage `_claude.json` from the host, upload it to the box, and extract into\n * `~/.claude/`. Overwrites any baked `_claude.json` — this is intentional, the\n * baked one is a prepare-time snapshot and we want the latest host state.\n */\nexport async function seedClaudeJsonAtCreate(\n backend: CloudBackend,\n handle: CloudHandle,\n opts: SeedClaudeJsonOptions = {},\n): Promise<void> {\n const log = opts.onLog ?? (() => {});\n let staged: Awaited<ReturnType<typeof stageClaudeJsonOnlyForUpload>> | null = null;\n try {\n staged = await stageClaudeJsonOnlyForUpload({ hostWorkspace: opts.hostWorkspace });\n if (staged.tarballPath === null) {\n log('claude: no _claude.json overlay (host has no claude config)');\n return;\n }\n await backend.uploadFile(handle, staged.tarballPath, REMOTE_TAR);\n const extract = await backend.exec(\n handle,\n `set -e; mkdir -p ${BOX_CLAUDE_DIR}; ` +\n `tar -xzf ${REMOTE_TAR} -C ${BOX_CLAUDE_DIR}; ` +\n `rm -f ${REMOTE_TAR}`,\n );\n if (extract.exitCode !== 0) {\n log(\n `claude: _claude.json overlay extract failed (exit ${String(extract.exitCode)}); ` +\n `stderr: ${extract.stderr.slice(-200)}`,\n );\n return;\n }\n log('claude: _claude.json overlay seeded');\n } catch (err) {\n log(\n `claude: _claude.json overlay failed (continuing): ${err instanceof Error ? err.message : String(err)}`,\n );\n } finally {\n if (staged) await staged.cleanup();\n }\n}\n","import { execa } from 'execa';\nimport type { CloudBackend, CloudHandle } from '@agentbox/core';\nimport { bashScript, quoteShellArg } from '../shell.js';\n\nexport interface SeedGitIdentityOptions {\n /** Host repo dir to read the effective `user.name`/`user.email` from. */\n hostRepo?: string;\n onLog?: (line: string) => void;\n}\n\n/** Generic fallback so a box always has a usable committer identity. */\nconst FALLBACK_NAME = 'agentbox';\nconst FALLBACK_EMAIL = 'agentbox@users.noreply.github.com';\n\n/**\n * Configure a git committer identity inside a cloud box.\n *\n * Docker boxes bind-mount the host `~/.gitconfig`, so they inherit the user's\n * identity for free. Cloud boxes (vercel/hetzner/daytona) can't bind-mount and\n * otherwise have *no* identity — which breaks any in-box commit: the agent's\n * own `git commit`, and the merge commit `agentbox git pull` writes. We mirror\n * the Docker behavior here: author as the host user when their identity is\n * resolvable, and fall back to a generic agentbox identity so commits never\n * fail with \"Committer identity unknown\".\n *\n * Reads the *effective* identity from the host repo (`git -C <repo> config\n * user.name`), so a repo-local override is honored just like a normal local\n * commit would. Sets `--global` for the box's agent user (cloud `exec` runs as\n * that user), which is where the in-box merge / agent commits look it up.\n *\n * Note: the git-lfs `filter.lfs.*` config is intentionally NOT seeded here — it\n * is registered system-wide in each base image (`git lfs install --system`, see\n * the provider install scripts / Dockerfile.box), so an LFS checkout smudges\n * without any per-box config. The objects themselves are seeded host-side by\n * `seedCloneLfsObjects` in workspace-seed.ts.\n */\nexport async function seedGitIdentity(\n backend: CloudBackend,\n handle: CloudHandle,\n opts: SeedGitIdentityOptions = {},\n): Promise<void> {\n const log = opts.onLog ?? (() => {});\n const name = (await readHostGitConfig('user.name', opts.hostRepo)) ?? FALLBACK_NAME;\n const email = (await readHostGitConfig('user.email', opts.hostRepo)) ?? FALLBACK_EMAIL;\n\n const script =\n `git config --global user.name ${quoteShellArg(name)} && ` +\n `git config --global user.email ${quoteShellArg(email)}`;\n const r = await backend.exec(handle, bashScript(script));\n if (r.exitCode !== 0) {\n // Non-fatal: the box still boots; the user just sees the identity error on\n // the next commit, same as before this step existed.\n log(`git: identity config failed (exit ${String(r.exitCode)}): ${(r.stderr || r.stdout).trim()}`);\n return;\n }\n log(`git: configured committer identity ${name} <${email}>`);\n}\n\n/** Read a host git config value (effective: system + global + repo-local). */\nasync function readHostGitConfig(key: string, hostRepo?: string): Promise<string | null> {\n const args = hostRepo ? ['-C', hostRepo, 'config', key] : ['config', key];\n const r = await execa('git', args, { reject: false });\n if (r.exitCode !== 0) return null;\n const value = (r.stdout ?? '').trim();\n return value.length > 0 ? value : null;\n}\n","/**\n * Copy host env/config files (`.env`, `secrets.toml`, `agentbox.yaml`, …) into\n * a cloud sandbox's `/workspace` at create time. Thin wrapper over the shared\n * env concern (`@agentbox/sandbox-core`'s sync/concerns/env): same host-side\n * `find` + `tar --null -T -` pack, with the cloud transport's `applyTarball`\n * (`uploadFile` + `backend.exec(tar -xf … --no-same-* -m)`) doing the extract.\n *\n * The wizard collects `envFilesToImport` (apps/cli/src/wizard.ts); this makes\n * the cloud provider honour it, exactly like the docker provider.\n */\n\nimport { makeSyncContext, pushEnvFiles } from '@agentbox/sandbox-core';\nimport type { CloudBackend, CloudHandle } from '@agentbox/core';\nimport { createCloudSyncTransport } from './sync-transport.js';\n\nexport interface UploadEnvFilesArgs {\n backend: CloudBackend;\n handle: CloudHandle;\n /** Absolute host workspace path the find runs against. */\n workspacePath: string;\n /** Glob patterns selected by the wizard (e.g. `.env`, `secrets.toml`). */\n files: string[];\n /** In-sandbox `/workspace` mount. Always `/workspace` today; configurable for tests. */\n workspaceDir?: string;\n onLog?: (line: string) => void;\n}\n\nexport interface UploadEnvFilesResult {\n /** Number of files written into the sandbox. 0 when nothing matched. */\n copied: number;\n}\n\nexport async function uploadEnvFiles(args: UploadEnvFilesArgs): Promise<UploadEnvFilesResult> {\n if (args.files.length === 0) return { copied: 0 };\n const ctx = makeSyncContext({\n boxName: '',\n boxId: '',\n provider: 'cloud',\n hostWorkspace: args.workspacePath,\n boxWorkspace: args.workspaceDir ?? '/workspace',\n onLog: args.onLog,\n });\n const transport = createCloudSyncTransport({ backend: args.backend, handle: args.handle });\n return pushEnvFiles(ctx, transport, args.files);\n}\n","/**\n * Apply the `carry:` block from `agentbox.yaml` against a cloud sandbox.\n *\n * Mirror of `copyCarryPathsToBox` in `@agentbox/sandbox-docker`: per-entry tar\n * upload + extract, with destinations that may live anywhere in the box\n * (not constrained to /workspace). Runs after `uploadEnvFiles` and before the\n * supervisor launches, so the first declared task sees the carry files\n * already in place.\n *\n * Best-effort per-entry: a single failed entry is recorded in `errors` and\n * the function returns — the box stays usable; the caller logs the misses.\n */\n\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type { CloudBackend, CloudHandle, ResolvedCarryEntry } from '@agentbox/core';\nimport { BOX_HOME, dirnameUnix, planCarryEntry } from '@agentbox/sandbox-core';\n\nexport interface UploadCarryArgs {\n backend: CloudBackend;\n handle: CloudHandle;\n entries: ResolvedCarryEntry[];\n onLog?: (line: string) => void;\n}\n\nexport interface UploadCarryResult {\n copied: number;\n errors: string[];\n /** Audit summary for BoxRecord.carry. */\n applied: Array<{ src: string; dest: string; bytes: number }>;\n}\n\nexport async function uploadCarryPaths(args: UploadCarryArgs): Promise<UploadCarryResult> {\n const log = args.onLog ?? (() => {});\n if (args.entries.length === 0) {\n return { copied: 0, errors: [], applied: [] };\n }\n\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-carry-'));\n const errors: string[] = [];\n const applied: UploadCarryResult['applied'] = [];\n let copied = 0;\n\n try {\n for (const [i, entry] of args.entries.entries()) {\n const where = `carry[${String(i)}] \"${entry.rawSrc}\"`;\n if (entry.kind === 'missing') {\n log(`${where}: skipped (missing on host, optional)`);\n continue;\n }\n try {\n await uploadOneEntry({\n backend: args.backend,\n handle: args.handle,\n entry,\n stageDir: stage,\n index: i,\n });\n copied += 1;\n applied.push({ src: entry.absSrc, dest: entry.absDest, bytes: entry.bytes ?? 0 });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n errors.push(`${where}: ${msg}`);\n log(`${where}: failed: ${msg}`);\n }\n }\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n\n return { copied, errors, applied };\n}\n\ninterface UploadOneArgs {\n backend: CloudBackend;\n handle: CloudHandle;\n entry: ResolvedCarryEntry;\n stageDir: string;\n index: number;\n}\n\nasync function uploadOneEntry(args: UploadOneArgs): Promise<void> {\n const { entry } = args;\n // Shared, byte-for-byte carry decisions (~/ expansion, file-vs-dir, exclude,\n // uid/mode defaults, rename-needed, parent-chain-needed) — see\n // `@agentbox/sandbox-core`'s files concern. `~/` is expanded host-side, never\n // inside the box: the supervisor user's $HOME equals BOX_HOME, but the exec\n // shell's current user (the SDK's default) is not guaranteed to be vscode on\n // every backend, so an explicit destination path is required.\n const plan = planCarryEntry(entry);\n if (!plan) return; // missing (optional + absent on host)\n const { boxDest, isDir, parentDir, exclude, uid, mode, fileBase, renameNeeded } = plan;\n\n // 1. Tar the host source on disk so backend.uploadFile (which takes a path,\n // not a stream) has something to send.\n const localTar = join(args.stageDir, `carry-${String(args.index)}.tar`);\n const excludeArgs = isDir ? exclude.map((p) => `--exclude=${p}`) : [];\n const tarArgs = isDir\n ? ['-C', entry.absSrc, '-cf', localTar, ...excludeArgs, '.']\n : ['-C', dirnameUnix(entry.absSrc), '-cf', localTar, fileBase];\n const packed = await execa('tar', tarArgs, { reject: false });\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack failed: ${String(packed.stderr).slice(0, 300)}`);\n }\n\n // 2. Upload the tar into the sandbox under a temp path.\n const remoteTar = `/tmp/agentbox-carry-${String(args.index)}.tar`;\n await args.backend.uploadFile(args.handle, localTar, remoteTar);\n\n // 3. mkdir + extract + optional chmod + optional chown + cleanup, in one\n // bash command. Single-quoted args inside double-quoted command string —\n // paths are safe because carry: dest values are user-provided absolute\n // paths the resolver already vetted.\n //\n // For files: tar's input contains a single entry at basename(absSrc), and we\n // extract at the dest's parent, then `mv` to the dest when the source\n // basename differs from the dest basename.\n const parts: string[] = [\n `mkdir -p ${shellQuote(parentDir)}`,\n isDir\n ? `tar -xf ${remoteTar} -C ${shellQuote(boxDest)} --no-same-permissions --no-same-owner -m`\n : `tar -xf ${remoteTar} -C ${shellQuote(parentDir)} --no-same-permissions --no-same-owner -m`,\n ];\n if (renameNeeded) {\n parts.push(\n `mv ${shellQuote(`${parentDir}/${fileBase}`)} ${shellQuote(boxDest)}`,\n );\n }\n if (mode) parts.push(`chmod -R ${mode} ${shellQuote(boxDest)}`);\n parts.push(`chown -R ${String(uid)}:${String(uid)} ${shellQuote(boxDest)}`);\n // Parent-chain chown: `mkdir -p` ran as root, so any new dirs between\n // $HOME and dirname(boxDest) are root-owned. Walk back up to $HOME\n // (exclusive) and chown each. Only when dest is under $HOME — system\n // paths like /etc/* keep their existing ownership.\n if (plan.parentChainNeeded) {\n parts.push(\n `parent=$(dirname ${shellQuote(boxDest)}); ` +\n `while [ \"$parent\" != \"${BOX_HOME}\" ] && [ \"$parent\" != \"/\" ]; do ` +\n `chown ${String(uid)}:${String(uid)} \"$parent\"; ` +\n `parent=$(dirname \"$parent\"); ` +\n `done`,\n );\n }\n parts.push(`rm -f ${remoteTar}`);\n const cmd = parts.join(' && ');\n\n // Vercel-only: force the extract to run as root. Vercel's exec wraps a\n // non-root command in `sudo -u vscode -H bash -lc '<cmd>'`, and that extra\n // `bash -lc` nesting mangles this command's `$(...)`/`$var`/`while` (the\n // parent var expands empty → `dirname \".\"` loops forever → the exec hangs\n // until timeout, surfacing as \"Stream ended before command finished\"). Its\n // single-`bash -lc` root path doesn't re-parse, so the command runs cleanly.\n // The command still chowns the dest to the target uid (default vscode 1000),\n // so files end up vscode-owned and writable regardless of who runs it.\n //\n // Scoped explicitly to Vercel rather than relying on other backends ignoring\n // `user:` — Hetzner/Daytona keep their existing (working) carry path\n // unchanged even if they start honoring `user` later.\n // E2B joins the vercel carve-out: its default exec runs as `vscode` (uid\n // 1000), which cannot `chown` files to other uids. The carry chain ends with\n // a `chown -R 1000:1000`, so as vscode it errors with \"Operation not\n // permitted\" and the parent-chain loop never reaches its terminator. Forcing\n // root makes the chown a no-op (target uid matches existing owner) and lets\n // the parent-chain walk complete.\n const wantsRoot = args.backend.name === 'vercel' || args.backend.name === 'e2b';\n const execOpts = wantsRoot ? { user: 'root' as const } : undefined;\n const res = await args.backend.exec(args.handle, cmd, execOpts);\n if (res.exitCode !== 0) {\n throw new Error(\n `in-box extract failed (exit ${String(res.exitCode)}): ${(res.stderr || res.stdout).slice(-300)}`,\n );\n }\n}\n\n/** Single-quote a shell argument; safe for any byte except NUL. */\nfunction shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n","/**\n * Cloud checkpoint store — parallel to `packages/sandbox-docker/src/checkpoint.ts`\n * but backed by provider-native snapshots (Daytona's `_experimental_createSnapshot`)\n * instead of local Docker image tags.\n *\n * Each user-facing checkpoint (`setup`, `with-deps`, …) is scoped to a project\n * and stored as a thin manifest on the host:\n *\n * ~/.agentbox/cloud-checkpoints/<backend>/<projectHash-mnemonic>/<name>/manifest.json\n *\n * The manifest maps the project-scoped name to a provider-unique snapshot name\n * — Daytona snapshots are org-wide, so the snapshot name is prefixed with the\n * project hash to avoid collisions across projects (and across users in the\n * same org).\n */\n\nimport { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, join } from 'node:path';\nimport type { CloudBackend } from '@agentbox/core';\nimport { hashProjectPath, projectDirSegment, sanitizeMnemonic } from '@agentbox/config';\nimport { type PreparedProviderKind, readPreparedStateRaw } from '@agentbox/sandbox-core';\n\nexport const CLOUD_CHECKPOINTS_ROOT = join(homedir(), '.agentbox', 'cloud-checkpoints');\n\n/**\n * All cloud snapshot names share this prefix so a stray `agentbox-ckpt-*`\n * snapshot in the Daytona dashboard is clearly recognisable as AgentBox's.\n * Mirrors `CHECKPOINT_IMAGE_PREFIX` from the docker package.\n */\nexport const CLOUD_SNAPSHOT_NAME_PREFIX = 'agentbox-ckpt-';\n\nexport interface CloudCheckpointManifest {\n /**\n * Schema history:\n * 1 — original fields (no base fingerprint; staleness unverifiable)\n * 2 — adds `baseProvider`, `baseFingerprint`, `cliVersion` so the wizard\n * can tell a checkpoint captured against a now-rebuilt base snapshot\n * from a fresh one. A legacy schema-1 manifest has no fingerprint and\n * is treated as \"stale / unverifiable\" by `evaluateCheckpoint`.\n */\n schema: 1 | 2;\n /** User-facing, project-scoped name (e.g. \"setup\"). */\n name: string;\n /** Cloud backend the snapshot lives in (e.g. \"daytona\"). */\n backend: string;\n /**\n * Provider-unique snapshot name — what the backend's `createSnapshot()` was\n * called with, and what gets passed to `provision({ snapshot })` on restore.\n */\n snapshotName: string;\n sourceBoxId: string;\n sourceBoxName: string;\n /**\n * Cloud provider whose base-snapshot fingerprint this checkpoint was\n * captured against. Schema-2+ only.\n */\n baseProvider?: string;\n /**\n * Build-context fingerprint of the base snapshot at capture time (the\n * provider's `prepared-state` `contextSha256`). Schema-2+ only; missing →\n * legacy schema-1 → \"unverifiable / stale\".\n */\n baseFingerprint?: string;\n /** CLI version that captured the checkpoint. Schema-2+ only. */\n cliVersion?: string;\n createdAt: string;\n}\n\nexport interface CloudCheckpointInfo {\n name: string;\n /** Host dir holding `manifest.json`. */\n dir: string;\n manifest: CloudCheckpointManifest;\n}\n\n/**\n * Deterministic provider-unique snapshot name for a project checkpoint. The\n * project-hash prefix prevents collisions across projects (and across users\n * in the same Daytona org); the mnemonic suffix keeps the Daytona dashboard\n * readable. The leading `agentbox-ckpt-` lets cleanup scripts recognise our\n * snapshots.\n */\nexport function cloudSnapshotName(projectRoot: string, name: string): string {\n const mnemonic = sanitizeMnemonic(basename(projectRoot));\n return `${CLOUD_SNAPSHOT_NAME_PREFIX}${hashProjectPath(projectRoot)}_${mnemonic}-${name}`;\n}\n\nfunction backendDir(backend: string, projectRoot: string): string {\n return join(CLOUD_CHECKPOINTS_ROOT, backend, projectDirSegment(projectRoot));\n}\n\n/**\n * Backend names that have a checkpoint directory under `CLOUD_CHECKPOINTS_ROOT`.\n * Lets the CLI's `checkpoint list` surface checkpoints from **plugin** cloud\n * providers (whose names aren't in the built-in `CLOUD_PROVIDER_NAMES`) without\n * loading them — a checkpoint store is just named directories on disk.\n */\nexport async function listCloudBackendDirs(): Promise<string[]> {\n try {\n return (await readdir(CLOUD_CHECKPOINTS_ROOT, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n return [];\n }\n}\n\nfunction checkpointDir(backend: string, projectRoot: string, name: string): string {\n return join(backendDir(backend, projectRoot), name);\n}\n\nasync function readManifest(dir: string): Promise<CloudCheckpointManifest | null> {\n try {\n const raw = await readFile(join(dir, 'manifest.json'), 'utf8');\n const m = JSON.parse(raw) as CloudCheckpointManifest;\n if (m.schema !== 1 && m.schema !== 2) return null;\n return m;\n } catch {\n return null;\n }\n}\n\n/**\n * Read every valid cloud checkpoint manifest directly under `root` (a backend's\n * `<hash>-<mnemonic>` project dir), sorted by `createdAt`. Shared by the scoped\n * and global listers. Missing root / unreadable manifests are skipped.\n */\nasync function listCloudCheckpointsInDir(root: string): Promise<CloudCheckpointInfo[]> {\n let entries: string[];\n try {\n entries = (await readdir(root, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n return [];\n }\n const out: CloudCheckpointInfo[] = [];\n for (const name of entries) {\n const dir = join(root, name);\n const manifest = await readManifest(dir);\n if (manifest) out.push({ name, dir, manifest });\n }\n out.sort((a, b) => a.manifest.createdAt.localeCompare(b.manifest.createdAt));\n return out;\n}\n\nexport async function listCloudCheckpoints(\n projectRoot: string,\n backend: string,\n): Promise<CloudCheckpointInfo[]> {\n return listCloudCheckpointsInDir(backendDir(backend, projectRoot));\n}\n\nexport interface CloudCheckpointProjectGroup {\n /** `<hash>-<mnemonic>` dir name under CLOUD_CHECKPOINTS_ROOT/<backend>/. */\n segment: string;\n items: CloudCheckpointInfo[];\n}\n\n/**\n * Every project's cloud checkpoints for `backend`, one group per project dir.\n * Best-effort: a missing backend root returns `[]`, and segments with zero\n * valid manifests are dropped. Used by `checkpoints -g`.\n */\nexport async function listAllCloudCheckpoints(\n backend: string,\n): Promise<CloudCheckpointProjectGroup[]> {\n const backendRoot = join(CLOUD_CHECKPOINTS_ROOT, backend);\n let segments: string[];\n try {\n segments = (await readdir(backendRoot, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n return [];\n }\n const out: CloudCheckpointProjectGroup[] = [];\n for (const segment of segments) {\n const items = await listCloudCheckpointsInDir(join(backendRoot, segment));\n if (items.length > 0) out.push({ segment, items });\n }\n return out;\n}\n\nexport async function resolveCloudCheckpoint(\n projectRoot: string,\n backend: string,\n ref: string,\n): Promise<CloudCheckpointInfo | null> {\n const dir = checkpointDir(backend, projectRoot, ref);\n const manifest = await readManifest(dir);\n if (!manifest) return null;\n return { name: ref, dir, manifest };\n}\n\nexport interface WriteCloudManifestFields {\n snapshotName: string;\n sourceBoxId: string;\n sourceBoxName: string;\n baseProvider?: string;\n baseFingerprint?: string;\n cliVersion?: string;\n}\n\nexport async function writeCloudCheckpointManifest(\n projectRoot: string,\n backend: string,\n name: string,\n fields: WriteCloudManifestFields,\n): Promise<CloudCheckpointInfo> {\n const dir = checkpointDir(backend, projectRoot, name);\n await mkdir(dir, { recursive: true });\n const manifest: CloudCheckpointManifest = {\n schema: 2,\n name,\n backend,\n snapshotName: fields.snapshotName,\n sourceBoxId: fields.sourceBoxId,\n sourceBoxName: fields.sourceBoxName,\n baseProvider: fields.baseProvider,\n baseFingerprint: fields.baseFingerprint,\n cliVersion: fields.cliVersion,\n createdAt: new Date().toISOString(),\n };\n await writeFile(join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\\n', 'utf8');\n return { name, dir, manifest };\n}\n\n/**\n * Current base-snapshot build-context fingerprint for a cloud provider, read\n * from its `~/.agentbox/<provider>-prepared.json`. Returns `undefined` when no\n * prepared state exists or it predates fingerprinting — callers then can't\n * verify staleness and must not falsely flag a checkpoint as stale.\n */\nexport function currentCloudBaseFingerprint(provider: string): string | undefined {\n try {\n const raw = readPreparedStateRaw(provider as PreparedProviderKind) as {\n base?: { contextSha256?: string };\n } | null;\n return raw?.base?.contextSha256;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Freshness of a cloud provider's baked base image / snapshot, derived purely\n * from the `contextSha256` of the baked runtime files.\n *\n * **Checksum-only.** CLI version strings stored alongside the fingerprint are\n * informational and MUST NOT influence the decision: a CLI bump that doesn't\n * change any baked file produces an identical hash → `fresh`.\n */\nexport type BaseStatus =\n /** No prepared base on disk. */\n | { state: 'unprepared' }\n /**\n * Can't compute the live fingerprint (e.g. a dev tree with no built ctl\n * bundle). Inert: callers must not prompt for a rebuild they can't verify.\n */\n | { state: 'unknown' }\n /** Stored fingerprint differs from current — the baked runtime is out of date. */\n | { state: 'stale'; reason: string }\n /** Stored fingerprint matches current. */\n | { state: 'fresh' };\n\n/**\n * Provider-agnostic compare that turns a stored + live build-context\n * fingerprint into a {@link BaseStatus}. Shared by the CLI wizard/doctor\n * (`evaluateBaseFreshness`) and the hub so the state model and the `stale`\n * reason string never drift between them. `stored`/`live` are resolved by the\n * caller (`currentCloudBaseFingerprint` + the provider's\n * `currentBaseFingerprintLive`); docker has no baked base and should not reach\n * here.\n */\nexport function baseFreshnessFromFingerprints(\n stored: string | undefined,\n live: string | undefined,\n): BaseStatus {\n if (!stored) return { state: 'unprepared' };\n if (!live) return { state: 'unknown' };\n if (stored !== live) {\n return {\n state: 'stale',\n reason: `baked runtime differs (base ${stored.slice(0, 12)}, current ${live.slice(0, 12)})`,\n };\n }\n return { state: 'fresh' };\n}\n\nexport async function removeCloudCheckpointDir(\n projectRoot: string,\n backend: string,\n name: string,\n): Promise<boolean> {\n const dir = checkpointDir(backend, projectRoot, name);\n const existed = (await readManifest(dir)) !== null;\n if (!existed) return false;\n await rm(dir, { recursive: true, force: true });\n return true;\n}\n\n/**\n * Probe whether a cloud checkpoint's underlying provider snapshot is still\n * bootable, pruning the dangling local manifest when it has expired or been\n * deleted out-of-band. Lets the create / wizard paths recover gracefully —\n * fall back to a from-scratch box and re-ask the setup wizard — instead of\n * letting `provision()` 410 on a snapshot that no longer exists.\n *\n * Returns `{ live: false }` when there is no manifest for `ref`. When the\n * backend can't probe (`snapshotExists` unimplemented) the snapshot is assumed\n * live: we never prune on uncertainty.\n */\nexport async function probeCloudCheckpoint(\n backend: Pick<CloudBackend, 'name' | 'snapshotExists'>,\n projectRoot: string,\n ref: string,\n): Promise<{ live: boolean; pruned: boolean }> {\n const found = await resolveCloudCheckpoint(projectRoot, backend.name, ref);\n if (!found) return { live: false, pruned: false };\n if (!backend.snapshotExists) return { live: true, pruned: false };\n const live = await backend.snapshotExists(found.manifest.snapshotName);\n if (live) return { live: true, pruned: false };\n await removeCloudCheckpointDir(projectRoot, backend.name, ref);\n return { live: false, pruned: true };\n}\n","/**\n * Detect the \"the snapshot I tried to boot from is gone\" failure across cloud\n * backends. Vercel surfaces it as an `APIError` with HTTP 410 (\"Gone\") and a\n * body of `{ error: { message: 'Snapshot expired or deleted.' } }`; other\n * backends phrase it differently. We match on the status code and a few\n * message shapes so the create path can fall back to a from-scratch box\n * instead of crashing when a base/checkpoint snapshot has been reaped.\n */\nexport function isSnapshotGoneError(err: unknown): boolean {\n if (err === null || typeof err !== 'object') return false;\n const e = err as {\n status?: unknown;\n response?: { status?: unknown };\n json?: { error?: { message?: unknown } };\n message?: unknown;\n };\n const status = e.response?.status ?? e.status;\n if (status === 410) return true;\n const parts = [\n typeof e.json?.error?.message === 'string' ? e.json.error.message : '',\n typeof e.message === 'string' ? e.message : '',\n ];\n const msg = parts.join(' ').toLowerCase();\n return (\n /snapshot[^.]*\\b(expired|deleted|gone|not[ -]?found)\\b/.test(msg) ||\n msg.includes('expired or deleted')\n );\n}\n","/**\n * Extract the internal `expose.port` values from a workspace's\n * `agentbox.yaml`. The cloud provider mints a preview URL per port so\n * users can hit services directly (the WebProxy on port 8080 also\n * stays — this is a side channel for raw access).\n *\n * Intentionally minimal: we don't validate the rest of the schema. The\n * supervisor enforces correctness at run-time; here we just need the\n * numeric `services.*.expose.port` values. Errors (missing file, bad\n * YAML, unexpected shape) silently degrade to \"no extra ports\", which\n * matches the existing \"URL is best-effort at create\" semantics.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { parse as parseYaml } from 'yaml';\n\nexport async function readExposedServicePorts(workspacePath: string): Promise<number[]> {\n let text: string;\n try {\n text = await readFile(join(workspacePath, 'agentbox.yaml'), 'utf8');\n } catch {\n return [];\n }\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch {\n return [];\n }\n if (!isPlainObject(doc)) return [];\n const services = doc['services'];\n if (!isPlainObject(services)) return [];\n const out = new Set<number>();\n for (const value of Object.values(services)) {\n if (!isPlainObject(value)) continue;\n const expose = value['expose'];\n if (!isPlainObject(expose)) continue;\n const port = expose['port'];\n if (typeof port === 'number' && Number.isInteger(port) && port > 0 && port < 65_536) {\n out.add(port);\n }\n }\n return [...out].sort((a, b) => a - b);\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n","/**\n * `cp`-style file transfer for cloud boxes — symmetric host↔box uploads and\n * downloads that mirror `docker cp` semantics. The Docker provider tar-pipes\n * over `docker exec`; clouds with no exec stream can't, so we stage to a\n * single tar file in `/tmp`, transfer it via `backend.uploadFile` /\n * `downloadFile`, and unpack on the other side. Handles files and\n * directories uniformly.\n *\n * Path semantics match `docker cp`'s pragmatic subset: trailing `/` on the\n * destination means \"treat as a directory, land the source under it\"; no\n * trailing `/` means \"destination is the full target path\" (rename during\n * extraction). The in-box `test -d` probe the Docker provider uses to detect\n * existing directories isn't replicated here — it'd cost an extra exec\n * round-trip per call and the trailing-`/` convention is the explicit form\n * anyway.\n */\n\nimport { execa } from 'execa';\nimport { existsSync, mkdirSync, renameSync, statSync } from 'node:fs';\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport {\n basename as hostBasename,\n dirname as hostDirname,\n join as hostJoin,\n resolve as hostResolve,\n} from 'node:path';\nimport { posix } from 'node:path';\nimport type { CloudBackend, CloudHandle } from '@agentbox/core';\nimport { bashScript, quoteShellArg } from './shell.js';\n\nconst REMOTE_UP_TAR = '/tmp/agentbox-cp-up.tar.gz';\nconst REMOTE_DOWN_TAR = '/tmp/agentbox-cp-down.tar.gz';\n\n/** In-box home for the agent user; cloud boxes always run as `vscode`. */\nconst BOX_HOME = '/home/vscode';\n\nexport interface CloudCpResult {\n /** Final landed path on the receiving side. */\n finalPath: string;\n}\n\nasync function uploadOneToCloudBox(\n backend: CloudBackend,\n handle: CloudHandle,\n hostSrc: string,\n boxDst: string,\n exclude?: string[],\n): Promise<CloudCpResult> {\n const srcAbs = hostResolve(hostSrc);\n if (!existsSync(srcAbs)) throw new Error(`source not found: ${hostSrc}`);\n const srcBasename = hostBasename(srcAbs);\n const srcParent = hostDirname(srcAbs);\n\n // Resolve `boxParent` + final filename per docker cp rules — see file\n // header. We can't probe `test -d` cheaply, so the user opts into the\n // dir-vs-file ambiguity with the trailing slash.\n let boxParent: string;\n let finalName: string;\n if (boxDst.endsWith('/')) {\n boxParent = boxDst.replace(/\\/+$/, '') || '/';\n finalName = srcBasename;\n } else {\n boxParent = posix.dirname(boxDst);\n finalName = posix.basename(boxDst);\n }\n const finalPath = boxParent === '/' ? `/${finalName}` : `${boxParent}/${finalName}`;\n\n const stage = await mkdtemp(hostJoin(tmpdir(), 'agentbox-cp-up-'));\n const localTar = hostJoin(stage, 'payload.tar.gz');\n try {\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs\n // that would otherwise litter the box's filesystem on every upload.\n const excludeArgs = (exclude ?? []).map((p) => `--exclude=${p}`);\n await execa('tar', ['-C', srcParent, '-czf', localTar, ...excludeArgs, srcBasename], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n await backend.uploadFile(handle, localTar, REMOTE_UP_TAR);\n\n // Sudo for the dir ops because `boxParent` may be outside the user's\n // writable area (e.g. /etc/foo); devcontainers/base grants vscode\n // passwordless sudo and the SUDO=:'' fallback makes it a no-op when\n // sudo isn't available (test sandboxes).\n const initialPath = boxParent === '/' ? `/${srcBasename}` : `${boxParent}/${srcBasename}`;\n // Daytona's S3-backed FUSE volumes return ENOSYS for rename(2), so `mv`\n // fails when the destination crosses the mount boundary. `cp -f` + `rm`\n // works on every backend (and on the regular sandbox disk is no slower\n // than mv for a single file).\n const renameStep =\n finalName !== srcBasename\n ? `$SUDO cp -f ${quoteShellArg(initialPath)} ${quoteShellArg(finalPath)} && $SUDO rm -f ${quoteShellArg(initialPath)}`\n : ': # no rename';\n // Parent-chain chown: `mkdir -p` ran as root (via $SUDO), so any new dirs\n // between $HOME and the landed path are root-owned. When the dest is under\n // the box home, walk back up to $HOME (exclusive) and chown each so the\n // agent (vscode) can write siblings — e.g. session-teleport lands a rollout\n // under `~/.codex/sessions/YYYY/MM/DD/` and Codex must then create its\n // `state_*.sqlite` index in that subtree. System paths (/etc/*) and\n // /workspace keep their existing ownership. The whole script runs via\n // `bashScript()` (`bash -c '<body>'`), which protects `$(...)`/`while` from\n // Vercel's outer `sudo -u vscode -H bash -lc` wrapping.\n // Strictly *under* home (trailing segment) — never `=== BOX_HOME`, else\n // `dirname` would be `/home` and the walk could reassign `/home` itself.\n const underHome = finalPath.startsWith(BOX_HOME + '/');\n const parentWalk = underHome\n ? `parent=$(dirname ${quoteShellArg(finalPath)}); ` +\n `while [ \"$parent\" != ${quoteShellArg(BOX_HOME)} ] && [ \"$parent\" != \"/\" ]; do ` +\n `$SUDO chown \"$(id -un):$(id -gn)\" \"$parent\" || true; ` +\n `parent=$(dirname \"$parent\"); ` +\n `done`\n : `: # dest outside ${BOX_HOME}; leave parent ownership untouched`;\n const script = [\n `set -euo pipefail`,\n `if command -v sudo >/dev/null 2>&1; then SUDO='sudo -n'; else SUDO=''; fi`,\n `$SUDO mkdir -p ${quoteShellArg(boxParent)}`,\n // --no-same-permissions / --no-same-owner / -m: Daytona's S3-backed\n // FUSE volumes reject chmod/utime/chown; skipping them lets the extract\n // complete on a mounted-volume destination. Harmless no-op on the\n // sandbox's regular disk. Same flags as the credential-seed extract.\n `$SUDO tar -xzf ${quoteShellArg(REMOTE_UP_TAR)} -C ${quoteShellArg(boxParent)} --no-same-permissions --no-same-owner -m`,\n renameStep,\n // chown the landed subtree, then the parent chain back up to $HOME.\n // Tolerate failure (chown bad on read-only / FUSE mounts).\n `$SUDO chown -R \"$(id -un):$(id -gn)\" ${quoteShellArg(finalPath)} || true`,\n parentWalk,\n `rm -f ${quoteShellArg(REMOTE_UP_TAR)}`,\n ].join('\\n');\n const r = await backend.exec(handle, bashScript(script));\n if (r.exitCode !== 0) {\n throw new Error(`cloud upload extract failed: ${r.stderr || r.stdout}`);\n }\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n return { finalPath };\n}\n\n/**\n * Pull the *contents* of an in-sandbox directory into a host directory —\n * `/workspace/*` → `<hostDst>/*`, not `<hostDst>/<srcBasename>/*`. Used by\n * `agentbox download` (the bulk workspace pull); `downloadFromCloudBox`\n * preserves the source basename for `docker cp` parity.\n */\nexport async function pullCloudDirContents(\n backend: CloudBackend,\n handle: CloudHandle,\n boxSrcDir: string,\n hostDstDir: string,\n): Promise<CloudCpResult> {\n const dstAbs = hostResolve(hostDstDir);\n mkdirSync(dstAbs, { recursive: true });\n\n const stage = await mkdtemp(hostJoin(tmpdir(), 'agentbox-pull-'));\n const localTar = hostJoin(stage, 'payload.tar.gz');\n try {\n // `tar -C <dir> -czf <tarball> .` packs the contents (no leading\n // basename component) so extraction lands them in dstAbs directly.\n const packScript = [\n `set -euo pipefail`,\n `cd ${quoteShellArg(boxSrcDir)}`,\n `tar -czf ${quoteShellArg(REMOTE_DOWN_TAR)} .`,\n ].join('\\n');\n const r = await backend.exec(handle, bashScript(packScript));\n if (r.exitCode !== 0) {\n throw new Error(`cloud workspace pack failed: ${r.stderr || r.stdout}`);\n }\n await backend.downloadFile(handle, REMOTE_DOWN_TAR, localTar);\n await execa('tar', ['-xzf', localTar, '-C', dstAbs]);\n await backend\n .exec(handle, `rm -f ${quoteShellArg(REMOTE_DOWN_TAR)}`)\n .catch(() => {\n /* best-effort */\n });\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n return { finalPath: dstAbs };\n}\n\nasync function downloadOneFromCloudBox(\n backend: CloudBackend,\n handle: CloudHandle,\n boxSrc: string,\n hostDst: string,\n exclude?: string[],\n): Promise<CloudCpResult> {\n const srcBasename = posix.basename(boxSrc);\n const srcParent = posix.dirname(boxSrc);\n\n const dstAbs = hostResolve(hostDst);\n let hostParent: string;\n let finalName: string;\n const dstExists = existsSync(dstAbs);\n if (hostDst.endsWith('/') || (dstExists && statSync(dstAbs).isDirectory())) {\n hostParent = dstAbs;\n finalName = srcBasename;\n } else {\n hostParent = hostDirname(dstAbs);\n finalName = hostBasename(dstAbs);\n }\n mkdirSync(hostParent, { recursive: true });\n const finalPath = hostJoin(hostParent, finalName);\n\n const stage = await mkdtemp(hostJoin(tmpdir(), 'agentbox-cp-down-'));\n const localTar = hostJoin(stage, 'payload.tar.gz');\n try {\n const excludeArgs = (exclude ?? [])\n .map((p) => `--exclude=${quoteShellArg(p)}`)\n .join(' ');\n const packScript = [\n `set -euo pipefail`,\n `cd ${quoteShellArg(srcParent)}`,\n `tar -czf ${quoteShellArg(REMOTE_DOWN_TAR)} ${excludeArgs} ${quoteShellArg(srcBasename)}`,\n ].join('\\n');\n const r = await backend.exec(handle, bashScript(packScript));\n if (r.exitCode !== 0) {\n throw new Error(`cloud download pack failed: ${r.stderr || r.stdout}`);\n }\n await backend.downloadFile(handle, REMOTE_DOWN_TAR, localTar);\n await execa('tar', ['-xzf', localTar, '-C', hostParent]);\n if (finalName !== srcBasename) {\n renameSync(hostJoin(hostParent, srcBasename), finalPath);\n }\n // Best-effort cleanup; tolerate failure (sandbox may have ephemeral /tmp).\n await backend\n .exec(handle, `rm -f ${quoteShellArg(REMOTE_DOWN_TAR)}`)\n .catch(() => {\n /* best-effort */\n });\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n return { finalPath };\n}\n\n/**\n * Copy one or more host sources into the cloud box. A single source keeps full\n * `docker cp` semantics; ≥2 sources land under a destination directory (the\n * cloud path has no in-box `test -d` probe, so the dir is opted into with a\n * trailing `/`). The single-source primitive is run once per source, serially —\n * `REMOTE_UP_TAR` is a fixed remote staging path reused each iteration.\n */\nexport async function uploadToCloudBox(\n backend: CloudBackend,\n handle: CloudHandle,\n hostSrcs: string[],\n boxDst: string,\n exclude?: string[],\n): Promise<CloudCpResult> {\n if (hostSrcs.length === 1) {\n return uploadOneToCloudBox(backend, handle, hostSrcs[0]!, boxDst, exclude);\n }\n if (!boxDst.endsWith('/')) {\n throw new Error(\n `cannot copy multiple sources to '${boxDst}': destination is not a directory (add a trailing slash, e.g. ${boxDst}/)`,\n );\n }\n for (const src of hostSrcs) {\n await uploadOneToCloudBox(backend, handle, src, boxDst, exclude);\n }\n return { finalPath: boxDst };\n}\n\n/**\n * Copy one or more box sources to the host. A single source keeps full\n * `docker cp` semantics; ≥2 sources land under a destination directory. Run\n * serially — `REMOTE_DOWN_TAR` is a fixed remote staging path reused each\n * iteration.\n */\nexport async function downloadFromCloudBox(\n backend: CloudBackend,\n handle: CloudHandle,\n boxSrcs: string[],\n hostDst: string,\n exclude?: string[],\n): Promise<CloudCpResult> {\n if (boxSrcs.length === 1) {\n return downloadOneFromCloudBox(backend, handle, boxSrcs[0]!, hostDst, exclude);\n }\n const dstAbs = hostResolve(hostDst);\n const dstExists = existsSync(dstAbs);\n if (!hostDst.endsWith('/') && !(dstExists && statSync(dstAbs).isDirectory())) {\n throw new Error(\n `cannot copy multiple sources to '${hostDst}': destination is not a directory (add a trailing slash, e.g. ${hostDst}/)`,\n );\n }\n mkdirSync(dstAbs, { recursive: true });\n for (const src of boxSrcs) {\n await downloadOneFromCloudBox(backend, handle, src, dstAbs, exclude);\n }\n return { finalPath: dstAbs };\n}\n","import type { CloudBackend, CloudHandle } from '@agentbox/core';\nimport type { GitPushMode } from '@agentbox/config';\nimport { bashScript, quoteShellArgv } from './shell.js';\n\n/**\n * Kick the single in-box self-configure step (`agentbox-ctl bootstrap`) inside a\n * cloud sandbox. This replaces the three separate host-driven launches (dockerd,\n * the ctl daemon, VNC): the host now provisions, then runs ONE exec that hands\n * control to the box's idempotent bootstrap, which clones (optional) and starts\n * whatever isn't already live. The same kick serves create AND resume.\n *\n * The exec is synchronous — the host awaits the bootstrap so create still\n * reports readiness (the bootstrap detaches the long-lived daemons internally).\n * A non-zero exit means the ctl daemon failed to come up (fatal); dockerd/VNC\n * failures are best-effort inside the bootstrap and don't fail the exec.\n *\n * Env (relay tokens, dockerd/VNC flags, optional clone) is exported inline\n * rather than relied upon from the sandbox's provision-time env, so a stop/start\n * that doesn't preserve env still brings the box back the same way.\n */\nexport interface KickCloudBootstrapArgs {\n backend: CloudBackend;\n handle: CloudHandle;\n boxId: string;\n boxName: string;\n relayUrl?: string;\n relayToken?: string;\n bridgeToken?: string;\n /** Exported as AGENTBOX_WEB_PROXY_PORT (Vercel uses 8080). */\n webProxyPort?: number;\n /**\n * The bare host (no scheme) this box is reachable at, exported as\n * AGENTBOX_BOX_HOST so the in-box placeholder engine (`agentbox-ctl render`,\n * the `{{AGENTBOX_BOX_HOST}}` env-init pattern) resolves the real host instead\n * of the derived `<box-name>.localhost`. `<name>.localhost` for portless\n * backends, the public preview host (e.g. `<sub>.vercel.run`) otherwise. When\n * unset the in-box engine falls back to deriving `<box-name>.localhost`.\n */\n boxHost?: string;\n /** false → AGENTBOX_LAUNCH_DOCKERD=0 (Vercel can't run nested containers). */\n launchDockerd: boolean;\n /** Present → start the VNC stack with this password; undefined → VNC disabled. */\n vncPassword?: string;\n /**\n * Optional in-box clone. When set, the bootstrap clones /workspace from\n * `authedUrl` (token-bearing) and scrubs origin to `originUrl`. Used by the\n * plane / cloud-IDE create path; the laptop path host-seeds and omits this.\n */\n clone?: { authedUrl: string; originUrl: string; branch?: string; depth?: number };\n /**\n * Hosted control-plane base URL when this box's live relay is the plane. When\n * set, the kick exports `AGENTBOX_CONTROL_PLANE_URL` (daemon → forwarder\n * upstream) and writes `AGENTBOX_GIT_LEASE=1` into box.env (login-shell\n * `git push` → lease-and-push direct). Re-passed on every kick (create AND\n * reEnsure/attach) from the persisted record so resume preserves the topology.\n */\n controlPlaneUrl?: string;\n /**\n * Git push routing for this box (`git.pushMode`): `relay` (host relay pushes\n * with host creds), `lease` (box leases a token and pushes direct), or `auto`\n * (default — lease iff a control plane is configured). Only `lease` (explicit\n * or auto-with-control-plane) writes `AGENTBOX_GIT_LEASE=1`. Omitted = `auto`.\n */\n gitPushMode?: GitPushMode;\n onLog?: (line: string) => void;\n}\n\n/**\n * Pure builder for the two env surfaces a bootstrap kick emits. Split out so the\n * control-plane threading (`AGENTBOX_CONTROL_PLANE_URL` / `AGENTBOX_GIT_LEASE`)\n * is unit-testable without a backend.\n *\n * - `env` — exported for the bootstrap process + its detached children (the ctl\n * daemon reads these). Carries the relay/bridge tokens + the clone + upstream.\n * - `boxEnvFile` — the identity + placeholder subset persisted to\n * /etc/agentbox/box.env so interactive login shells (`agentbox shell`, and the\n * tmux shell where `git push` runs) resolve the same values. box.env is\n * world-readable (0644), so it deliberately excludes the relay/bridge tokens\n * (those travel via the daemon's 0600 /run/agentbox/relay.env) but DOES carry\n * the non-secret `AGENTBOX_GIT_LEASE` flag, which the login-shell `git push`\n * must see. Written on every kick (create AND reEnsure/attach).\n */\nexport function buildBootstrapEnv(args: KickCloudBootstrapArgs): {\n env: string[];\n boxEnvFile: string[];\n} {\n const env: string[] = [\n `AGENTBOX_BOX_ID=${quoteShellArgv([args.boxId])}`,\n `AGENTBOX_BOX_NAME=${quoteShellArgv([args.boxName])}`,\n `AGENTBOX_BOX_KIND=cloud`,\n `AGENTBOX_LAUNCH_DOCKERD=${args.launchDockerd ? '1' : '0'}`,\n ];\n if (args.relayUrl) env.push(`AGENTBOX_RELAY_URL=${quoteShellArgv([args.relayUrl])}`);\n if (args.relayToken) env.push(`AGENTBOX_RELAY_TOKEN=${quoteShellArgv([args.relayToken])}`);\n if (args.bridgeToken) env.push(`AGENTBOX_BRIDGE_TOKEN=${quoteShellArgv([args.bridgeToken])}`);\n if (args.webProxyPort !== undefined)\n env.push(`AGENTBOX_WEB_PROXY_PORT=${quoteShellArgv([String(args.webProxyPort)])}`);\n if (args.boxHost) env.push(`AGENTBOX_BOX_HOST=${quoteShellArgv([args.boxHost])}`);\n if (args.vncPassword) {\n env.push(`AGENTBOX_VNC_ENABLED=1`);\n env.push(`AGENTBOX_VNC_PASSWORD=${quoteShellArgv([args.vncPassword])}`);\n } else {\n env.push(`AGENTBOX_VNC_ENABLED=0`);\n }\n if (args.clone) {\n env.push(`AGENTBOX_CLONE_URL=${quoteShellArgv([args.clone.authedUrl])}`);\n env.push(`AGENTBOX_ORIGIN_URL=${quoteShellArgv([args.clone.originUrl])}`);\n if (args.clone.branch)\n env.push(`AGENTBOX_CLONE_BRANCH=${quoteShellArgv([args.clone.branch])}`);\n if (args.clone.depth !== undefined)\n env.push(`AGENTBOX_CLONE_DEPTH=${quoteShellArgv([String(args.clone.depth)])}`);\n }\n\n const boxEnvFile: string[] = [\n `AGENTBOX_BOX_ID=${quoteShellArgv([args.boxId])}`,\n `AGENTBOX_BOX_NAME=${quoteShellArgv([args.boxName])}`,\n `AGENTBOX_BOX_KIND=cloud`,\n ];\n if (args.webProxyPort !== undefined)\n boxEnvFile.push(`AGENTBOX_WEB_PROXY_PORT=${quoteShellArgv([String(args.webProxyPort)])}`);\n if (args.boxHost) boxEnvFile.push(`AGENTBOX_BOX_HOST=${quoteShellArgv([args.boxHost])}`);\n\n // Control-plane topology: the daemon needs the upstream URL (process env)\n // regardless of push routing — it drives the registry/events/permissions, not\n // just leasing.\n if (args.controlPlaneUrl) {\n env.push(`AGENTBOX_CONTROL_PLANE_URL=${quoteShellArgv([args.controlPlaneUrl])}`);\n }\n\n // Git push routing (git.pushMode). The login-shell `git push` leases + pushes\n // direct only when this flag is set; otherwise it routes through the host relay.\n // `auto` (default) leases iff a control plane is configured for the box.\n const pushMode = args.gitPushMode ?? 'auto';\n const lease = pushMode === 'lease' || (pushMode === 'auto' && Boolean(args.controlPlaneUrl));\n if (lease) {\n boxEnvFile.push(`AGENTBOX_GIT_LEASE=1`);\n }\n\n return { env, boxEnvFile };\n}\n\nexport async function kickCloudBootstrap(args: KickCloudBootstrapArgs): Promise<void> {\n const { env, boxEnvFile } = buildBootstrapEnv(args);\n\n const script = [\n `set -e`,\n // /etc/agentbox is root-owned; the non-root sandbox user needs sudo to\n // write the login-shell env file (cloud bases grant vscode passwordless\n // sudo; root SSH boxes fall through with SUDO=''). Quoted heredoc → the\n // values (already shell-quoted for `set -a; . box.env`) land verbatim.\n `if command -v sudo >/dev/null 2>&1; then SUDO='sudo -n'; else SUDO=''; fi`,\n `$SUDO mkdir -p /etc/agentbox`,\n `$SUDO tee /etc/agentbox/box.env >/dev/null <<'AGENTBOX_BOX_ENV_EOF'`,\n ...boxEnvFile,\n `AGENTBOX_BOX_ENV_EOF`,\n `export ${env.join(' ')}`,\n `/usr/local/bin/agentbox-ctl bootstrap`,\n ].join('\\n');\n\n const r = await args.backend.exec(args.handle, bashScript(script));\n if (r.stdout && args.onLog) {\n for (const line of r.stdout.split('\\n')) if (line.trim()) args.onLog(line);\n }\n if (r.exitCode !== 0) {\n throw new Error(`agentbox-ctl bootstrap failed: ${r.stderr || r.stdout}`);\n }\n}\n","/**\n * Register a control-plane cloud box on the hosted plane (not the laptop relay).\n *\n * A classic-cloud box is registered on the laptop's loopback relay (which then\n * runs a CloudBoxPoller to drain its /bridge). A control-plane box instead\n * forwards its /rpc straight to the plane, so it must be registered *on the\n * plane* — with its **origin URL**, which the plane needs to mint a repo-scoped\n * GitHub-App push token (`leaseTokenResult` mints from the registered origin,\n * never from box params). Uses the plane's admin bearer over HTTPS, mirroring\n * `apps/cli/src/control-plane/ensure-repo-installed.ts`.\n */\nimport { execa } from 'execa';\n\nexport interface RegisterBoxWithPlaneArgs {\n controlPlaneUrl: string;\n adminToken: string;\n boxId: string;\n token: string;\n name: string;\n originUrl: string;\n backend: string;\n bridgeToken?: string;\n previewUrl?: string;\n previewToken?: string;\n createdAt?: string;\n projectIndex?: number;\n autoApproveHostActions?: boolean;\n autoApproveSafeHostActions?: boolean;\n}\n\n/** Read the host workspace's `origin` remote URL (the box's push target). */\nexport async function readGitOriginUrl(workspacePath: string): Promise<string | undefined> {\n const r = await execa('git', ['-C', workspacePath, 'remote', 'get-url', 'origin'], {\n reject: false,\n });\n const url = (r.stdout ?? '').trim();\n return r.exitCode === 0 && url.length > 0 ? url : undefined;\n}\n\n/** POST /admin/register-box on the plane with the admin bearer. Throws on non-2xx. */\nexport async function registerBoxWithPlane(args: RegisterBoxWithPlaneArgs): Promise<void> {\n const url = `${args.controlPlaneUrl.replace(/\\/$/, '')}/admin/register-box`;\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${args.adminToken}`,\n },\n body: JSON.stringify({\n boxId: args.boxId,\n token: args.token,\n name: args.name,\n kind: 'cloud',\n backend: args.backend,\n originUrl: args.originUrl,\n bridgeToken: args.bridgeToken,\n previewUrl: args.previewUrl,\n previewToken: args.previewToken,\n createdAt: args.createdAt,\n projectIndex: args.projectIndex,\n autoApproveHostActions: args.autoApproveHostActions,\n autoApproveSafeHostActions: args.autoApproveSafeHostActions,\n }),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new Error(`plane register-box → ${String(res.status)}: ${text}`);\n }\n}\n","import { execa } from 'execa';\nimport { copyFile, mkdir, mkdtemp, rm, stat } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { CloudBackend, CloudHandle, ResyncResult } from '@agentbox/core';\nimport { detectGitRepos } from '@agentbox/sandbox-core';\nimport { bashScript, quoteShellArgv } from '../shell.js';\n\n/**\n * Seed `/workspace` inside a cloud sandbox from the host workspace. Mirrors\n * what `seedWorkspace` does for the Docker provider, adapted for the cloud\n * channel (`backend.uploadFile` + `backend.exec`):\n *\n * - Git workspace: `git clone --no-checkout [--depth=N] file://hostRepo`\n * into a host-side temp dir, tar the resulting `.git/`, upload, extract\n * into `/workspace`, repoint `origin`, `git checkout -B agentbox/<box>`\n * to materialize the working tree. Repeats per nested repo for monorepos.\n * - Non-git workspace: tar the host workspace, upload, extract.\n *\n * Why clone-and-tar instead of `git bundle`? `git bundle create` has no\n * `--depth` flag in any released git version (verified 2.39 and 2.52), and\n * the portable detours all produce bundles with unsatisfiable prerequisites.\n * Shipping a shallow clone is the only way to cap commit count portably.\n */\nexport interface SeedCloudWorkspaceArgs {\n backend: CloudBackend;\n handle: CloudHandle;\n /** Absolute host path the user passed via `-w`. */\n workspacePath: string;\n /** Branch name to check out inside the sandbox (`agentbox/<box-name>`). */\n branch: string;\n /** In-sandbox destination; defaults to `/workspace`. */\n workspaceDir?: string;\n /**\n * Commit cap for the host-side shallow `git clone`. `undefined` (the\n * common case) → adaptive default: clone the last `DEFAULT_BUNDLE_DEPTH`\n * commits and, if the resulting tar exceeds `LARGE_BUNDLE_THRESHOLD_BYTES`,\n * redo at `LARGE_BUNDLE_DEPTH`. `0` → full history (no `--depth`). `> 0` →\n * fixed shallow depth, no adaptive rebuild. Applied per repo.\n */\n bundleDepth?: number;\n /**\n * Base ref the box's `<branch>` is forked from (default: clone's HEAD).\n * When set, the host clone passes `--branch <fromBranch>` so the clone's\n * HEAD points at the requested ref, and the in-sandbox `git checkout -B\n * <branch>` picks it up. Nested repos keep their own default branch —\n * `<fromBranch>` is applied to the root only. Caller is responsible for\n * validating the ref host-side.\n */\n fromBranch?: string;\n /**\n * Reuse an existing branch directly (root repo only) instead of forking a\n * fresh per-box branch. The host clone pins `--branch <useBranch>` so the\n * clone HEAD lands on it, and the in-sandbox checkout is a plain `git\n * checkout <useBranch>` (no `-B` reset). Mutually exclusive with\n * `fromBranch` (enforced by the CLI). When set, `branch` equals\n * `useBranch`.\n */\n useBranch?: string;\n /**\n * Checkpoint-restore overlay mode. When true, `/workspace` already exists\n * (restored from a snapshot, carrying the checkpoint's gitignored warm\n * artifacts — node_modules, build caches, …). Instead of wiping it, swap\n * only `<repo>/.git` for a fresh host clone, move onto a fresh per-box\n * branch at the host's current base ref (`git checkout -f -B` + `git reset\n * --hard`), and overlay the host's uncommitted/untracked carry-over — the\n * gitignored warm state is left untouched. Non-git workspaces are left as\n * the snapshot baked them (no branch / carry-over concept).\n */\n overlay?: boolean;\n /**\n * Checkpoint-restore only: when true, re-branch to the host target but DON'T\n * replay the host's uncommitted (stash) / untracked carry-over. Set when the\n * user passed `--no-resync` (`resyncOnStart === false`) — mirrors docker's\n * checkpoint restore, which forks the fresh branch but skips\n * `resyncWorkspaceFromHost` when resync is off. Ignored on a fresh seed.\n */\n skipCarryOver?: boolean;\n onLog?: (line: string) => void;\n}\n\nexport interface SeedCloudWorkspaceResult {\n /** True when a git repo was found at the workspace root and a clone was used. */\n fromGit: boolean;\n /** Resolved branch (matches `branch` arg). */\n branch: string;\n /**\n * Conflicts from an overlay (checkpoint-restore) carry-over, in the shape the\n * CLI's `buildResyncWarning` consumes. Absent on a fresh (non-overlay) seed.\n */\n resync?: ResyncResult;\n}\n\nconst WORKSPACE_DIR_DEFAULT = '/workspace';\n\nexport async function seedCloudWorkspace(\n args: SeedCloudWorkspaceArgs,\n): Promise<SeedCloudWorkspaceResult> {\n const workspaceDir = args.workspaceDir ?? WORKSPACE_DIR_DEFAULT;\n const log = args.onLog ?? (() => {});\n const repos = await detectGitRepos(args.workspacePath);\n const root = repos.find((r) => r.kind === 'root');\n const nested = repos.filter((r) => r.kind === 'nested');\n\n if (!root && args.overlay) {\n // Checkpoint restore of a non-git workspace: there's no branch to fork and\n // no git carry-over to apply, and overlaying a tar would clobber the warm\n // snapshot tree. Keep /workspace exactly as the snapshot baked it.\n log('checkpoint restore: non-git workspace — keeping snapshot /workspace as-is');\n return { fromGit: false, branch: args.branch };\n }\n\n if (root) {\n log(\n args.overlay\n ? nested.length > 0\n ? `checkpoint restore: re-branching /workspace + ${String(nested.length)} nested repo${nested.length === 1 ? '' : 's'} (warm artifacts kept)`\n : 'checkpoint restore: re-branching /workspace onto a fresh per-box branch (warm artifacts kept)'\n : nested.length > 0\n ? `seeding /workspace from shallow git clone (+${String(nested.length)} nested repo${nested.length === 1 ? '' : 's'})`\n : 'seeding /workspace from shallow git clone',\n );\n const resyncRepos: ResyncResult['repos'] = [];\n const rootConflicts = await reseedRepo({\n backend: args.backend,\n handle: args.handle,\n hostRepo: root.hostMainRepo,\n branch: args.branch,\n workspaceDir,\n bundleDepth: args.bundleDepth,\n fromBranch: args.fromBranch,\n useBranch: args.useBranch,\n overlay: args.overlay,\n skipCarryOver: args.skipCarryOver,\n onLog: log,\n });\n if (args.overlay) resyncRepos.push({ containerPath: workspaceDir, ...rootConflicts });\n // Each nested repo gets its own clone at /workspace/<rel>. We do these\n // after the root clone because the root extract wipes /workspace; a\n // nested dir created during the root checkout (if tracked) would be\n // replaced when we extract over it.\n for (const r of nested) {\n const sub = `${workspaceDir}/${r.relPathFromWorkspace}`;\n log(`seeding nested repo ${r.relPathFromWorkspace} from shallow git clone`);\n const nestedConflicts = await reseedRepo({\n backend: args.backend,\n handle: args.handle,\n hostRepo: r.hostMainRepo,\n branch: args.branch,\n workspaceDir: sub,\n bundleDepth: args.bundleDepth,\n overlay: args.overlay,\n skipCarryOver: args.skipCarryOver,\n onLog: log,\n });\n if (args.overlay) resyncRepos.push({ containerPath: sub, ...nestedConflicts });\n }\n const resync: ResyncResult | undefined = args.overlay\n ? {\n repos: resyncRepos,\n hadConflicts: resyncRepos.some(\n (r) => r.mergeConflicts.length > 0 || r.overlaySkipped.length > 0,\n ),\n }\n : undefined;\n return { fromGit: true, branch: args.branch, resync };\n }\n\n log('seeding /workspace from workspace tarball (no git detected)');\n await seedFromTar({\n backend: args.backend,\n handle: args.handle,\n hostDir: args.workspacePath,\n workspaceDir,\n });\n return { fromGit: false, branch: args.branch };\n}\n\ninterface SeedFromGitCloneArgs {\n backend: CloudBackend;\n handle: CloudHandle;\n hostRepo: string;\n branch: string;\n workspaceDir: string;\n /** See `SeedCloudWorkspaceArgs.bundleDepth`. */\n bundleDepth?: number;\n /** See `SeedCloudWorkspaceArgs.fromBranch`. */\n fromBranch?: string;\n /** See `SeedCloudWorkspaceArgs.useBranch`. Root clone only. */\n useBranch?: string;\n /** See `SeedCloudWorkspaceArgs.overlay`. Swap only `.git`, keep the tree. */\n overlay?: boolean;\n /** See `SeedCloudWorkspaceArgs.skipCarryOver`. Re-branch but skip stash/untracked. */\n skipCarryOver?: boolean;\n onLog?: (line: string) => void;\n}\n\n/**\n * Temporary host ref used to carry the `git stash create` commit into the\n * shallow clone so the in-sandbox repo can apply it. Created before clone,\n * fetched into the clone under `refs/remotes/origin/<...>` with an explicit\n * refspec, then deleted from the host repo in `finally`.\n */\nconst STASH_CARRYOVER_REF = 'refs/agentbox-carryover/stash';\nconst REMOTE_UNTRACKED_TAR = '/tmp/agentbox-carryover-untracked.tar.gz';\n\n// In-box markers the carry-over script prints to stdout so the host can build a\n// `ResyncResult`. On a checkpoint restore the box wins every conflict (the host\n// change is skipped, never left unmerged) and the skipped path is reported here\n// — mirrors docker's `resyncWorkspaceFromHost` so the CLI injects the same\n// \"conflicting host changes SKIPPED … agentbox-ctl reload\" prompt to the agent.\nconst MERGE_CONFLICT_MARKER = '__AGENTBOX_MERGE_CONFLICT__:';\nconst OVERLAY_SKIP_MARKER = '__AGENTBOX_OVERLAY_SKIP__:';\n\n/** Per-repo conflict outcome of an overlay (checkpoint-restore) carry-over. */\nexport interface RepoSeedConflicts {\n mergeConflicts: string[];\n overlaySkipped: string[];\n}\n\nexport function parseSeedConflicts(stdout: string): RepoSeedConflicts {\n const merge = new Set<string>();\n const overlay = new Set<string>();\n for (const raw of stdout.split('\\n')) {\n const line = raw.trim();\n if (line.startsWith(MERGE_CONFLICT_MARKER)) {\n const p = line.slice(MERGE_CONFLICT_MARKER.length).trim();\n if (p) merge.add(p);\n } else if (line.startsWith(OVERLAY_SKIP_MARKER)) {\n const p = line.slice(OVERLAY_SKIP_MARKER.length).trim();\n if (p) overlay.add(p);\n }\n }\n return { mergeConflicts: [...merge], overlaySkipped: [...overlay] };\n}\n\n/**\n * In-box carry-over steps: replay the host's uncommitted (stash) + untracked\n * state onto the freshly checked-out tree. `detectConflicts` (checkpoint\n * restore) makes every collision resolve box-wins and emit a marker:\n * - stash apply conflict → `git checkout --ours` the unmerged paths (keep the\n * box's version), report them as MERGE_CONFLICT.\n * - untracked file already present in the box → skip it (`tar --skip-old-files`)\n * and report it as OVERLAY_SKIP.\n * Fresh seed (no `detectConflicts`) checks out onto an empty tree, so the simple\n * apply/extract can never collide. Pipes (not `< <(...)`) — the box has no\n * /dev/fd (Vercel/Firecracker). All steps are `-e`-safe.\n */\nexport function buildCarryOverSteps(opts: {\n workspaceDir: string;\n hasStash: boolean;\n hasUntracked: boolean;\n detectConflicts: boolean;\n}): string[] {\n const wd = quoteShellArgv([opts.workspaceDir]);\n const stashRef = quoteShellArgv(['refs/remotes/origin/agentbox-carryover/stash']);\n const untracked = quoteShellArgv([REMOTE_UNTRACKED_TAR]);\n const steps: string[] = [];\n if (opts.hasStash) {\n steps.push(\n opts.detectConflicts\n ? `if git -C ${wd} rev-parse --verify ${stashRef} >/dev/null 2>&1; then ` +\n `if ! git -C ${wd} stash apply ${stashRef} >/dev/null 2>&1; then ` +\n `git -C ${wd} diff --name-only --diff-filter=U | while IFS= read -r p; do [ -n \"$p\" ] && echo \"${MERGE_CONFLICT_MARKER}$p\"; done || true ; ` +\n `git -C ${wd} checkout --ours -- . >/dev/null 2>&1 || true ; ` +\n `git -C ${wd} add -A >/dev/null 2>&1 || true ; ` +\n `fi ; ` +\n `git -C ${wd} update-ref -d ${stashRef} || true ; ` +\n `fi`\n : `if git -C ${wd} rev-parse --verify ${stashRef} >/dev/null 2>&1; then ` +\n `git -C ${wd} stash apply ${stashRef} || ` +\n `echo \"agentbox: stash apply soft-failed; carry-over may be incomplete\" >&2 ; ` +\n `git -C ${wd} update-ref -d ${stashRef} || true ; ` +\n `fi`,\n );\n }\n if (opts.hasUntracked) {\n steps.push(\n opts.detectConflicts\n ? `if [ -f ${untracked} ]; then ` +\n // Report (but don't clobber) untracked files that already exist in\n // the box tree, then extract only the new ones (--skip-old-files).\n `tar -tzf ${untracked} | while IFS= read -r p; do case \"$p\" in ''|*/) continue ;; esac; if [ -e ${wd}/\"$p\" ]; then echo \"${OVERLAY_SKIP_MARKER}$p\"; fi; done || true ; ` +\n `tar -C ${wd} --skip-old-files -xzf ${untracked} || true ; ` +\n `rm -f ${untracked} ; ` +\n `fi`\n : `if [ -f ${untracked} ]; then ` +\n `tar -C ${wd} -xzf ${untracked} && rm -f ${untracked} ; ` +\n `fi`,\n );\n }\n return steps;\n}\n\n/**\n * Adaptive cap on the host-side shallow clone. Default keeps cold cloud\n * creates fast on big monorepos: clone the last 200 commits; if the tarred\n * `.git/` still exceeds 20 MB, redo at 100. Explicit `bundleDepth` skips\n * the adaptive rebuild (the user picked a number; trust it).\n */\nconst DEFAULT_BUNDLE_DEPTH = 200;\nconst LARGE_BUNDLE_DEPTH = 100;\nconst LARGE_BUNDLE_THRESHOLD_BYTES = 20 * 1024 * 1024;\n\n/**\n * Per-repo seed dispatcher. Fresh create → full shallow clone. Checkpoint\n * restore (`overlay`) → try the incremental delta-bundle path (ship only the\n * host commits the checkpoint's `.git` is missing), falling back to the\n * full-clone overlay (`.git` swap) when the box diverged / the delta isn't\n * computable. Returns the carry-over conflicts (empty for a fresh seed).\n */\nasync function reseedRepo(args: SeedFromGitCloneArgs): Promise<RepoSeedConflicts> {\n if (args.overlay) {\n const delta = await tryReseedRepoDelta(args);\n if (delta) return delta;\n (args.onLog ?? (() => {}))(\n `checkpoint restore: ${args.workspaceDir}: delta not usable, falling back to full clone`,\n );\n }\n return seedFromGitClone(args);\n}\n\nasync function seedFromGitClone(args: SeedFromGitCloneArgs): Promise<RepoSeedConflicts> {\n const log = args.onLog ?? (() => {});\n let conflicts: RepoSeedConflicts = { mergeConflicts: [], overlaySkipped: [] };\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-clone-'));\n const cloneDir = join(stage, 'clone');\n const tarPath = join(stage, 'workspace.tar.gz');\n const untrackedTarPath = join(stage, 'untracked.tar.gz');\n // Per-repo carry-over (mirrors `collectRepoCarryOver` from sandbox-docker):\n // - `git stash create` captures every staged + tracked-modified change\n // (including deletes/renames) as a one-off commit.\n // - untracked files get tarred separately because `stash create` (no -u\n // option) doesn't capture them.\n // The stash commit rides into the shallow clone via an explicit-refspec\n // fetch after the initial clone (HEAD-only clone doesn't pull arbitrary\n // refs). The untracked tar uploads on the side and the in-sandbox script\n // untars it after `git checkout` materializes the working tree.\n //\n // --use-branch skips carry-over entirely: the box gets the reused branch's\n // committed tip, not the host's uncommitted state (which may belong to a\n // different branch). Mirrors the docker reuse path, which builds its\n // RepoCarryOver with `stashSha: null` / empty untracked.\n const stashSha =\n args.useBranch || args.skipCarryOver ? null : await safeStashCreate(args.hostRepo);\n const untrackedSize =\n args.useBranch || args.skipCarryOver\n ? 0\n : await maybeBuildUntrackedTar(args.hostRepo, untrackedTarPath);\n let stashRefCreated = false;\n try {\n if (stashSha) {\n const ref = await execa(\n 'git',\n ['-C', args.hostRepo, 'update-ref', STASH_CARRYOVER_REF, stashSha],\n { reject: false },\n );\n stashRefCreated = ref.exitCode === 0;\n }\n // Pick the initial depth.\n // - undefined → adaptive default (200, may rebuild at 100 if >20 MB)\n // - 0 → full history (no `--depth` flag)\n // - N > 0 → fixed shallow depth, no rebuild\n // Shallow history is fine here because `git push` from inside the box\n // travels through the host relay's bundle pull-back, which resolves the\n // merge base against the host repo's full history.\n const configured = args.bundleDepth;\n const adaptive = configured === undefined;\n const initialDepth: number | null = adaptive\n ? DEFAULT_BUNDLE_DEPTH\n : configured === 0\n ? null\n : configured;\n log(\n adaptive\n ? `clone: depth=${String(DEFAULT_BUNDLE_DEPTH)} (default, adaptive)`\n : initialDepth === null\n ? 'clone: depth=full (configured)'\n : `clone: depth=${String(initialDepth)} (configured)`,\n );\n // --use-branch reuses the named branch directly; otherwise --from-branch\n // (or nothing) picks the fork base. Either way it pins the clone's HEAD.\n const cloneBranch = args.useBranch ?? args.fromBranch;\n const lfsRef = cloneBranch ?? 'HEAD';\n await runShallowClone(args.hostRepo, cloneDir, initialDepth, stashRefCreated, cloneBranch);\n // Pack the checkout ref's LFS objects into the clone's .git/lfs BEFORE the\n // tar so the in-box checkout smudges real content (no box network/creds).\n await seedCloneLfsObjects(args.hostRepo, cloneDir, lfsRef, log);\n await tarCloneDir(cloneDir, tarPath);\n if (adaptive && initialDepth !== null) {\n const size = await safeFileSize(tarPath);\n if (size > LARGE_BUNDLE_THRESHOLD_BYTES) {\n const mb = (size / (1024 * 1024)).toFixed(1);\n log(\n `clone tar exceeded ${String(LARGE_BUNDLE_THRESHOLD_BYTES / (1024 * 1024))} MB at depth ${String(DEFAULT_BUNDLE_DEPTH)} (${mb} MB), rebuilding at depth ${String(LARGE_BUNDLE_DEPTH)}`,\n );\n await rm(cloneDir, { recursive: true, force: true });\n await rm(tarPath, { force: true });\n await runShallowClone(args.hostRepo, cloneDir, LARGE_BUNDLE_DEPTH, stashRefCreated, cloneBranch);\n // Fresh cloneDir from the rebuild — re-seed its LFS objects too.\n await seedCloneLfsObjects(args.hostRepo, cloneDir, lfsRef, log);\n await tarCloneDir(cloneDir, tarPath);\n }\n }\n const remoteUrl = await readOriginUrl(args.hostRepo);\n const remoteTar = '/tmp/agentbox-workspace.tar.gz';\n await args.backend.uploadFile(args.handle, tarPath, remoteTar);\n if (untrackedSize > 0) {\n await args.backend.uploadFile(args.handle, untrackedTarPath, REMOTE_UNTRACKED_TAR);\n }\n const setOrigin = remoteUrl\n ? `git -C ${quoteShellArgv([args.workspaceDir])} remote set-url origin ${quoteShellArgv([remoteUrl])}`\n : ': # no host origin to copy';\n // Extract the shallow clone's .git over the destination, then repoint\n // `origin` from the file:// placeholder to the real upstream so future\n // fetch/push target the actual remote (`git push` itself travels back\n // through the host relay). `git checkout -B <branch>` then materializes\n // the working tree from HEAD (the clone was `--no-checkout`, so the\n // tarball only carried `.git/`).\n // /workspace lives at the root in the snapshot — root-owned by default\n // (Dockerfile.box never chowns it). The sandbox runs non-root, so the\n // dir ops need sudo. The devcontainers/base image grants passwordless\n // sudo to `vscode`; SUDO is a no-op when sudo isn't needed/available.\n const SUDO = `if command -v sudo >/dev/null 2>&1; then SUDO='sudo -n'; else SUDO=''; fi`;\n // Stash apply is best-effort — applying onto a possibly shallow clone\n // can hit \"needs merge\" conflicts in pathological cases (e.g. host had\n // local changes against a commit outside the depth window). Soft-fail\n // is better than blocking provision; any unapplied changes can be\n // re-derived from the host as a fallback.\n const carryOverSteps = buildCarryOverSteps({\n workspaceDir: args.workspaceDir,\n hasStash: Boolean(stashSha),\n hasUntracked: untrackedSize > 0,\n // Conflict detection (box-wins + markers) only matters on a checkpoint\n // restore, where /workspace already has the snapshot's files to collide\n // with. A fresh seed checks out onto an empty tree — nothing to conflict.\n detectConflicts: Boolean(args.overlay),\n });\n // Overlay (checkpoint restore) keeps the snapshot's working tree (its\n // gitignored warm artifacts are the checkpoint's value) and swaps only\n // `<dir>/.git`; the force-checkout + `reset --hard` then move the box onto\n // a fresh per-box branch at the host base ref, dropping the source box's\n // stale TRACKED deviations while leaving untracked/ignored files intact.\n // Fresh seed wipes the dir and materializes the tree from scratch.\n const gitDir = `${args.workspaceDir}/.git`;\n const prepSteps = args.overlay\n ? [`$SUDO rm -rf ${quoteShellArgv([gitDir])}`]\n : [\n `$SUDO rm -rf ${quoteShellArgv([args.workspaceDir])}`,\n `$SUDO mkdir -p ${quoteShellArgv([args.workspaceDir])}`,\n `$SUDO chown \"$(id -un):$(id -gn)\" ${quoteShellArgv([args.workspaceDir])}`,\n ];\n const checkoutSteps = args.overlay\n ? [\n args.useBranch\n ? `git -C ${quoteShellArgv([args.workspaceDir])} checkout -f ${quoteShellArgv([args.branch])}`\n : `git -C ${quoteShellArgv([args.workspaceDir])} checkout -f -B ${quoteShellArgv([args.branch])}`,\n `git -C ${quoteShellArgv([args.workspaceDir])} reset --hard HEAD`,\n ]\n : [\n // reuse: the clone already landed on `<branch>` (pinned via\n // `--branch`); a plain checkout materializes the working tree without\n // resetting the ref. fork: `-B` (re)points `<branch>` at clone HEAD.\n args.useBranch\n ? `git -C ${quoteShellArgv([args.workspaceDir])} checkout ${quoteShellArgv([args.branch])}`\n : `git -C ${quoteShellArgv([args.workspaceDir])} checkout -B ${quoteShellArgv([args.branch])}`,\n ];\n const script = [\n `set -euo pipefail`,\n // Move out of any cwd we might inherit from Daytona's executeCommand\n // before we delete /workspace. The agentbox image bakes WORKDIR\n // /workspace; if the shell's cwd is /workspace when we `rm -rf` it,\n // the next process inherits a stale cwd FD and tar's children fail\n // with \"Unable to read current working directory\".\n `cd /tmp`,\n SUDO,\n // Fresh: rm -rf only the dir we extract into (for nested repos that's\n // `/workspace/<rel>`, so the root clone is preserved). Overlay: rm only\n // `<dir>/.git`, preserving the warm working tree.\n ...prepSteps,\n `tar -C ${quoteShellArgv([args.workspaceDir])} -xzf ${quoteShellArgv([remoteTar])}`,\n setOrigin,\n ...checkoutSteps,\n ...carryOverSteps,\n `rm -f ${quoteShellArgv([remoteTar])}`,\n ].join('\\n');\n // Daytona's executeCommand shells out via dash (`/bin/sh`), which rejects\n // bash idioms like `set -o pipefail`. Wrap in `bash -c` so the script\n // runs in bash regardless of what `/bin/sh` points at.\n const r = await args.backend.exec(args.handle, bashScript(script));\n if (r.exitCode !== 0) {\n throw new Error(`workspace seed (clone) failed: ${r.stderr || r.stdout}`);\n }\n if (args.overlay) conflicts = parseSeedConflicts(r.stdout);\n } finally {\n // Defensive cleanup of the temp stash ref on host. If we threw between\n // updates, the ref may still be present; delete it so re-runs don't\n // accrue refs/agentbox-carryover/* entries.\n if (stashRefCreated) {\n await execa('git', ['-C', args.hostRepo, 'update-ref', '-d', STASH_CARRYOVER_REF], {\n reject: false,\n });\n }\n await rm(stage, { recursive: true, force: true });\n }\n return conflicts;\n}\n\nconst DELTA_TARGET_REF = 'refs/agentbox-delta/target';\nconst REMOTE_DELTA_BUNDLE = '/tmp/agentbox-delta.bundle';\nconst REMOTE_DELTA_LFS = '/tmp/agentbox-delta-lfs.tar.gz';\nconst SHA_RE = /^[0-9a-f]{40}$/;\n\n/**\n * Incremental checkpoint-restore for one repo: instead of re-cloning the whole\n * history, ship only the commits the snapshot's `/workspace/.git` is MISSING\n * (`checkpointTip..hostTarget`) as a git bundle, fetch them into the existing\n * `.git`, then move onto the fresh per-box branch at the host target and replay\n * carry-over. Returns the carry-over conflicts on success, or `null` to signal\n * the caller to fall back to a full-clone overlay (box diverged / tip unknown /\n * bundle build failed). Drops the checkpoint's own tracked commits by resetting\n * to the host target — matching docker.\n */\nasync function tryReseedRepoDelta(args: SeedFromGitCloneArgs): Promise<RepoSeedConflicts | null> {\n const log = args.onLog ?? (() => {});\n const wd = quoteShellArgv([args.workspaceDir]);\n\n // 1. The commit the snapshot's /workspace/.git is parked at.\n const tipRes = await args.backend.exec(\n args.handle,\n bashScript(`git -C ${wd} rev-parse HEAD 2>/dev/null || true`),\n );\n const checkpointTip = tipRes.stdout.trim();\n if (!SHA_RE.test(checkpointTip)) return null; // not a git repo / detached weirdness\n\n // 2. The host fork base (same ref the fresh seed forks from).\n const baseRef = args.useBranch ?? args.fromBranch ?? 'HEAD';\n const targetRes = await execa('git', ['-C', args.hostRepo, 'rev-parse', baseRef], {\n reject: false,\n });\n const target = targetRes.stdout.trim();\n if (targetRes.exitCode !== 0 || !SHA_RE.test(target)) return null;\n\n // 3. Delta is only valid when the host still has checkpointTip AND it's an\n // ancestor of the target (otherwise the box diverged → full-clone reset).\n const hasTip = await execa(\n 'git',\n ['-C', args.hostRepo, 'cat-file', '-e', `${checkpointTip}^{commit}`],\n { reject: false },\n );\n if (hasTip.exitCode !== 0) return null;\n const ancestor = await execa(\n 'git',\n ['-C', args.hostRepo, 'merge-base', '--is-ancestor', checkpointTip, target],\n { reject: false },\n );\n if (ancestor.exitCode !== 0) return null;\n\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-delta-'));\n const bundlePath = join(stage, 'delta.bundle');\n const untrackedTarPath = join(stage, 'untracked.tar.gz');\n const deltaLfsTarPath = join(stage, 'delta-lfs.tar.gz');\n // --use-branch reuses the committed tip; no host uncommitted carry-over.\n const stashSha =\n args.useBranch || args.skipCarryOver ? null : await safeStashCreate(args.hostRepo);\n const untrackedSize =\n args.useBranch || args.skipCarryOver\n ? 0\n : await maybeBuildUntrackedTar(args.hostRepo, untrackedTarPath);\n let stashRefCreated = false;\n try {\n if (stashSha) {\n const ref = await execa(\n 'git',\n ['-C', args.hostRepo, 'update-ref', STASH_CARRYOVER_REF, stashSha],\n { reject: false },\n );\n stashRefCreated = ref.exitCode === 0;\n }\n const needTarget = target !== checkpointTip;\n if (needTarget) {\n await execa('git', ['-C', args.hostRepo, 'update-ref', DELTA_TARGET_REF, target], {\n reject: false,\n });\n }\n // Bundle the refs the box lacks, excluding everything it already has\n // (`^checkpointTip` — the box holds this, so the bundle's prerequisite is\n // satisfiable even though its .git is shallow).\n const bundleRefs: string[] = [];\n if (needTarget) bundleRefs.push(DELTA_TARGET_REF);\n if (stashRefCreated) bundleRefs.push(STASH_CARRYOVER_REF);\n let haveBundle = false;\n if (bundleRefs.length > 0) {\n const b = await execa(\n 'git',\n ['-C', args.hostRepo, 'bundle', 'create', bundlePath, ...bundleRefs, `^${checkpointTip}`],\n { reject: false },\n );\n if (b.exitCode !== 0) return null; // unexpected → fall back to full clone\n haveBundle = true;\n await args.backend.uploadFile(args.handle, bundlePath, REMOTE_DELTA_BUNDLE);\n }\n if (untrackedSize > 0) {\n await args.backend.uploadFile(args.handle, untrackedTarPath, REMOTE_UNTRACKED_TAR);\n }\n // Ship the LFS objects the delta introduces (oids in target but not in the\n // checkpoint tip the box already holds), so the post-restore checkout\n // smudges new LFS files to real content. Bounded + best-effort.\n const deltaLfsSize = await maybeBuildDeltaLfsTar(\n args.hostRepo,\n target,\n checkpointTip,\n deltaLfsTarPath,\n );\n if (deltaLfsSize > 0) {\n await args.backend.uploadFile(args.handle, deltaLfsTarPath, REMOTE_DELTA_LFS);\n log(\n `checkpoint restore: ${args.workspaceDir}: ${String(deltaLfsSize)} B of new git-lfs objects`,\n );\n }\n log(\n needTarget\n ? `checkpoint restore: ${args.workspaceDir}: delta bundle (${checkpointTip.slice(0, 8)}..${target.slice(0, 8)})`\n : `checkpoint restore: ${args.workspaceDir}: no new host commits; re-branch + carry-over only`,\n );\n\n const remoteUrl = await readOriginUrl(args.hostRepo);\n const setOrigin = remoteUrl\n ? `git -C ${wd} remote set-url origin ${quoteShellArgv([remoteUrl])}`\n : ': # no host origin to copy';\n const fetchRefspecs: string[] = [];\n if (needTarget) fetchRefspecs.push(`+${DELTA_TARGET_REF}:${DELTA_TARGET_REF}`);\n if (stashRefCreated)\n fetchRefspecs.push(`+${STASH_CARRYOVER_REF}:refs/remotes/origin/agentbox-carryover/stash`);\n const fetchStep =\n haveBundle && fetchRefspecs.length > 0\n ? `git -C ${wd} fetch --no-tags ${quoteShellArgv([REMOTE_DELTA_BUNDLE])} ${fetchRefspecs.map((s) => quoteShellArgv([s])).join(' ')}`\n : ': # no delta bundle to fetch';\n // Box ends at the host target SHA (drop the checkpoint's own commits), on a\n // fresh per-box branch; gitignored warm artifacts are untouched by checkout/reset.\n const checkoutStep = args.useBranch\n ? `git -C ${wd} checkout -f ${quoteShellArgv([args.branch])}`\n : `git -C ${wd} checkout -f -B ${quoteShellArgv([args.branch])} ${quoteShellArgv([target])}`;\n const carryOverSteps = buildCarryOverSteps({\n workspaceDir: args.workspaceDir,\n hasStash: Boolean(stashSha),\n hasUntracked: untrackedSize > 0,\n detectConflicts: true,\n });\n // Extract the delta's new LFS objects into the box's object store BEFORE the\n // checkout/reset smudges them. `.git/lfs/objects/aa/bb/<oid>` layout is\n // preserved by the tar so they land content-addressed.\n const lfsStep =\n deltaLfsSize > 0\n ? `tar -C ${quoteShellArgv([`${args.workspaceDir}/.git`])} -xzf ${quoteShellArgv([REMOTE_DELTA_LFS])}`\n : ': # no delta lfs objects';\n const SUDO = `if command -v sudo >/dev/null 2>&1; then SUDO='sudo -n'; else SUDO=''; fi`;\n const script = [\n `set -euo pipefail`,\n `cd /tmp`,\n SUDO,\n fetchStep,\n lfsStep,\n checkoutStep,\n `git -C ${wd} reset --hard ${quoteShellArgv([target])}`,\n setOrigin,\n ...carryOverSteps,\n `git -C ${wd} update-ref -d ${quoteShellArgv([DELTA_TARGET_REF])} || true`,\n `rm -f ${quoteShellArgv([REMOTE_DELTA_BUNDLE])} ${quoteShellArgv([REMOTE_DELTA_LFS])}`,\n ].join('\\n');\n const r = await args.backend.exec(args.handle, bashScript(script));\n if (r.exitCode !== 0) {\n // The box's .git is intact (we only fetched + checked out); a clean\n // fall-back to the full-clone overlay can still recover.\n log(`checkpoint restore: ${args.workspaceDir}: delta apply failed, falling back: ${r.stderr || r.stdout}`);\n return null;\n }\n return parseSeedConflicts(r.stdout);\n } finally {\n if (stashRefCreated) {\n await execa('git', ['-C', args.hostRepo, 'update-ref', '-d', STASH_CARRYOVER_REF], {\n reject: false,\n });\n }\n await execa('git', ['-C', args.hostRepo, 'update-ref', '-d', DELTA_TARGET_REF], {\n reject: false,\n });\n await rm(stage, { recursive: true, force: true });\n }\n}\n\n/**\n * Shallow `git clone --no-checkout` into `cloneDir`. `depth === null` → full\n * history (no `--depth` flag). When the host carries a stash ref, that ref\n * is explicitly fetched into the new clone under `refs/remotes/origin/...`\n * with a matching `--depth`, so the in-box `stash apply` can find it.\n *\n * `--no-checkout` skips materializing the working tree on host (we'd just\n * throw it away when we tar `.git/`). `file://` is required so git treats\n * the source as a remote — without it, `git clone <local-path>` uses object\n * hardlinks and silently ignores `--depth`, producing a full clone.\n */\nasync function runShallowClone(\n hostRepo: string,\n cloneDir: string,\n depth: number | null,\n includeStashRef: boolean,\n fromBranch?: string,\n): Promise<void> {\n const cloneArgs: string[] = ['clone', '--no-checkout', '--quiet'];\n if (depth !== null) cloneArgs.push(`--depth=${String(depth)}`);\n // `--branch` pins the clone's HEAD to the requested ref so the in-sandbox\n // `git checkout -B <branch>` picks up that ref as the fork point. Accepts\n // branch names + tags; SHAs aren't supported by `git clone --branch` and\n // would need a separate fetch (callers using SHAs should validate\n // host-side and pass a branch/tag name instead, or skip --from-branch).\n if (fromBranch) cloneArgs.push('--branch', fromBranch);\n cloneArgs.push(`file://${hostRepo}`, cloneDir);\n await execa('git', cloneArgs);\n if (includeStashRef) {\n // Soft-fail: the stash commit's parents could in principle fall outside\n // a very shallow window; the in-box `stash apply` already soft-fails,\n // so missing the ref here is equivalent.\n const fetchArgs: string[] = ['-C', cloneDir, 'fetch', '--quiet'];\n if (depth !== null) fetchArgs.push(`--depth=${String(depth)}`);\n fetchArgs.push(\n `file://${hostRepo}`,\n `+${STASH_CARRYOVER_REF}:refs/remotes/origin/agentbox-carryover/stash`,\n );\n await execa('git', fetchArgs, { reject: false });\n }\n}\n\nasync function tarCloneDir(cloneDir: string, outPath: string): Promise<void> {\n await execa('tar', ['-C', cloneDir, '-czf', outPath, '.'], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n}\n\nconst LFS_OID_RE = /^[0-9a-f]{64}$/;\n\n/** Content-addressed path of an LFS object inside a `.git/` dir: `lfs/objects/aa/bb/<oid>`. */\nexport function lfsObjectRelPath(oid: string): string {\n return join('lfs', 'objects', oid.slice(0, 2), oid.slice(2, 4), oid);\n}\n\n/**\n * The set of LFS object oids reachable from `ref` in `hostRepo`. Empty when the\n * repo doesn't use LFS, `ref` is unknown, or git-lfs isn't installed on the host\n * (all best-effort — never throws). `git lfs ls-files --long` prints\n * \"<oid> <* or -> <path>\" per tracked blob.\n */\nasync function lfsOidsForRef(hostRepo: string, ref: string): Promise<string[]> {\n const listed = await execa('git', ['-C', hostRepo, 'lfs', 'ls-files', '--long', ref], {\n reject: false,\n });\n if (listed.exitCode !== 0) return [];\n const oids = listed.stdout\n .split('\\n')\n .map((l) => l.trim().split(/\\s+/)[0] ?? '')\n .filter((o) => LFS_OID_RE.test(o));\n return [...new Set(oids)];\n}\n\n/**\n * Pack the LFS objects reachable from `ref` into the shallow clone's\n * `.git/lfs/objects/` BEFORE it's tarred, so the in-box `git checkout` smudges\n * real content instead of leaving pointer files. Docker gets this for free via\n * its bind-mounted shared `.git/lfs`; cloud has no bind mount, so we copy the\n * content-addressed blobs into the clone where they ride the existing workspace\n * tar (no box network / credentials needed at checkout).\n *\n * Bounded + best-effort, mirroring the docker provider's `prefetchHostLfs`:\n * - probe `git lfs ls-files` → a non-LFS repo does nothing, no log noise.\n * - `git lfs fetch origin <ref>` (host holds the creds) warms the host cache.\n * - copy ONLY the ref's oids (not the whole `.git/lfs` cache, which can be\n * GBs) into the clone. A missing oid (fetch failed / offline) is left as a\n * pointer — the box still seeds, just without that object's content.\n */\nasync function seedCloneLfsObjects(\n hostRepo: string,\n cloneDir: string,\n ref: string,\n log: (line: string) => void,\n): Promise<void> {\n // Cheap probe so the overwhelmingly common non-LFS repo does nothing and logs\n // nothing. Empty stdout or non-zero exit (no git-lfs binary / not LFS) → skip.\n const tracked = await execa('git', ['-C', hostRepo, 'lfs', 'ls-files', '-n', ref], {\n reject: false,\n });\n if (tracked.exitCode !== 0 || tracked.stdout.trim().length === 0) return;\n\n // Warm the host object cache for the checkout ref (uses the host's creds).\n const fetched = await execa('git', ['-C', hostRepo, 'lfs', 'fetch', 'origin', ref], {\n reject: false,\n });\n if (fetched.exitCode !== 0) {\n const msg = (fetched.stderr || fetched.stdout || `exit ${String(fetched.exitCode ?? '?')}`)\n .trim()\n .split('\\n')[0];\n log(`git-lfs prefetch for ${ref} skipped (best-effort, continuing): ${msg}`);\n }\n\n const oids = await lfsOidsForRef(hostRepo, ref);\n let copied = 0;\n for (const oid of oids) {\n const rel = lfsObjectRelPath(oid);\n const dst = join(cloneDir, '.git', rel);\n try {\n await mkdir(dirname(dst), { recursive: true });\n await copyFile(join(hostRepo, '.git', rel), dst);\n copied++;\n } catch {\n // Object isn't in the host cache (fetch missed / offline) — leave the\n // pointer; the box surfaces it as a pointer rather than failing the seed.\n }\n }\n if (copied > 0) log(`seeded ${String(copied)} git-lfs object(s) for ${ref} into clone`);\n}\n\n/**\n * Tar the LFS objects that the checkpoint restore's delta introduces — the oids\n * reachable from `target` but not from `checkpointTip` (which the box already\n * has from when it was first seeded). Preserves the `lfs/objects/aa/bb/<oid>`\n * layout so an in-box `tar -x` into `<workspaceDir>/.git` lands them in the\n * box's object store. Returns the tar size (0 when there's nothing to ship, so\n * the caller can skip the upload + extract). Best-effort; never throws.\n */\nasync function maybeBuildDeltaLfsTar(\n hostRepo: string,\n target: string,\n checkpointTip: string,\n outPath: string,\n): Promise<number> {\n const targetOids = await lfsOidsForRef(hostRepo, target);\n if (targetOids.length === 0) return 0;\n const have = new Set(await lfsOidsForRef(hostRepo, checkpointTip));\n const deltaOids = targetOids.filter((o) => !have.has(o));\n if (deltaOids.length === 0) return 0;\n\n // Warm the host cache for the target ref, then keep only the oids whose blob\n // actually exists on disk (a missed fetch just ships fewer objects).\n await execa('git', ['-C', hostRepo, 'lfs', 'fetch', 'origin', target], { reject: false });\n const gitDir = join(hostRepo, '.git');\n const relPaths: string[] = [];\n for (const oid of deltaOids) {\n const rel = lfsObjectRelPath(oid);\n try {\n await stat(join(gitDir, rel));\n relPaths.push(rel);\n } catch {\n // not present — skip\n }\n }\n if (relPaths.length === 0) return 0;\n const tar = await execa('tar', ['-C', gitDir, '-czf', outPath, ...relPaths], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n reject: false,\n });\n if (tar.exitCode !== 0) return 0;\n return safeFileSize(outPath);\n}\n\nasync function safeFileSize(path: string): Promise<number> {\n try {\n return (await stat(path)).size;\n } catch {\n return 0;\n }\n}\n\n/**\n * Best-effort `git stash create` on the host repo. Returns the stash SHA\n * (or `null` when the worktree is clean / git is missing / the call fails).\n * Mirrors the docker provider's `collectRepoCarryOver` shape — pure host\n * git, no side effects on the working tree.\n */\nasync function safeStashCreate(hostRepo: string): Promise<string | null> {\n const r = await execa('git', ['-C', hostRepo, 'stash', 'create'], { reject: false });\n if (r.exitCode !== 0) return null;\n const sha = r.stdout.trim();\n return sha.length > 0 ? sha : null;\n}\n\n/**\n * Tar the repo's untracked-not-ignored files into `outPath`. Returns the\n * tar size in bytes (0 when there's nothing to tar, so callers can skip\n * the upload). `git stash create` doesn't capture untracked, so the carry-\n * over needs this side channel — matches docker's behavior.\n */\nasync function maybeBuildUntrackedTar(hostRepo: string, outPath: string): Promise<number> {\n const list = await execa(\n 'git',\n ['-C', hostRepo, 'ls-files', '--others', '--exclude-standard', '-z'],\n { reject: false },\n );\n if (list.exitCode !== 0 || list.stdout.length === 0) return 0;\n // Feed NUL-delimited paths to `tar --null -T -` so spaces / quotes /\n // newlines in filenames survive. Use COPYFILE_DISABLE=1 to suppress\n // macOS' AppleDouble `._<name>` sidecars (same hardening as the\n // agent-credential tarballs).\n const tar = await execa(\n 'tar',\n ['-C', hostRepo, '--null', '-T', '-', '-czf', outPath],\n {\n input: list.stdout,\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n reject: false,\n },\n );\n if (tar.exitCode !== 0) return 0;\n try {\n const { stat } = await import('node:fs/promises');\n const s = await stat(outPath);\n return s.size;\n } catch {\n return 0;\n }\n}\n\nasync function readOriginUrl(hostRepo: string): Promise<string | null> {\n const r = await execa('git', ['-C', hostRepo, 'remote', 'get-url', 'origin'], { reject: false });\n if (r.exitCode !== 0) return null;\n const out = (r.stdout ?? '').trim();\n return out.length > 0 ? out : null;\n}\n\ninterface SeedFromTarArgs {\n backend: CloudBackend;\n handle: CloudHandle;\n hostDir: string;\n workspaceDir: string;\n}\n\nasync function seedFromTar(args: SeedFromTarArgs): Promise<void> {\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-tar-'));\n const tarPath = join(stage, 'workspace.tar.gz');\n try {\n await execa('tar', ['-C', args.hostDir, '-czf', tarPath, '.']);\n const remoteTar = '/tmp/agentbox-workspace.tar.gz';\n await args.backend.uploadFile(args.handle, tarPath, remoteTar);\n const SUDO = `if command -v sudo >/dev/null 2>&1; then SUDO='sudo -n'; else SUDO=''; fi`;\n const script = [\n `set -euo pipefail`,\n // Move out of any cwd we might inherit from Daytona's executeCommand\n // before we delete /workspace. The agentbox image bakes WORKDIR\n // /workspace; if the shell's cwd is /workspace when we `rm -rf` it,\n // the next process inherits a stale cwd FD and git-clone's child\n // (index-pack) fails with \"Unable to read current working directory\".\n `cd /tmp`,\n SUDO,\n `$SUDO rm -rf ${quoteShellArgv([args.workspaceDir])}`,\n `$SUDO mkdir -p ${quoteShellArgv([args.workspaceDir])}`,\n `$SUDO chown \"$(id -un):$(id -gn)\" ${quoteShellArgv([args.workspaceDir])}`,\n `tar -C ${quoteShellArgv([args.workspaceDir])} -xzf ${quoteShellArgv([remoteTar])}`,\n `rm -f ${quoteShellArgv([remoteTar])}`,\n ].join('\\n');\n const r = await args.backend.exec(args.handle, bashScript(script));\n if (r.exitCode !== 0) {\n throw new Error(`workspace seed (tar) failed: ${r.stderr || r.stdout}`);\n }\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n}\n","/**\n * `MockCloudBackend` — a fully in-memory implementation of `CloudBackend` for\n * tests and as a reference. New cloud backends (Vercel, Fly.io, …) can use\n * the contract suite in `test/contract.ts` to validate that their backend\n * behaves the way `createCloudProvider` expects, and look at this file as a\n * minimal example.\n *\n * Behavior is intentionally simple — every method records the call (so\n * tests can assert ordering) and resolves with deterministic values. No\n * I/O. The implementation covers every required method on `CloudBackend`\n * plus every optional one, so contract tests can exercise both branches.\n */\n\nimport type {\n CloudBackend,\n CloudExecOptions,\n CloudExecResult,\n CloudFileEntry,\n CloudHandle,\n CloudPreviewUrl,\n CloudProvisionRequest,\n CloudSandboxSummary,\n CloudState,\n} from '@agentbox/core';\n\ninterface SandboxRecord {\n id: string;\n name: string;\n state: CloudState;\n createdAt: string;\n image: string;\n /** Pseudo-file content keyed by remote path. */\n files: Map<string, Uint8Array>;\n}\n\nexport interface MockCloudBackendOptions {\n /** Name reported by `backend.name`. Defaults to `'mock'`. */\n name?: string;\n /** Initial sandboxes pre-loaded into the backend (e.g. for list() tests). */\n preloaded?: Array<{ id: string; name?: string; state?: CloudState; createdAt?: string }>;\n /**\n * Optional hook fired before every method runs. Tests can use this to\n * inject failures (`throw new Error(...)` or a typed Daytona-shaped error\n * to exercise the retry wrapper).\n */\n beforeCall?: (method: string, args: unknown[]) => void | Promise<void>;\n}\n\nexport interface MockCloudBackend extends CloudBackend {\n /** Method names captured in invocation order — useful for assertions. */\n readonly calls: ReadonlyArray<{ method: string; args: unknown[] }>;\n /** Sandboxes currently present in the backend (post any provision/destroy). */\n readonly sandboxes: ReadonlyArray<Readonly<SandboxRecord>>;\n /**\n * Empty the recorded `calls` log. Useful between assertions in a single\n * test: do an action, assert, clear, do another action, assert again\n * without the first batch polluting the filter. Tests previously poked\n * `calls.length = 0`, which trips strict TS on the readonly array.\n */\n clearCalls(): void;\n}\n\n/** Make a fresh mock backend. Always returns a brand-new internal state. */\nexport function makeMockCloudBackend(opts: MockCloudBackendOptions = {}): MockCloudBackend {\n const name = opts.name ?? 'mock';\n const calls: Array<{ method: string; args: unknown[] }> = [];\n const sandboxes = new Map<string, SandboxRecord>();\n const snapshots = new Map<string, { id: string }>();\n\n for (const pre of opts.preloaded ?? []) {\n sandboxes.set(pre.id, {\n id: pre.id,\n name: pre.name ?? pre.id,\n state: pre.state ?? 'running',\n createdAt: pre.createdAt ?? new Date().toISOString(),\n image: 'mock/preloaded',\n files: new Map(),\n });\n }\n\n const record = async (method: string, args: unknown[]): Promise<void> => {\n calls.push({ method, args });\n if (opts.beforeCall) await opts.beforeCall(method, args);\n };\n const requireSandbox = (id: string): SandboxRecord => {\n const sb = sandboxes.get(id);\n if (!sb) throw new Error(`mock backend: sandbox ${id} not found`);\n return sb;\n };\n\n const backend: MockCloudBackend = {\n name,\n get calls() {\n return calls;\n },\n get sandboxes() {\n return Array.from(sandboxes.values());\n },\n clearCalls(): void {\n calls.length = 0;\n },\n\n async provision(req: CloudProvisionRequest): Promise<CloudHandle> {\n await record('provision', [req]);\n const id = `mock-${String(sandboxes.size + 1)}-${req.name}`;\n sandboxes.set(id, {\n id,\n name: req.name,\n state: 'running',\n createdAt: new Date().toISOString(),\n image: req.snapshot ?? req.image,\n files: new Map(),\n });\n return { sandboxId: id };\n },\n\n async get(sandboxId: string): Promise<CloudHandle | null> {\n await record('get', [sandboxId]);\n return sandboxes.has(sandboxId) ? { sandboxId } : null;\n },\n\n async list(): Promise<CloudSandboxSummary[]> {\n await record('list', []);\n return Array.from(sandboxes.values()).map((sb) => ({\n sandboxId: sb.id,\n name: sb.name,\n createdAt: sb.createdAt,\n state: sb.state,\n }));\n },\n\n async start(h: CloudHandle): Promise<void> {\n await record('start', [h]);\n const sb = requireSandbox(h.sandboxId);\n sb.state = 'running';\n },\n async stop(h: CloudHandle): Promise<void> {\n await record('stop', [h]);\n const sb = requireSandbox(h.sandboxId);\n sb.state = 'stopped';\n },\n async pause(h: CloudHandle): Promise<void> {\n await record('pause', [h]);\n const sb = requireSandbox(h.sandboxId);\n sb.state = 'paused';\n },\n async resume(h: CloudHandle): Promise<void> {\n await record('resume', [h]);\n const sb = requireSandbox(h.sandboxId);\n sb.state = 'running';\n },\n async destroy(h: CloudHandle): Promise<void> {\n await record('destroy', [h]);\n sandboxes.delete(h.sandboxId);\n },\n async state(h: CloudHandle): Promise<CloudState> {\n await record('state', [h]);\n const sb = sandboxes.get(h.sandboxId);\n return sb ? sb.state : 'missing';\n },\n\n async exec(\n h: CloudHandle,\n cmd: string,\n opts?: CloudExecOptions,\n ): Promise<CloudExecResult> {\n await record('exec', [h, cmd, opts]);\n requireSandbox(h.sandboxId);\n return { exitCode: 0, stdout: '', stderr: '' };\n },\n\n async uploadFile(h: CloudHandle, localPath: string, remotePath: string): Promise<void> {\n await record('uploadFile', [h, localPath, remotePath]);\n const sb = requireSandbox(h.sandboxId);\n sb.files.set(remotePath, new Uint8Array([0]));\n },\n async downloadFile(h: CloudHandle, remotePath: string, localPath: string): Promise<void> {\n await record('downloadFile', [h, remotePath, localPath]);\n const sb = requireSandbox(h.sandboxId);\n if (!sb.files.has(remotePath)) {\n throw new Error(`mock backend: ${remotePath} not in sandbox ${h.sandboxId}`);\n }\n },\n async listFiles(h: CloudHandle, remoteDir: string): Promise<CloudFileEntry[]> {\n await record('listFiles', [h, remoteDir]);\n const sb = requireSandbox(h.sandboxId);\n const prefix = remoteDir.endsWith('/') ? remoteDir : `${remoteDir}/`;\n const out: CloudFileEntry[] = [];\n for (const p of sb.files.keys()) {\n if (p.startsWith(prefix)) {\n out.push({ name: p.slice(prefix.length), isDir: false });\n }\n }\n return out;\n },\n\n async previewUrl(h: CloudHandle, port: number): Promise<CloudPreviewUrl> {\n await record('previewUrl', [h, port]);\n requireSandbox(h.sandboxId);\n return { url: `https://${String(port)}-${h.sandboxId}.mock.preview`, token: 'mock-token' };\n },\n\n async signedPreviewUrl(\n h: CloudHandle,\n port: number,\n expiresInSeconds: number,\n ): Promise<CloudPreviewUrl> {\n await record('signedPreviewUrl', [h, port, expiresInSeconds]);\n requireSandbox(h.sandboxId);\n return {\n url: `https://${String(port)}-${h.sandboxId}-signed${String(expiresInSeconds)}.mock.preview`,\n };\n },\n\n async attachArgv(h: CloudHandle): Promise<string[]> {\n await record('attachArgv', [h]);\n requireSandbox(h.sandboxId);\n return ['ssh', '-o', 'StrictHostKeyChecking=no', `mock-token@${h.sandboxId}.mock.ssh`];\n },\n\n async revokeAttachToken(h: CloudHandle, argv: string[]): Promise<void> {\n await record('revokeAttachToken', [h, argv]);\n },\n\n async ensureVolume(volumeName: string): Promise<{ volumeId: string }> {\n await record('ensureVolume', [volumeName]);\n return { volumeId: `vol-${volumeName}` };\n },\n\n async createSnapshot(h: CloudHandle, snapshotName: string): Promise<void> {\n await record('createSnapshot', [h, snapshotName]);\n requireSandbox(h.sandboxId);\n snapshots.set(snapshotName, { id: snapshotName });\n },\n\n async deleteSnapshot(snapshotName: string): Promise<void> {\n await record('deleteSnapshot', [snapshotName]);\n snapshots.delete(snapshotName);\n },\n };\n\n return backend;\n}\n","export {\n CLOUD_WEB_PROXY_PORT,\n CLOUD_WORKSPACE_DIR,\n createCloudProvider,\n emptyCloudStats,\n hostTermForCloud,\n renderInnerCommand,\n type CreateCloudProviderOptions,\n} from './cloud-provider.js';\nexport { kickCloudBootstrap, type KickCloudBootstrapArgs } from './bootstrap-launch.js';\nexport {\n seedCloudWorkspace,\n type SeedCloudWorkspaceArgs,\n type SeedCloudWorkspaceResult,\n} from './sync/workspace-seed.js';\nexport {\n agentSpecsForCloud,\n ensureAgentHomeDirsOwned,\n ensureAgentVolumesForCloud,\n extractCloudAgentCredentials,\n seedAgentVolumesIfFresh,\n seedOpencodeModelState,\n type CloudAgentKind,\n type EnsureAgentVolumesResult,\n type SeedAgentVolumesOptions,\n} from './sync/agent-credentials.js';\nexport { uploadEnvFiles, type UploadEnvFilesArgs, type UploadEnvFilesResult } from './sync/env-files.js';\nexport { createCloudSyncTransport, type CloudSyncTransportInit } from './sync/sync-transport.js';\nexport { makeCloudSync, type CloudSyncOptions } from './sync/cloud-sync.js';\nexport { seedDynamicConfig, type SeedDynamicConfigOptions } from './sync/dynamic-sync.js';\nexport {\n seedClaudeJsonAtCreate,\n type SeedClaudeJsonOptions,\n} from './sync/claude-json-overlay.js';\nexport { seedGitIdentity, type SeedGitIdentityOptions } from './sync/git-identity.js';\nexport { bashScript, quoteShellArg, quoteShellArgv } from './shell.js';\nexport {\n makeMockCloudBackend,\n type MockCloudBackend,\n type MockCloudBackendOptions,\n} from './mock-backend.js';\nexport {\n downloadFromCloudBox,\n pullCloudDirContents,\n uploadToCloudBox,\n type CloudCpResult,\n} from './cloud-cp.js';\nexport {\n CLOUD_CHECKPOINTS_ROOT,\n CLOUD_SNAPSHOT_NAME_PREFIX,\n baseFreshnessFromFingerprints,\n cloudSnapshotName,\n currentCloudBaseFingerprint,\n listAllCloudCheckpoints,\n listCloudBackendDirs,\n listCloudCheckpoints,\n probeCloudCheckpoint,\n removeCloudCheckpointDir,\n resolveCloudCheckpoint,\n writeCloudCheckpointManifest,\n type BaseStatus,\n type CloudCheckpointInfo,\n type CloudCheckpointManifest,\n type CloudCheckpointProjectGroup,\n type WriteCloudManifestFields,\n} from './checkpoint.js';\n// Re-export host-side agent-config staging from sandbox-docker so cloud\n// providers (sandbox-daytona, future cloud backends) can use them without\n// taking a direct sandbox-docker dep (which would bend the provider-isolation\n// rule). The implementations live in sandbox-docker for historical reasons:\n// they were originally built for the docker rsync-into-volume flow and stayed\n// there when the cloud path adopted them.\nexport {\n stageClaudeStaticForUpload,\n stageClaudeJsonOnlyForUpload,\n stageClaudeCredentialsForUpload,\n stageCodexStaticForUpload,\n stageCodexCredentialsForUpload,\n stageAgentsStaticForUpload,\n stageOpencodeStaticForUpload,\n stageOpencodeCredentialsForUpload,\n type StageClaudeOptions,\n type StageCodexOptions,\n type StageOpencodeOptions,\n type StageResult,\n} from '@agentbox/sandbox-core';\nexport {\n CREDENTIALS_BACKUP_FILE,\n CODEX_CREDENTIALS_BACKUP_FILE,\n OPENCODE_CREDENTIALS_BACKUP_FILE,\n isRealAgentCredential,\n type CredentialAgentKind,\n} from '@agentbox/sandbox-docker';\n// Portless helpers — same re-export pattern as the stage* helpers above.\n// Lives in sandbox-docker for historical reasons (the file predates the\n// hetzner provider), surfaced here so non-docker providers (sandbox-hetzner,\n// any future SSH-tunneled backend) don't need a direct sandbox-docker dep.\n// Phase 1 of the hetzner provider work: `portlessBrowserEnv` now takes a\n// `{ mapTarget }` option so the in-box Chromium remap targets the right host\n// gateway per provider (`host.docker.internal` for docker, `127.0.0.1` for\n// hetzner where the box is the VPS).\nexport {\n detectPortless,\n installPortless,\n portlessAlias,\n portlessBrowserEnv,\n portlessGetUrl,\n portlessInstallHint,\n portlessStartHint,\n portlessDoctorRow,\n portlessUnalias,\n resetPortlessCache,\n resolvePortlessHostStateDir,\n startPortlessProxy,\n PORTLESS_PROXY_PORT,\n type PortlessBrowserEnvOptions,\n type PortlessState,\n} from '@agentbox/sandbox-docker';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,wBAAwB,CAAC,GAAG,OAAO,uBAAuB,QAAQ,EAAE,EAAE,KAAK,IAAI;AACxF;AAEA,SAAS,mBAAmB,MAA0B;AACpD,UAAQ,MAAM;IACZ,KAAK;AACH,aAAO;IACT,KAAK;AACH,aAAO;IACT,KAAK;AACH,aAAO;EACX;AACF;AAEA,SAAS,eAAe,MAAkB,MAAmC;AAC3E,UAAQ,MAAM;IACZ,KAAK;AACH,aAAO;IACT,KAAK;AAGH,aAAO;IACT,KAAK,QAAQ;AACX,UAAI,CAAC,MAAM,SAAS;AAClB,eAAO;MACT;AAIA,YAAM,OAAO,KAAK,SAAS,SAAY,OAAO,KAAK,IAAI,IAAI;AAC3D,YAAM,OAAO,CAAC,UAAU,YAAY,IAAI,CAAC,EAAE;AAC3C,UAAI,KAAK,WAAW,MAAO,MAAK,KAAK,UAAU;AAC/C,aAAO,oCAAoC,YAAY,KAAK,OAAO,CAAC,IAAI,KAAK,KAAK,GAAG,CAAC;IACxF;EACF;AACF;AAGA,SAAS,YAAY,GAAmB;AACtC,SAAO,MAAM,EAAE,QAAQ,MAAM,OAAO,IAAI;AAC1C;","names":["basename","mkdtemp","rm","tmpdir","join","execa","mkdtemp","rm","writeFile","tmpdir","join","execa","mkdtemp","rm","tmpdir","join","execa","rm","writeFile","join","readFile","join","execa","mkdtemp","rm","tmpdir","mkdir","dirname","fetch","mkdtemp","join","tmpdir","execa","rm","statSync","writeFile","REMOTE_TAR","readFile","BOX_HOME","SHA_RE","mkdir","dirname","stat","basename","makeSyncContext","opts","detectGitRepos"]}
|