@madarco/agentbox 0.23.1 → 0.23.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/{_cloud-attach-HGP3MQEG.js → _cloud-attach-BQRWX3J2.js} +4 -4
  3. package/dist/{chunk-QVWGQJV6.js → chunk-GGRZ3GZO.js} +2 -2
  4. package/dist/{chunk-L5SOSNQI.js → chunk-I6ZRWTPR.js} +26 -4
  5. package/dist/chunk-I6ZRWTPR.js.map +1 -0
  6. package/dist/{chunk-QGL734YX.js → chunk-LA4JMS27.js} +11 -3
  7. package/dist/{chunk-QGL734YX.js.map → chunk-LA4JMS27.js.map} +1 -1
  8. package/dist/{chunk-CKC3CP7Y.js → chunk-LK2JT2OO.js} +19 -7
  9. package/dist/{chunk-CKC3CP7Y.js.map → chunk-LK2JT2OO.js.map} +1 -1
  10. package/dist/{chunk-Q626V2YX.js → chunk-LSQXT5WZ.js} +2 -2
  11. package/dist/{chunk-4AV2L2KY.js → chunk-QEQFZLYR.js} +8 -8
  12. package/dist/{chunk-ERMU7RMK.js → chunk-SFA57TGX.js} +4 -4
  13. package/dist/{chunk-JXDSSSXS.js → chunk-W3FQPFP7.js} +3 -3
  14. package/dist/{dist-Z3GSHEFO.js → dist-CUKBKS3N.js} +5 -5
  15. package/dist/{dist-X3O3HEYD.js → dist-FXQFTT75.js} +5 -5
  16. package/dist/{dist-W5476E2U.js → dist-QO4CTLAX.js} +5 -5
  17. package/dist/{dist-GEHCZJCS.js → dist-V235KVEX.js} +5 -5
  18. package/dist/{dist-JFUUDAI3.js → dist-Z2NEVV55.js} +5 -3
  19. package/dist/index.js +22 -39
  20. package/dist/index.js.map +1 -1
  21. package/dist/{prepared-state-LW2PKTEQ-5YMKG7UN.js → prepared-state-BUO75YLZ-CDTISC2C.js} +2 -2
  22. package/package.json +1 -1
  23. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  24. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  25. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +1 -1
  26. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  27. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  28. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  29. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  30. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  31. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  32. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  33. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +1 -1
  34. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bqbkd5._.js +2 -2
  35. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qa4a0v._.js +2 -2
  36. package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_boxes_[id]_page_tsx_1-j_972._.js +1 -1
  37. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  38. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  39. package/runtime/hub/apps/hub/.next/static/chunks/{1py5tlz57h7ra.js → 44o5lj23__y1m.js} +1 -1
  40. package/runtime/hub/apps/hub/{chunk-JQFB2CNA.js → chunk-2Z74R6ZT.js} +10 -2
  41. package/runtime/hub/apps/hub/{chunk-6HD4PARX.js → chunk-AR7CEZ2G.js} +25 -3
  42. package/runtime/hub/apps/hub/{chunk-K6RA5GJI.js → chunk-H22XP3NY.js} +18 -6
  43. package/runtime/hub/apps/hub/{dist-OUNL2TCW.js → dist-LNHEG5P4.js} +3 -3
  44. package/runtime/hub/apps/hub/{dist-7GNKBKFV.js → dist-LZNRLUYY.js} +3 -3
  45. package/runtime/hub/apps/hub/{dist-JWVTVHBT.js → dist-Q6G66Z57.js} +3 -3
  46. package/runtime/hub/apps/hub/{dist-L2MMBH7P.js → dist-SD4G36EP.js} +3 -3
  47. package/runtime/hub/apps/hub/{dist-3HR4RIPE.js → dist-VV6Z2CQX.js} +4 -2
  48. package/runtime/hub/apps/hub/{prepared-state-LW2PKTEQ-7BCXARGA.js → prepared-state-BUO75YLZ-CAXQS5Y3.js} +1 -1
  49. package/runtime/hub/apps/hub/server.js +23 -10
  50. package/dist/chunk-L5SOSNQI.js.map +0 -1
  51. /package/dist/{_cloud-attach-HGP3MQEG.js.map → _cloud-attach-BQRWX3J2.js.map} +0 -0
  52. /package/dist/{chunk-QVWGQJV6.js.map → chunk-GGRZ3GZO.js.map} +0 -0
  53. /package/dist/{chunk-Q626V2YX.js.map → chunk-LSQXT5WZ.js.map} +0 -0
  54. /package/dist/{chunk-4AV2L2KY.js.map → chunk-QEQFZLYR.js.map} +0 -0
  55. /package/dist/{chunk-ERMU7RMK.js.map → chunk-SFA57TGX.js.map} +0 -0
  56. /package/dist/{chunk-JXDSSSXS.js.map → chunk-W3FQPFP7.js.map} +0 -0
  57. /package/dist/{dist-JFUUDAI3.js.map → dist-CUKBKS3N.js.map} +0 -0
  58. /package/dist/{dist-X3O3HEYD.js.map → dist-FXQFTT75.js.map} +0 -0
  59. /package/dist/{dist-W5476E2U.js.map → dist-QO4CTLAX.js.map} +0 -0
  60. /package/dist/{dist-GEHCZJCS.js.map → dist-V235KVEX.js.map} +0 -0
  61. /package/dist/{dist-Z3GSHEFO.js.map → dist-Z2NEVV55.js.map} +0 -0
  62. /package/dist/{prepared-state-LW2PKTEQ-5YMKG7UN.js.map → prepared-state-BUO75YLZ-CDTISC2C.js.map} +0 -0
  63. /package/runtime/hub/apps/hub/.next/static/{mcWRLSGubwKk9p3RFz2-Q → 12hWAUQ9O9G3VS4vxKuav}/_buildManifest.js +0 -0
  64. /package/runtime/hub/apps/hub/.next/static/{mcWRLSGubwKk9p3RFz2-Q → 12hWAUQ9O9G3VS4vxKuav}/_clientMiddlewareManifest.js +0 -0
  65. /package/runtime/hub/apps/hub/.next/static/{mcWRLSGubwKk9p3RFz2-Q → 12hWAUQ9O9G3VS4vxKuav}/_ssgManifest.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../packages/core/src/agent.ts","../../../packages/core/src/box-record.ts","../../../packages/core/src/replace.ts","../../../packages/core/src/errors.ts","../../../packages/core/src/identity.ts","../../../packages/core/src/sync/agent-kind.ts","../../../packages/core/src/sync/provider-sync.ts","../../../packages/core/src/sync/topology.ts","../../../packages/core/src/sync/files.ts","../../../packages/core/src/sync/containment.ts","../../../packages/core/src/sync/git-refs.ts","../../../packages/sandbox-core/src/state.ts","../../../packages/sandbox-core/src/git-detect.ts","../../../packages/sandbox-core/src/host-open.ts","../../../packages/sandbox-core/src/ssh-config.ts","../../../packages/sandbox-core/src/claude-app-config.ts","../../../packages/sandbox-core/src/cloud-ssh.ts","../../../packages/sandbox-core/src/ssh-key.ts","../../../packages/sandbox-core/src/box-git.ts","../../../packages/sandbox-core/src/doctor.ts","../../../packages/sandbox-core/src/secrets.ts","../../../packages/sandbox-core/src/plugin-registry.ts","../../../packages/sandbox-core/src/carry-render.ts","../../../packages/sandbox-core/src/sync/recording-transport.ts","../../../packages/sandbox-core/src/sync/registry.ts","../../../packages/sandbox-core/src/sync/context.ts","../../../packages/sandbox-core/src/sync/concerns/env.ts","../../../packages/sandbox-core/src/sync/concerns/files.ts","../../../packages/sandbox-core/src/sync/agents/claude/paths.ts","../../../packages/sandbox-core/src/sync/host-links.ts","../../../packages/sandbox-core/src/sync/concerns/skills.ts","../../../packages/sandbox-core/src/sync/concerns/credentials.ts","../../../packages/sandbox-core/src/sync/concerns/git.ts","../../../packages/sandbox-core/src/sync/concerns/dynamic.ts","../../../packages/sandbox-core/src/sync/host-stage.ts","../../../packages/sandbox-core/src/sync/claude-hooks-filter.ts","../../../packages/sandbox-core/src/sync/codex-config.ts","../../../packages/sandbox-core/src/prepared-state.ts","../../../packages/sandbox-docker/src/prepared-state.ts","../../../packages/sandbox-docker/src/image.ts"],"sourcesContent":["import type { AgentKind } from './types.js';\n\nexport interface AgentLauncher {\n readonly kind: AgentKind;\n buildArgs(initialMessage: string, userArgs: string[]): string[];\n}\n\nconst claudeCodeLauncher: AgentLauncher = {\n kind: 'claude-code',\n // claude treats its first positional argument as the seed user turn in\n // interactive mode (`claude \"<message>\"`), so we slot the initial message\n // ahead of any user-passed flags.\n buildArgs(initialMessage, userArgs) {\n if (!initialMessage) return [...userArgs];\n return [initialMessage, ...userArgs];\n },\n};\n\n// codex accepts a leading positional as the seed prompt — `codex \"<message>\"`\n// drops the user into the TUI with that turn pre-submitted. Same shape as\n// claude, so the launcher is structurally identical.\nconst codexLauncher: AgentLauncher = {\n kind: 'codex',\n buildArgs(initialMessage, userArgs) {\n if (!initialMessage) return [...userArgs];\n return [initialMessage, ...userArgs];\n },\n};\n\n// opencode also accepts a leading positional as the seed prompt — `opencode\n// \"<message>\"` enters the TUI with that turn pre-submitted. Mirrors claude/codex.\nconst opencodeLauncher: AgentLauncher = {\n kind: 'opencode',\n buildArgs(initialMessage, userArgs) {\n if (!initialMessage) return [...userArgs];\n return [initialMessage, ...userArgs];\n },\n};\n\nexport function resolveAgentLauncher(kind: AgentKind): AgentLauncher {\n if (kind === 'claude-code') return claudeCodeLauncher;\n if (kind === 'codex') return codexLauncher;\n if (kind === 'opencode') return opencodeLauncher;\n throw new Error(`unknown agent kind: ${String(kind)}`);\n}\n","/**\n * The per-box state record persisted to `~/.agentbox/state.json`. Shared by\n * every provider: a box may be a local Docker container or a remote cloud\n * sandbox. The `provider` discriminator says which; provider-specific fields\n * live flat (Docker, for historical reasons) or under `cloud` (cloud backends).\n */\n\nimport type { BoxRuntimeState } from './provider.js';\nimport type { SyncTopology } from './sync/types.js';\n\n/** Sandbox backend a box runs on. Open-ended so future providers need no core change. */\nexport type ProviderName = 'docker' | 'daytona' | 'hetzner' | (string & {});\n\n/**\n * Docker-backend-specific fields nested under `BoxRecord.docker` once 7.1\n * lands fully. Today every Docker box also keeps the flat copies of these\n * fields on `BoxRecord` directly for back-compat (state.json migration is\n * the rest of 7.1) — write sites populate both shapes; read sites still\n * use the flat fields. New code should target this interface so the\n * eventual flat-field removal is a search-and-replace, not a redesign.\n */\nexport interface DockerBoxFields {\n /** Docker container name (`agentbox-<id|name>`). */\n container: string;\n /** Base image / checkpoint image tag the container was started from. */\n image: string;\n /** Per-box scratch dir with the `cp -c` APFS clone (when --host-snapshot is on). */\n snapshotDir?: string | null;\n /** Host-side path to the agentbox-ctl unix socket bind-mounted into the container. */\n socketPath?: string;\n /** Docker volume mounted at /home/vscode/.claude inside the box. */\n claudeConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.codex inside the box. */\n codexConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.agents inside the box (Agent Skills). */\n agentsConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.local/share/opencode. */\n opencodeConfigVolume?: string;\n /** Per-box volume holding `.vscode-server`. */\n vscodeServerVolume?: string;\n /** Per-box volume holding `.cursor-server`. */\n cursorServerVolume?: string;\n /** Host port mapped to the noVNC web server. */\n vncHostPort?: number;\n /** Host port mapped to container :80. */\n webHostPort?: number;\n /** Portless route name registered for this box's web port. */\n portlessAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box. */\n portlessUrl?: string;\n /** Portless route name registered for this box's noVNC port (`vnc-<box-name>`). */\n portlessVncAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box's VNC. */\n portlessVncUrl?: string;\n /** Volume mounted at /var/lib/docker for the in-box dockerd. */\n dockerVolume?: string;\n /** True when this box's `dockerVolume` is the shared cache. */\n dockerCacheShared?: boolean;\n /** Checkpoint image tag this box was started from. */\n checkpointImage?: string;\n}\n\n/**\n * Cloud-backend-specific fields for a box. Populated only when\n * `BoxRecord.provider` is a cloud provider; `undefined` for Docker boxes.\n */\nexport interface CloudBoxFields {\n /** Cloud backend name, e.g. 'daytona'. Mirrors `BoxRecord.provider`. */\n backend: string;\n /** Provider-native sandbox id (the handle the backend SDK resolves). */\n sandboxId: string;\n /** Resolved base image / snapshot ref the sandbox was provisioned from. */\n image?: string;\n /**\n * In-box port the web service is exposed on (the supervisor's WebProxy\n * listen port). Cloud boxes bind a non-privileged port; Docker boxes use 80.\n */\n webPort?: number;\n /**\n * Token-authed preview URLs keyed by in-box port. Resolved at create and\n * refreshed on every start (preview tokens can rotate across stop/start).\n */\n previewUrls?: Record<number, string>;\n /**\n * Preview URL of the in-sandbox relay's `/bridge/*` surface — the channel the\n * host CloudBoxPoller drains. Refreshed on start alongside `previewUrls`.\n */\n relayPreviewUrl?: string;\n /**\n * Daytona-style preview-proxy token for `relayPreviewUrl` (sent as\n * `x-daytona-preview-token` header). Persisted so a relay restart can\n * rehydrate the poller without re-resolving from the SDK.\n */\n relayPreviewToken?: string;\n /**\n * Bearer secret authenticating the host poller to the in-sandbox relay's\n * `/bridge/*` routes. Distinct from `BoxRecord.relayToken` (the per-box token\n * the in-box agent sees) so a compromised agent cannot impersonate the host.\n */\n bridgeToken?: string;\n /**\n * User-facing checkpoint name this box was provisioned from (e.g. `setup`),\n * when `agentbox create --checkpoint <name>` resolved to a cloud snapshot.\n * Surfaces in `agentbox status --inspect` so the user can tell which\n * checkpoint a box is currently running.\n */\n snapshotRef?: string;\n /**\n * Last lifecycle state agentbox itself drove this box to (running on\n * create/start/resume, paused on pause/stop/vercel-checkpoint). `listBoxes`\n * shows this for cloud boxes so `agentbox list` stays instant — no SDK probe.\n * It reflects the last *host-initiated* op, not the authoritative live state\n * (a platform-side stop won't update it); `agentbox list --live` probes for\n * the real state. Absent on pre-feature records → treated as `running`.\n */\n lastState?: BoxRuntimeState;\n /**\n * Effective per-session timeout (ms) the sandbox was created with, when the\n * backend models one (vercel `Sandbox.create({ timeout })`). Recorded so the\n * host keepalive loop can seed its tracked death-time accurately (the\n * effective value can be project/workspace-overridden, not the global\n * default). Absent on backends without a session timeout / pre-feature records.\n */\n sessionTimeoutMs?: number;\n /**\n * True when this box's `/workspace` was seeded from the host checkout (the\n * laptop `create` path), i.e. it has a real fork base shared with the host.\n * Left unset for `inBoxClone` / plane boxes (they clone in-box from a leased\n * URL with no host fork base). Gates the session-start live-box resync — only\n * host-seeded boxes can merge the host's current state back in (Phase 7.5).\n */\n hostSeeded?: boolean;\n /**\n * The box's per-box branch (`agentbox/<name>`, or `--use-branch <b>`). The\n * merge target branch for the live-box resync; re-derived layout aside, this\n * is the one piece resync can't recover from the box alone.\n */\n workspaceBranch?: string;\n /**\n * Last branch the HOST sanctioned for this cloud box (defaults to\n * `workspaceBranch`, updated by host `agentbox git checkout`/`branch`/`pull\n * <branch>`). The cloud push gate auto-approves a push only to a scratch\n * branch OR this value — the cloud analogue of the docker registry's\n * `BoxWorktree.sanctionedBranch`. Absent → treated as `workspaceBranch`.\n */\n sanctionedBranch?: string;\n /**\n * The box's resolved sync federation shape (`resolveSyncTopology`). `'cloud'`\n * for a classic host-synced box, `'control-plane'` when its live relay is a\n * hosted control plane (the box forwards `/rpc` to the plane and leases push\n * tokens directly). Persisted so the value is stable across resumes.\n */\n topology?: SyncTopology;\n /**\n * The hosted control-plane base URL this box points at, when\n * `topology === 'control-plane'`. Persisted (not re-derived from config) so a\n * resume re-kick on a host whose config has changed/lacks the URL still\n * re-threads the box's forwarder upstream + `AGENTBOX_GIT_LEASE` correctly.\n */\n controlPlaneUrl?: string;\n /**\n * Git push routing (`git.pushMode`): `'auto' | 'relay' | 'lease'`. Persisted\n * (not re-derived from config) so a resume re-kick re-threads `AGENTBOX_GIT_LEASE`\n * correctly even if the host config changed. Mirrors config's `GitPushMode`.\n */\n gitPushMode?: 'auto' | 'relay' | 'lease';\n}\n\n/**\n * Last resolved SSH connection target for a box — host/user, the per-box\n * identity file (identity-authed providers: docker localhost sshd, Hetzner),\n * and an optional port (docker publishes its sshd on an ephemeral loopback\n * port; cloud providers use the default 22). Persisted on `BoxRecord.ssh`\n * whenever we're already online (create/start/code/open/shell) so\n * `~/.agentbox/ssh/config` can be regenerated purely from state — the\n * regenerate never hits a provider API or wakes a paused box. The host IP /\n * loopback port can change across stop/start, so it is refreshed on start/resume.\n * Absent for providers with no SSH.\n */\nexport interface SshTargetRecord {\n host: string;\n user: string;\n identityFile?: string;\n port?: number;\n}\n\nexport interface GitWorktreeRecord {\n kind: 'root' | 'nested';\n /** Host path to the main repo whose `.git/` is the source of the worktree. */\n hostMainRepo: string;\n /**\n * Agent-visible container path of the worktree (`/workspace` for root,\n * `/workspace/<sub>` for nested).\n */\n containerPath: string;\n /**\n * Per-box unique path where git registered the worktree. Docker boxes\n * register against the bind-mounted host `.git/`; cloud boxes clone into the\n * sandbox so this is a sandbox-local path. `destroyBox` uses it to deregister\n * a Docker worktree on the host.\n */\n gitWorktreePath: string;\n /** Branch the worktree was created on, e.g. `agentbox/<box-name>`. */\n branch: string;\n /**\n * The last branch the HOST put this box on — its create-time `branch`,\n * updated by host-driven `agentbox git checkout`/`branch`/`pull <branch>`.\n * Distinct from `branch` (which stays the immutable scratch identity used by\n * host-only land, checkout guards, and upstream-sync skip): the relay\n * auto-approves a push only to a scratch branch OR this sanctioned branch,\n * so an in-box agent self-switching to `main` and pushing still prompts.\n * Absent on records written before this field existed → treated as `branch`.\n */\n sanctionedBranch?: string;\n /** Workspace-relative path the repo was found at (empty string for root). */\n relPathFromWorkspace: string;\n}\n\nexport interface BoxRecord {\n id: string;\n name: string;\n /**\n * Cosmetic user-chosen label, set via `agentbox status <box> --set-name`.\n * Purely for display and lookup — unlike `name` it does NOT drive the\n * container, git branch, or Portless URL. Absent means \"fall back to name\".\n * See docs/state.md.\n */\n displayName?: string;\n /**\n * Sandbox backend the box runs on. Absent on records written before the\n * multi-provider split — `readState` migrates those to `'docker'` on read.\n */\n provider?: ProviderName;\n /**\n * Unique runtime identifier. For docker records: the container name\n * (`agentbox-<id|name>`) — what `docker exec` resolves. For cloud\n * records: the backend sandbox id, prefixed with `cloud:` so a grep\n * for \"agentbox-cloud-*\" finds nothing (post 7.2) — the cloud\n * sandbox is not a docker container and shouldn't look like one.\n * Docker-internal code should only ever reach this via\n * `requireDockerProvider(box, ...)` first.\n */\n container: string;\n /**\n * The image the box was started from. Docker: base image or checkpoint\n * image tag. Cloud: the resolved sandbox image / snapshot ref (mirrors\n * `box.cloud.image`).\n */\n image: string;\n workspacePath: string;\n /**\n * Optional per-box scratch dir holding a `cp -c` APFS clone of the host\n * workspace, made at create time when `--host-snapshot` is on. Docker only.\n */\n snapshotDir?: string | null;\n /**\n * Host-side path to the agentbox-ctl unix socket bind-mounted into the\n * container at /run/agentbox/ctl.sock. Docker only.\n */\n socketPath?: string;\n /** Docker volume mounted at /home/vscode/.claude inside the box. Docker only. */\n claudeConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.codex inside the box. Docker only. */\n codexConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.agents inside the box (Agent Skills). Docker only. */\n agentsConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.local/share/opencode. Docker only. */\n opencodeConfigVolume?: string;\n /** Per-box volume holding `.vscode-server`. Docker only. */\n vscodeServerVolume?: string;\n /** Per-box volume holding `.cursor-server`. Docker only. */\n cursorServerVolume?: string;\n /**\n * Bearer token the in-box supervisor uses to authenticate with the relay.\n * Generated at create time and forwarded as AGENTBOX_RELAY_TOKEN.\n */\n relayToken?: string;\n /** Per-box git worktrees. Empty/absent when the host workspace is not a git checkout. */\n gitWorktrees?: GitWorktreeRecord[];\n /** True when the box was created with --with-playwright. */\n withPlaywright?: boolean;\n /** True when the box was created with --with-env. */\n withEnv?: boolean;\n /**\n * Resolved `box.autoApproveHostActions` at create time. Forwarded to the\n * host relay so host-action confirms (git push, cp, gh writes, checkpoint)\n * auto-resolve to `y` for this box — with an audit event per bypass.\n * Persisted so a `relay` rehydrate re-registers with the same policy.\n */\n autoApproveHostActions?: boolean;\n /**\n * Resolved `box.autoApproveSafeHostActions` at create time (default true).\n * Forwarded to the relay so the SAFE subset of host actions (open PR, PR\n * comments, sanctioned-branch push, contained non-secret file copy, CI\n * rerun, checkpoint, integration writes) auto-resolves without a prompt.\n * Absent is treated as enabled (default on) by the relay. Persisted so a\n * `relay` rehydrate re-registers with the same policy.\n */\n autoApproveSafeHostActions?: boolean;\n /**\n * Carry summary recorded at create time: which host paths were copied into\n * the box from `agentbox.yaml`'s `carry:` block. Audit trail for inspect\n * (the actual file content is not retained — only the src/dest pairs and\n * sizes). Absent when no carry: block was applied.\n */\n carry?: {\n count: number;\n /**\n * `hash` is a content hash of the host source at copy time, used by the\n * on-start resync to re-copy only entries whose host source changed.\n * Absent on records written before resync existed (treated as \"changed\").\n */\n entries: Array<{ src: string; dest: string; bytes: number; hash?: string }>;\n };\n /** VNC stack (Xvnc + websockify + noVNC) is enabled for this box. */\n vncEnabled?: boolean;\n /** Container-side noVNC web port. */\n vncContainerPort?: number;\n /** Host port mapped to the noVNC web server (Docker), or preview port (cloud). */\n vncHostPort?: number;\n /** Per-box password baked into Xvnc's PasswordFile and the auto-connect URL. */\n vncPassword?: string;\n /** Container port reserved for the web service `expose:` forward. */\n webContainerPort?: number;\n /** Host port mapped to container :80 (Docker). */\n webHostPort?: number;\n /** In-box localhost sshd is enabled for this box (Docker). */\n sshEnabled?: boolean;\n /** Container-side sshd port (22). Docker. */\n sshContainerPort?: number;\n /** Ephemeral loopback host port mapped to the container's sshd (Docker). */\n sshHostPort?: number;\n /**\n * Last resolved SSH connection target. Regenerated into `~/.agentbox/ssh/config`\n * by `syncAgentboxSshConfig`. Docker: `127.0.0.1` + the per-box key + the\n * ephemeral `sshHostPort`; cloud (Hetzner): the VPS IP + per-box key.\n */\n ssh?: SshTargetRecord;\n /** Portless route name registered for this box's web port. Docker only. */\n portlessAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box. Docker only. */\n portlessUrl?: string;\n /** Portless route name registered for this box's noVNC port (`vnc-<box-name>`). */\n portlessVncAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box's VNC. */\n portlessVncUrl?: string;\n /** Volume mounted at /var/lib/docker for the in-box dockerd. Docker only. */\n dockerVolume?: string;\n /** True when this box's `dockerVolume` is the shared cache. Docker only. */\n dockerCacheShared?: boolean;\n /** Absolute host path of the project this box belongs to. */\n projectRoot?: string;\n /** Monotonic 1-based index within `projectRoot`. Never recycled. */\n projectIndex?: number;\n /** The checkpoint image tag this box was started from. Docker only. */\n checkpointImage?: string;\n /** Lineage of the checkpoint this box was started from. */\n checkpointSource?: {\n ref: string;\n type: 'layered' | 'flattened';\n /** Checkpoint refs composing the chain, base-most last. */\n chain: string[];\n };\n /** Resource ceilings actually applied at create. */\n resourceLimits?: {\n memoryBytes?: number;\n cpus?: number;\n pidsLimit?: number;\n disk?: string;\n };\n /**\n * Docker-backend-specific fields. Populated alongside the flat fields\n * during the 7.1 transition; once readers migrate, the flat fields go\n * away. New code SHOULD prefer `box.docker?.<field>` and fall back to\n * the flat field via the `dockerField()` helper in `@agentbox/core`.\n */\n docker?: DockerBoxFields;\n /** Cloud-backend-specific fields. Present only for cloud providers. */\n cloud?: CloudBoxFields;\n /**\n * The agent last launched in this box (`agentbox claude` / `codex` /\n * `opencode`). Recorded on every launch (foreground + queued). Durable, unlike\n * the in-box session pointers which are cleared on the running->stopped tmux\n * edge — so it's the signal `agentbox recover` uses to know which agent to\n * relaunch/attach, and the only such signal for an adopted box with no live\n * session.\n */\n lastAgent?: 'claude' | 'codex' | 'opencode';\n createdAt: string; // ISO-8601\n}\n\n/**\n * Read a Docker-specific field with fallback to the legacy flat slot.\n * Prefer this over `box.field` directly while the 7.1 migration is in\n * flight — once the flat fields are removed, this collapses to\n * `box.docker?.[key]` and the migration is mechanical.\n */\nexport function dockerField<K extends keyof DockerBoxFields>(\n box: BoxRecord,\n key: K,\n): DockerBoxFields[K] | undefined {\n if (box.docker && box.docker[key] !== undefined) return box.docker[key];\n // Fall back to the flat copy. Container / image are required at the\n // BoxRecord top level so they always exist as flat fields today.\n return (box as unknown as Record<string, unknown>)[key as string] as\n | DockerBoxFields[K]\n | undefined;\n}\n\nexport interface StateFile {\n version: 1;\n boxes: BoxRecord[];\n}\n\nexport type FindBoxResult =\n | { kind: 'ok'; box: BoxRecord }\n | { kind: 'none' }\n | { kind: 'ambiguous'; matches: BoxRecord[] };\n","/**\n * Provider-neutral text-replacement engine. Pure (no fs / no yaml) so it can be\n * shared by the host carry path (`renderCarryEntries`) and the in-box\n * `agentbox-ctl render` CLI without a dependency cycle. The yaml/fs loaders that\n * read a `replacements:` block live in `@agentbox/ctl` (which has those deps).\n */\n\n/**\n * The fixed set of `{{NAME}}` placeholders that `replaceEnvs` / `--env`\n * substitution recognizes. Deliberately a whitelist (not \"any env var\") so a\n * rendered file is predictable: a stray `{{FOO}}` is left untouched rather than\n * silently clobbered, and secrets/tokens are never substitutable.\n */\nexport const PLACEHOLDER_KEYS = [\n 'AGENTBOX_BOX_NAME',\n 'AGENTBOX_BOX_ID',\n 'AGENTBOX_BOX_KIND',\n 'AGENTBOX_HOST_WORKSPACE',\n 'AGENTBOX_PROJECT_ROOT',\n // Convenience: the host this box is reachable at. Derived from\n // AGENTBOX_BOX_NAME as `<box-name>.localhost` when not set explicitly (the\n // portless host for docker/hetzner). Public-URL cloud providers\n // (vercel/daytona/e2b) set it explicitly at boot to the real preview host\n // (e.g. `<sub>.vercel.run`), which then wins over the derived fallback.\n 'AGENTBOX_BOX_HOST',\n] as const;\n\nexport type PlaceholderKey = (typeof PLACEHOLDER_KEYS)[number];\n\nconst PLACEHOLDER_SET = new Set<string>(PLACEHOLDER_KEYS);\n\n/** A single regex/literal substitution. `to` may itself contain placeholders. */\nexport interface ReplaceRule {\n from: string;\n to: string;\n /** Treat `from` as a JS regex (with `flags`); otherwise a literal string. */\n regex?: boolean;\n /** Regex flags (default `g`). Ignored unless `regex` is true. */\n flags?: string;\n}\n\nexport class ReplaceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ReplaceError';\n }\n}\n\nconst PLACEHOLDER_RE = /\\{\\{\\s*([A-Z0-9_]+)\\s*\\}\\}/g;\n\n/**\n * Replace `{{NAME}}` placeholders whose NAME is in {@link PLACEHOLDER_KEYS}\n * with the matching value from `context`. Unknown names (not whitelisted) are\n * left as-is. Whitelisted names with no value in `context` are also left as-is\n * (and reported via `onWarn`).\n */\nexport function substitutePlaceholders(\n text: string,\n context: Record<string, string>,\n onWarn?: (msg: string) => void,\n): string {\n return text.replace(PLACEHOLDER_RE, (match, name: string) => {\n if (!PLACEHOLDER_SET.has(name)) return match;\n const value = context[name];\n if (value === undefined) {\n onWarn?.(`placeholder {{${name}}} has no value in this context — left untouched`);\n return match;\n }\n return value;\n });\n}\n\nexport interface ApplyReplacementsOptions {\n /** When true, substitute `{{NAME}}` whitelist placeholders across the file. */\n env?: boolean;\n /** Ordered custom rules applied after (or instead of) placeholder env subst. */\n rules?: ReplaceRule[];\n /** Placeholder values (used by both `env` subst and rule `to` strings). */\n context: Record<string, string>;\n onWarn?: (msg: string) => void;\n}\n\n/**\n * Apply env-placeholder substitution and/or custom rules to file content.\n * Rules run in declaration order; each rule's `to` string is itself run through\n * placeholder substitution so `to: '.{{AGENTBOX_BOX_NAME}}.localhost'` works\n * regardless of `env`.\n */\nexport function applyReplacements(content: string, opts: ApplyReplacementsOptions): string {\n let out = content;\n if (opts.env) {\n out = substitutePlaceholders(out, opts.context, opts.onWarn);\n }\n for (const rule of opts.rules ?? []) {\n const to = substitutePlaceholders(rule.to, opts.context, opts.onWarn);\n if (rule.regex) {\n let re: RegExp;\n try {\n re = new RegExp(rule.from, rule.flags ?? 'g');\n } catch (err) {\n throw new ReplaceError(\n `invalid regex \"${rule.from}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n out = out.replace(re, to);\n } else {\n // Literal: split/join so `$`/special chars in either side stay literal.\n out = out.split(rule.from).join(to);\n }\n }\n return out;\n}\n\n/**\n * Fill in `AGENTBOX_BOX_HOST` (the published portless host, `<box-name>.localhost`)\n * from `AGENTBOX_BOX_NAME` when it isn't already set. Single source of truth for\n * the host-derivation rule, shared by every placeholder-context builder. Mutates\n * and returns `ctx`.\n */\nexport function deriveBoxHost(ctx: Record<string, string>): Record<string, string> {\n if (ctx.AGENTBOX_BOX_HOST === undefined && ctx.AGENTBOX_BOX_NAME !== undefined) {\n ctx.AGENTBOX_BOX_HOST = `${ctx.AGENTBOX_BOX_NAME}.localhost`;\n }\n return ctx;\n}\n\n/** Build the whitelist placeholder context from a process environment. */\nexport function placeholderContextFromEnv(\n env: NodeJS.ProcessEnv = process.env,\n): Record<string, string> {\n const ctx: Record<string, string> = {};\n for (const key of PLACEHOLDER_KEYS) {\n const v = env[key];\n if (typeof v === 'string' && v.length > 0) ctx[key] = v;\n }\n return deriveBoxHost(ctx);\n}\n\n// --- rule parsing (shared by config top-level `replacements:` and the CLI) ---\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nconst RULE_KEYS = new Set(['from', 'to', 'regex', 'flags']);\n\n/** Parse one rule mapping (from `replacements:` blocks or carry `replace:`). */\nexport function parseReplaceRule(raw: unknown, where: string): ReplaceRule {\n if (!isPlainObject(raw)) {\n throw new ReplaceError(`${where} must be a mapping with at least { from, to }`);\n }\n for (const key of Object.keys(raw)) {\n if (!RULE_KEYS.has(key)) throw new ReplaceError(`${where} has unknown key \"${key}\"`);\n }\n if (typeof raw.from !== 'string' || raw.from.length === 0) {\n throw new ReplaceError(`${where}.from must be a non-empty string`);\n }\n if (typeof raw.to !== 'string') {\n throw new ReplaceError(`${where}.to must be a string`);\n }\n const rule: ReplaceRule = { from: raw.from, to: raw.to };\n if (raw.regex !== undefined && raw.regex !== null) {\n if (typeof raw.regex !== 'boolean') throw new ReplaceError(`${where}.regex must be a boolean`);\n rule.regex = raw.regex;\n }\n if (raw.flags !== undefined && raw.flags !== null) {\n if (typeof raw.flags !== 'string') throw new ReplaceError(`${where}.flags must be a string`);\n rule.flags = raw.flags;\n }\n if (rule.regex) {\n try {\n new RegExp(rule.from, rule.flags ?? 'g');\n } catch (err) {\n throw new ReplaceError(\n `${where}.from is not a valid regex: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n return rule;\n}\n\n/** Parse a list of rules (carry `replace:` or a `replacements:` named set). */\nexport function parseReplaceRules(raw: unknown, where: string): ReplaceRule[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) throw new ReplaceError(`${where} must be a list of rules`);\n return raw.map((r, i) => parseReplaceRule(r, `${where}[${String(i)}]`));\n}\n\n/** Parse the top-level `replacements:` block: name → rule list. */\nexport function parseReplacements(raw: unknown): Record<string, ReplaceRule[]> {\n if (raw === undefined || raw === null) return {};\n if (!isPlainObject(raw)) {\n throw new ReplaceError('replacements must be a mapping of name → rule list');\n }\n const out: Record<string, ReplaceRule[]> = {};\n for (const [name, rules] of Object.entries(raw)) {\n if (!/^[A-Za-z0-9_-]+$/.test(name)) {\n throw new ReplaceError(`replacements.${name}: name must match [A-Za-z0-9_-]+`);\n }\n out[name] = parseReplaceRules(rules, `replacements.${name}`);\n }\n return out;\n}\n\n/**\n * Resolve a list of named rule-set references against a `replacements:` map,\n * concatenating their rules in reference order. Throws on an unknown name.\n */\nexport function resolveRuleRefs(\n refs: string[],\n replacements: Record<string, ReplaceRule[]>,\n where: string,\n): ReplaceRule[] {\n const out: ReplaceRule[] = [];\n for (const name of refs) {\n const set = replacements[name];\n if (set === undefined) {\n const known = Object.keys(replacements);\n throw new ReplaceError(\n `${where}: unknown replacements rule-set \"${name}\"` +\n (known.length > 0 ? ` (known: ${known.join(', ')})` : ' (none declared)'),\n );\n }\n out.push(...set);\n }\n return out;\n}\n\n/** Parse a CLI `--rule 'from=>to'` argument into a rule. `regex` opt-in. */\nexport function parseRuleArg(arg: string, regex: boolean): ReplaceRule {\n const idx = arg.indexOf('=>');\n if (idx === -1) {\n throw new ReplaceError(`--rule \"${arg}\" must be of the form 'from=>to'`);\n }\n const from = arg.slice(0, idx);\n const to = arg.slice(idx + 2);\n if (from.length === 0) throw new ReplaceError(`--rule \"${arg}\" has an empty 'from'`);\n return parseReplaceRule({ from, to, ...(regex ? { regex: true } : {}) }, `--rule \"${arg}\"`);\n}\n","/**\n * Provider-neutral box-resolution errors. Thrown by the box-ref resolver and\n * caught by the CLI's lifecycle error handler. They carry the query (and, for\n * the ambiguous case, the candidate records) so the CLI can render a useful\n * hint.\n */\n\nimport type { BoxRecord } from './box-record.js';\n\n/**\n * Marker class for expected, actionable failures that the CLI should render\n * to the user as a clean message (no stack trace) — e.g. \"you skipped a\n * required `agentbox prepare` step\". The top-level CLI catch in\n * `apps/cli/src/index.ts` detects this via `instanceof` and falls back to the\n * `name` field so bundling / dual-publish boundaries can't lose the marker.\n */\nexport class UserFacingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'UserFacingError';\n }\n}\n\nexport class BoxNotFoundError extends Error {\n constructor(public readonly query: string) {\n super(`no agentbox matches \"${query}\"`);\n this.name = 'BoxNotFoundError';\n }\n}\n\nexport class AmbiguousBoxError extends Error {\n constructor(\n public readonly query: string,\n public readonly matches: BoxRecord[],\n ) {\n const ids = matches.map((m) => m.id).join(', ');\n super(`\"${query}\" matches multiple boxes: ${ids}`);\n this.name = 'AmbiguousBoxError';\n }\n}\n","import { randomBytes } from 'node:crypto';\n\n/**\n * Stable identity helpers shared across providers. Currently just the per-box\n * id mint; checkpoint ids etc. can join later under their own prefix.\n */\n\n/**\n * Type tag prefixed to every minted box id so the kind is readable at a glance\n * and id namespaces can grow without colliding (reserve `c` for checkpoints,\n * etc.). The leading non-digit is load-bearing: it guarantees a box id is never\n * an all-decimal string, which would otherwise collide with the per-project\n * numeric index in `resolveBoxRef` (`agentbox open 4`) and make all-digit ids\n * unresolvable.\n */\nexport const BOX_ID_PREFIX = 'b';\n\nexport function generateBoxId(): string {\n return `${BOX_ID_PREFIX}${randomBytes(4).toString('hex')}`;\n}\n","/**\n * The single adapter reconciling the two spellings of the Claude agent across\n * the codebase:\n * - `'claude'` — canonical INTERNAL name (sync layer, docker volumes,\n * `BoxRecord.lastAgent`, the CLI `claude` subcommand).\n * - `'claude-code'` — the FROZEN wire/registry name (relay `QueueAgentKind`,\n * persisted queue jobs, the `AgentLauncher` registry).\n *\n * Everything downstream of a boundary uses the canonical `SyncAgentKind`;\n * `toQueueKind` / `toSyncKind` translate only at the boundary. We NEVER rewrite\n * persisted wire/record values — back-compat is read-time normalization\n * (`normalizeLastAgent`), so existing box records and in-flight queue jobs keep\n * working untouched.\n */\n\n/** Canonical internal agent id. */\nexport type SyncAgentKind = 'claude' | 'codex' | 'opencode';\n\n/** The frozen wire/queue spelling (relay `QueueAgentKind`, persisted jobs). */\nexport type QueueAgentKind = 'claude-code' | 'codex' | 'opencode';\n\nexport const SYNC_AGENT_KINDS: readonly SyncAgentKind[] = ['claude', 'codex', 'opencode'];\n\n/** True for a known canonical id. */\nexport function isSyncAgentKind(v: unknown): v is SyncAgentKind {\n return v === 'claude' || v === 'codex' || v === 'opencode';\n}\n\n/**\n * Boundary → internal. Maps the wire spelling `'claude-code'` to `'claude'`;\n * `'codex'`/`'opencode'` pass through. Throws on anything else so a typo can't\n * silently seed the wrong agent.\n */\nexport function toSyncKind(k: string): SyncAgentKind {\n if (k === 'claude-code' || k === 'claude') return 'claude';\n if (k === 'codex') return 'codex';\n if (k === 'opencode') return 'opencode';\n throw new Error(`unknown agent kind: ${k}`);\n}\n\n/** Internal → boundary. Maps `'claude'` to the wire spelling `'claude-code'`. */\nexport function toQueueKind(k: SyncAgentKind): QueueAgentKind {\n return k === 'claude' ? 'claude-code' : k;\n}\n\n/**\n * Read-time back-compat for persisted `BoxRecord.lastAgent`. A record written by\n * any past/forked build that stored `'claude-code'` still resolves to\n * `'claude'`; unknown/absent values return undefined rather than throwing (a\n * stale record must never crash `list`/`recover`).\n */\nexport function normalizeLastAgent(raw: string | undefined | null): SyncAgentKind | undefined {\n if (!raw) return undefined;\n if (raw === 'claude-code' || raw === 'claude') return 'claude';\n if (raw === 'codex') return 'codex';\n if (raw === 'opencode') return 'opencode';\n return undefined;\n}\n","/**\n * `ProviderSync` — the co-located, auditable surface of every shared sync\n * activity a provider performs. One implementation per provider\n * (`makeDockerSync` / `makeCloudSync`), each method a thin delegation to the\n * provider-neutral concern in `@agentbox/sandbox-core`. The two goals this\n * serves — see `docs/sync-architecture.md` §\"Co-location: the ProviderSync\n * facade\":\n *\n * - **Per-provider audit** — one file (`docker-sync.ts` / `cloud-sync.ts`) is\n * the complete list of a provider's sync ops.\n * - **Per-concern cross-provider audit** — `dockerSync.resyncWorkspace` vs\n * `cloudSync.resyncWorkspace` are peer methods under one interface.\n *\n * The handle (docker container / cloud backend+handle) is closed at construction\n * time; every method takes the `SyncContext` plus its own operation args.\n *\n * Granularity is GROUPED: per-tool agent config (static config, skills, dynamic,\n * box-facts) bundles into `seedAgentConfig`; resync / credentials / extract /\n * git-identity / env / carry stay separate peer methods. Workspace *seed* (git\n * worktree create + docker `mount --bind`) is deliberately NOT here — it has no\n * cloud analog (cloud clones), so it stays a provider-specific step called\n * directly by each `create()`. Each facade file's header names that carve-out so\n * the file remains the full picture.\n */\n\nimport type { GitWorktreeRecord } from '../box-record.js';\nimport type { ResolvedCarryEntry, ResyncResult } from '../provider.js';\nimport type { SyncContext } from './context.js';\n\n/** Env var that flips every `ProviderSync` op into a print-only no-op. */\nexport const SYNC_DRYRUN_ENV = 'AGENTBOX_SYNC_DRYRUN';\n\n/**\n * Outcome of applying the approved `carry:` entries into a box. Mirrors the\n * docker `CopyCarryResult` shape (kept identical so `applyCarry` returns it\n * verbatim): the count copied, per-entry errors, and an audit summary for\n * `BoxRecord.carry` (`hash` is the host source content hash at copy time).\n */\nexport interface CarryApplyResult {\n copied: number;\n errors: string[];\n applied: Array<{ src: string; dest: string; bytes: number; hash?: string }>;\n}\n\nexport interface ProviderSync {\n /**\n * Merge the host's checked-out branch into each box worktree's per-box branch\n * and overlay the host's uncommitted/untracked changes, box-wins on conflict.\n * `worktrees` are the box's recorded worktrees (root + nested).\n */\n resyncWorkspace(ctx: SyncContext, worktrees: GitWorktreeRecord[]): Promise<ResyncResult>;\n /**\n * Seed the per-tool agent config (claude/codex/opencode): static config +\n * skills + dynamic (workflows/memory) + box-facts. The method body lists the\n * sub-steps in order so the facade file stays the auditable full picture.\n */\n seedAgentConfig(ctx: SyncContext): Promise<void>;\n /** Seed the host's agent logins (claude/codex/opencode) into the box. */\n seedCredentials(ctx: SyncContext): Promise<void>;\n /** Capture the box's agent logins back to the host backups. Returns updated agents. */\n extractCredentials(ctx: SyncContext): Promise<string[]>;\n /** Seed the host git identity (`~/.gitconfig`) into the box. Docker no-op (bind-mounted). */\n seedGitIdentity(ctx: SyncContext): Promise<void>;\n /** Copy gitignore-bypassing host env files matching `patterns` into /workspace. */\n seedEnvFiles(ctx: SyncContext, patterns: string[]): Promise<{ copied: number }>;\n /** Apply the approved `carry:` entries (host→box file copies) into the box. */\n applyCarry(ctx: SyncContext, entries: ResolvedCarryEntry[]): Promise<CarryApplyResult>;\n}\n\n/**\n * Wrap a `ProviderSync` so each op prints `[sync dry-run] <label>.<op>(…)` via\n * `ctx.onLog` and returns a benign default WITHOUT executing — the readable\n * audit of \"what the facade would do.\" `makeDockerSync`/`makeCloudSync` apply\n * this when {@link SYNC_DRYRUN_ENV} is set. The inner facade is never invoked, so\n * a dry run makes no host/box changes.\n */\nexport function dryRunProviderSync(label: string): ProviderSync {\n const note = (ctx: SyncContext, op: string, detail = ''): void =>\n ctx.onLog(`[sync dry-run] ${label}.${op}(${detail})`);\n return {\n resyncWorkspace(ctx, worktrees) {\n note(ctx, 'resyncWorkspace', `${String(worktrees.length)} worktree(s)`);\n return Promise.resolve({ repos: [], hadConflicts: false });\n },\n seedAgentConfig(ctx) {\n note(ctx, 'seedAgentConfig');\n return Promise.resolve();\n },\n seedCredentials(ctx) {\n note(ctx, 'seedCredentials');\n return Promise.resolve();\n },\n extractCredentials(ctx) {\n note(ctx, 'extractCredentials');\n return Promise.resolve([]);\n },\n seedGitIdentity(ctx) {\n note(ctx, 'seedGitIdentity');\n return Promise.resolve();\n },\n seedEnvFiles(ctx, patterns) {\n note(ctx, 'seedEnvFiles', `${String(patterns.length)} pattern(s)`);\n return Promise.resolve({ copied: 0 });\n },\n applyCarry(ctx, entries) {\n note(ctx, 'applyCarry', `${String(entries.length)} entry/entries`);\n return Promise.resolve({ copied: 0, errors: [], applied: [] });\n },\n };\n}\n","/**\n * Pure resolver for a box's {@link SyncTopology} — the \"resolved ONCE per box\n * (from the provider name + whether a control-plane URL is configured)\" step the\n * `SyncTopology` doc describes. No fs/exec — string logic only — so it's shared\n * by the provider (persists it on the record) and any host/box consumer.\n */\nimport type { SyncTopology } from './types.js';\n\n/**\n * Resolve a box's federation topology from its provider name and whether a\n * hosted control-plane URL is configured for it.\n *\n * - docker → always `'docker'` (bind-mounted `.git`, host relay loopback; never\n * a control-plane target).\n * - any cloud provider + a non-empty control-plane URL → `'control-plane'`\n * (the box's live relay is the plane; git push-back leases a token directly).\n * - any cloud provider without one → `'cloud'` (host-side sync via the backend).\n */\nexport function resolveSyncTopology(providerName: string, controlPlaneUrl?: string): SyncTopology {\n if (providerName === 'docker') return 'docker';\n return controlPlaneUrl && controlPlaneUrl.length > 0 ? 'control-plane' : 'cloud';\n}\n","/**\n * Pure download / file-transfer decisions, co-located here so *all* sync\n * decision logic is discoverable under `core/src/sync/` — even though the two\n * download handlers keep genuinely divergent transports (docker re-shells the\n * host CLI; cloud calls `pullCloudDirContents`, workspace-only). We do NOT\n * force-unify the transport; only these shared, pure decisions live here.\n *\n * No fs/exec beyond `node:path`/`node:os` string helpers.\n */\n\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, resolve } from 'node:path';\n\n/** The `download.<kind>` variants an in-box agent can request. */\nexport type DownloadKind = 'workspace' | 'env' | 'config' | 'claude';\n\n/**\n * Parse the `download.<kind>` RPC method into its kind, defaulting a missing\n * suffix to 'workspace'. Duplicated inline at the docker (`server.ts`) and\n * cloud (`host-actions.ts`) download entry points.\n */\nexport function parseDownloadKind(method: string): DownloadKind {\n return (method.split('.')[1] ?? 'workspace') as DownloadKind;\n}\n\n/**\n * Resolve a host path supplied by an in-box agent to an absolute host path.\n * Absolute paths pass through; a leading `~`/`~/` expands against the host\n * home; anything else is relative to the box's host `workspacePath` (NOT the\n * relay daemon's CWD). When `workspacePath` is unknown, relative paths fall\n * back to `path.resolve` (process CWD) — same as the old behaviour.\n */\nexport function resolveHostPath(workspacePath: string | undefined, hostPath: string): string {\n if (isAbsolute(hostPath)) return hostPath;\n if (hostPath === '~') return homedir();\n if (hostPath.startsWith('~/')) return join(homedir(), hostPath.slice(2));\n return workspacePath ? resolve(workspacePath, hostPath) : resolve(hostPath);\n}\n","/**\n * Host-side path-containment + secret-file guards for the relay's auto-approve\n * decisions. Unlike its pure sibling `files.ts`, this module DOES touch the\n * filesystem (`realpath`) — that's the whole point: following symlinks is what\n * catches an in-project symlink that actually points outside the box's project\n * folder. Lives in `@agentbox/core` so the relay (`@agentbox/relay`) and the\n * host CLI's carry resolver (`apps/cli`) share one containment definition.\n *\n * These are advisory *safety* checks for relaxing approval prompts, never the\n * only boundary: a not-contained / secret path just falls back to prompting.\n */\n\nimport { realpath } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, normalize, resolve, sep } from 'node:path';\n\n/** realpath `p`, falling back to a lexical resolve when it can't be canonicalized. */\nexport async function realpathSafe(p: string): Promise<string> {\n try {\n return await realpath(p);\n } catch {\n return resolve(p);\n }\n}\n\n/**\n * True when canonicalized `child` is `parent` or lives under it. Both are\n * resolved so the comparison happens in the same (already realpath'd) space —\n * callers pass values that have been through `realpathSafe`.\n */\nexport function isInside(child: string, parent: string): boolean {\n const c = resolve(child);\n const p = resolve(parent);\n if (c === p) return true;\n return c.startsWith(p + sep);\n}\n\n/**\n * realpath the deepest *existing* prefix of `p`, then re-append the\n * not-yet-existing tail. Lets a download/cp destination that doesn't exist yet\n * still be containment-checked (its existing parent is canonicalized, so a\n * symlinked parent pointing outside is caught), while a fully-existing source\n * is realpath'd end-to-end.\n */\nasync function realpathDeepestExisting(p: string): Promise<string> {\n let cur = resolve(p);\n const tail: string[] = [];\n // Bounded by the path depth; dirname() reaches the root fixpoint.\n for (;;) {\n try {\n const real = await realpath(cur);\n return tail.length > 0 ? resolve(real, ...tail.reverse()) : real;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return resolve(p);\n const parent = dirname(cur);\n if (parent === cur) return resolve(p); // nothing along the path exists\n tail.push(basename(cur));\n cur = parent;\n }\n }\n}\n\n/**\n * True when `hostPath` (an absolute host path) resolves to a location inside\n * the box's `workspacePath` (the host dir mirroring `/workspace`). Symlinks are\n * followed via realpath so an in-project link escaping the folder fails the\n * check. A literal `..` that survives normalization is rejected outright.\n * Returns `false` (→ caller prompts) when the workspace is unknown.\n */\nexport async function isContainedInWorkspace(\n hostPath: string,\n workspacePath: string | undefined,\n): Promise<boolean> {\n if (!workspacePath) return false;\n if (!isAbsolute(hostPath)) return false;\n // A surviving `..` segment means the literal path escapes upward.\n if (normalize(hostPath).split(sep).includes('..')) return false;\n const wsReal = await realpathSafe(workspacePath);\n const real = await realpathDeepestExisting(hostPath);\n return isInside(real, wsReal);\n}\n\n/** Sensitive directory names: any path segment equal to one of these is secret. */\nconst SECRET_DIR_SEGMENTS = new Set(['.ssh', '.aws', '.gnupg']);\n\n/** Exact basenames that are always secrets. */\nconst SECRET_BASENAMES = new Set(['credentials', '.npmrc', '.netrc', '.pgpass', '.htpasswd']);\n\n/** Basename patterns that mark a likely secret / private key. */\nconst SECRET_BASENAME_PATTERNS: readonly RegExp[] = [\n /^\\.env(\\..+)?$/, // .env, .env.local, .env.production\n /\\.(pem|key|pfx|p12|keystore|jks)$/i,\n /^id_(rsa|dsa|ecdsa|ed25519)$/, // private SSH keys (not the .pub)\n];\n\n/**\n * True when `hostPath` looks like a secret/credential file — used to keep a\n * host->box copy of such a file behind the approval prompt even when the path\n * is contained. Deliberately conservative (a false positive just re-adds a\n * prompt the user can approve): matches secret dirs, `.config/gh`, exact\n * credential basenames, and private-key patterns.\n */\nexport function looksLikeSecret(hostPath: string): boolean {\n const segs = normalize(hostPath).split(sep).filter(Boolean);\n for (const seg of segs) {\n if (SECRET_DIR_SEGMENTS.has(seg)) return true;\n }\n // `.config/gh` (gh CLI auth) — two adjacent segments.\n for (let i = 0; i + 1 < segs.length; i++) {\n if (segs[i] === '.config' && segs[i + 1] === 'gh') return true;\n }\n const base = basename(hostPath);\n if (SECRET_BASENAMES.has(base)) return true;\n return SECRET_BASENAME_PATTERNS.some((re) => re.test(base));\n}\n","/**\n * Pure git ref/branch decisions, shared by the relay host paths and the in-box\n * ctl. Lives in `@agentbox/core` (not `sandbox-core`) because `@agentbox/ctl`\n * depends only on core — same pattern as the pure engine in `../replace.ts`.\n *\n * No fs/exec: only string logic. The three git push-back paths (docker relay,\n * cloud relay, in-box lease push) keep their divergent *mechanisms* but read\n * these *decisions* from here so the branch/refspec/remote/upstream spellings\n * can't drift apart.\n */\n\n/** Prefix of the per-box scratch branch (`agentbox/<name>`). */\nexport const SCRATCH_BRANCH_PREFIX = 'agentbox/';\n\n/**\n * True for a per-box `agentbox/<name>` scratch branch. Undefined-safe so it\n * reproduces the existing `worktree?.branch.startsWith(...) ?? false` sites\n * exactly (`isScratchBranch(undefined) === false`).\n */\nexport function isScratchBranch(branch: string | undefined): boolean {\n return !!branch && branch.startsWith(SCRATCH_BRANCH_PREFIX);\n}\n\n/**\n * True when a push to `branch` is a *sanctioned* push that may bypass the\n * relay's confirm prompt: it's the box's own `agentbox/<name>` scratch branch\n * (always its job), or it exactly matches the branch the host last put the box\n * on (`sanctionedBranch`). An in-box agent that self-switches HEAD to some\n * other branch (e.g. `main`) fails both arms, so its push still prompts.\n * Undefined-safe; empty/`HEAD` never matches the sanctioned arm.\n */\nexport function isSanctionedPushBranch(\n branch: string | undefined,\n sanctionedBranch: string | undefined,\n): boolean {\n if (isScratchBranch(branch)) return true;\n return isResolvedBranch(branch ?? '') && !!sanctionedBranch && branch === sanctionedBranch;\n}\n\n/**\n * Resolve the push remote, defaulting to 'origin'.\n *\n * MUST be `??`, not `||`: only an *undefined* remote falls back to 'origin'.\n * A legitimately-empty wire remote must stay '' — `||` would coerce it and\n * silently change the push target.\n */\nexport function resolveRemote(remote?: string): string {\n return remote ?? 'origin';\n}\n\n/**\n * Host-only land destination branch: the requested `as` when non-empty, else\n * the source branch (server.ts `handleGitSaveToHost` ≡ host-actions.ts\n * `runGitRpc` host-only path).\n */\nexport function resolveLandDest(src: string, as?: string): string {\n return as && as.length > 0 ? as : src;\n}\n\n/**\n * Host-only land refspec for `git fetch . <refspec>` (docker) / `git fetch\n * <bundle> <refspec>` (cloud). Force prepends `+` for a non-fast-forward\n * overwrite of the destination branch.\n */\nexport function landRefspec(src: string, dest: string, force?: boolean): string {\n return `${force ? '+' : ''}${src}:refs/heads/${dest}`;\n}\n\n/** Upstream ref for `git branch --set-upstream-to=<remote>/<branch>`. */\nexport function upstreamRef(remote: string, branch: string): string {\n return `${remote}/${branch}`;\n}\n\n/**\n * Remote-tracking ref for the cloud in-box `git update-ref\n * refs/remotes/<remote>/<branch>` (docker shares .git/, so the ref updates\n * during the push and only the upstream config is missing). Kept beside\n * `upstreamRef` to document the two distinct ref shapes side-by-side.\n */\nexport function remoteTrackingRef(remote: string, branch: string): string {\n return `refs/remotes/${remote}/${branch}`;\n}\n\n/**\n * Detached-HEAD guard for a probed branch name (cloud `runGitRpc` resolves the\n * branch via `rev-parse --abbrev-ref HEAD`). NOTE: intentionally NOT used by\n * ctl's weaker `!branch` check — adopting it there would add a `=== 'HEAD'`\n * rejection on the control-plane lease push path (a behavior change).\n */\nexport function isResolvedBranch(s: string): boolean {\n return s.length > 0 && s !== 'HEAD';\n}\n\n/**\n * Filter a user-supplied extra-argv tail down to strings. The argv *prefixes*\n * differ per site (`git -C repo push …` vs `-C repo push …` vs `push …`) and\n * stay site-local; only this trailing arg-filter is shared.\n */\nexport function sanitizeGitArgs(args: unknown): string[] {\n return Array.isArray(args) ? args.filter((a): a is string => typeof a === 'string') : [];\n}\n\n/**\n * Wire params for the `git.push` / `git.fetch` RPCs. Canonical home for the\n * shape that the relay receives and the in-box ctl builds (previously declared\n * independently in `relay/src/types.ts` and `ctl/src/commands/git.ts`).\n */\nexport interface GitRpcParams {\n /** Container path identifying which worktree to run against. Defaults to /workspace. */\n path?: string;\n /** Remote name; defaults to 'origin'. */\n remote?: string;\n /** Extra argv tail appended after the standard args (e.g. ['--set-upstream', 'origin', 'branch']). */\n args?: string[];\n /**\n * git.push only: land the box's branch in the host's *local* repo instead of\n * pushing to the remote. Nothing is published online; the relay skips the\n * host-initiated-token / confirm-prompt gate (that gate guards remote pushes).\n */\n hostOnly?: boolean;\n /**\n * git.push --host-only only: destination branch name in the host repo.\n * Defaults to the box's current branch name when omitted.\n */\n as?: string;\n /** git.push --host-only only: allow a non-fast-forward overwrite of the destination branch. */\n force?: boolean;\n /**\n * One-time token minted by the host CLI via `/admin/host-initiated/mint`\n * before invoking this RPC through `agentbox-ctl`. The relay validates the\n * token against its in-memory store, scoped to `(boxId, method)`; on\n * match, the token is consumed and the confirm prompt is skipped. Boxes\n * cannot mint these (the admin endpoint is loopback-only), so a malicious\n * agent cannot forge \"host-initiated\" calls. Invalid/expired tokens fall\n * through to the normal prompt path.\n */\n hostInitiated?: string;\n}\n","import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport type {\n BoxRecord,\n DockerBoxFields,\n FindBoxResult,\n SshTargetRecord,\n StateFile,\n} from '@agentbox/core';\n\nexport const STATE_DIR = join(homedir(), '.agentbox');\nexport const STATE_FILE = join(STATE_DIR, 'state.json');\n\nconst EMPTY: StateFile = { version: 1, boxes: [] };\n\n// Cross-process lock tunables. The lock guards the read-modify-write of\n// `state.json` so concurrent `agentbox create`/`destroy` processes can't lose\n// each other's records or interleave a half-written file. Held only for the\n// duration of one read+write (sub-millisecond), so contention clears fast even\n// with a burst of parallel creates.\nconst LOCK_STALE_MS = 15_000; // a lock older than this is presumed abandoned\nconst LOCK_ACQUIRE_TIMEOUT_MS = 20_000;\nconst LOCK_RETRY_MS = 25;\n\n/**\n * Run `fn` while holding an exclusive cross-process lock on `${path}.lock`.\n *\n * Acquisition: create the lockfile with `wx` (O_EXCL) — atomic on local FSes.\n * On contention, retry with a short backoff until {@link LOCK_ACQUIRE_TIMEOUT_MS};\n * a lockfile older than {@link LOCK_STALE_MS} is treated as abandoned (crashed\n * holder) and forcibly broken. If the lock still can't be taken before the\n * timeout we proceed anyway — the write is atomic (temp+rename) so the worst\n * case degrades to a possible lost update, never a corrupt file. The lock is\n * always released in `finally`.\n */\nasync function withStateLock<T>(path: string, fn: () => Promise<T>): Promise<T> {\n const lockPath = `${path}.lock`;\n await mkdir(dirname(path), { recursive: true });\n const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS;\n let held = false;\n while (!held) {\n try {\n const fh = await open(lockPath, 'wx');\n await fh.writeFile(`${String(process.pid)}\\n`);\n await fh.close();\n held = true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;\n // Break a stale lock left by a crashed holder.\n try {\n const st = await stat(lockPath);\n if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {\n await rm(lockPath, { force: true });\n continue;\n }\n } catch {\n // lock vanished between open and stat — retry immediately\n continue;\n }\n if (Date.now() >= deadline) break; // give up waiting; proceed best-effort\n await delay(LOCK_RETRY_MS);\n }\n }\n try {\n return await fn();\n } finally {\n if (held) await rm(lockPath, { force: true }).catch(() => {});\n }\n}\n\n/**\n * Locked read-modify-write of the state file. `mutator` receives the current\n * state and returns the next one; the read and the (atomic) write happen under\n * the same lock so concurrent mutators serialize instead of clobbering.\n */\nexport async function mutateState(\n mutator: (state: StateFile) => StateFile,\n path: string = STATE_FILE,\n): Promise<void> {\n await withStateLock(path, async () => {\n const state = await readState(path);\n await writeState(mutator(state), path);\n });\n}\n\nexport async function readState(path: string = STATE_FILE): Promise<StateFile> {\n try {\n const raw = await readFile(path, 'utf8');\n const parsed = JSON.parse(raw) as StateFile;\n if (parsed.version !== 1 || !Array.isArray(parsed.boxes)) {\n throw new Error(`unrecognized state file shape at ${path}`);\n }\n // Migrate-on-read: records written before the multi-provider split carry no\n // `provider` field — they are all Docker boxes. Default it so every\n // consumer (provider registry, `findBox`) sees a discriminated record.\n // Also backfill `box.docker` from the flat fields for Docker records so\n // forward-looking readers (7.1) see the nested shape without waiting\n // for the box to be re-recorded.\n for (const b of parsed.boxes) {\n b.provider ??= 'docker';\n if ((b.provider ?? 'docker') === 'docker' && !b.docker) {\n b.docker = projectDockerFields(b);\n }\n // The SSH target moved from `box.cloud.ssh` to top-level `box.ssh`.\n // Backfill on read so an already-created box (e.g. a Hetzner box) keeps its\n // `~/.agentbox/ssh/config` alias — `syncAgentboxSshConfig` only reads\n // `box.ssh`, and it would otherwise vanish until the box is next started.\n const legacySsh = (b.cloud as { ssh?: SshTargetRecord } | undefined)?.ssh;\n if (!b.ssh && legacySsh) b.ssh = legacySsh;\n }\n return parsed;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { ...EMPTY };\n }\n throw err;\n }\n}\n\nexport async function writeState(state: StateFile, path: string = STATE_FILE): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n // Atomic: write a sibling temp file then rename over the target. rename(2) is\n // atomic on local filesystems, so a concurrent writer (or a reader) never\n // observes a half-written / interleaved JSON file. The pid+time suffix keeps\n // parallel writers from colliding on the temp path itself.\n const tmp = `${path}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, JSON.stringify(state, null, 2) + '\\n', 'utf8');\n await rename(tmp, path);\n}\n\nexport async function recordBox(box: BoxRecord, path: string = STATE_FILE): Promise<void> {\n // Forward-looking shape: every Docker write also mirrors the flat\n // docker-specific fields into `box.docker` so readers can move to the\n // nested form opportunistically (7.1). Cloud records skip the mirror —\n // the discriminator is `box.provider !== 'docker'`.\n const toWrite: BoxRecord =\n (box.provider ?? 'docker') === 'docker' && !box.docker\n ? { ...box, docker: projectDockerFields(box) }\n : box;\n await mutateState(\n (state) => ({\n version: 1,\n boxes: [...state.boxes.filter((b) => b.id !== toWrite.id), toWrite],\n }),\n path,\n );\n}\n\n/**\n * Record which agent was last launched in a box (`agentbox claude` / `codex` /\n * `opencode`). A locked read-modify-write so it can't clobber a concurrent\n * state change. No-op when the box isn't in state (a race with `destroy`).\n * `agentbox recover` reads `box.lastAgent` to decide which agent to relaunch.\n */\nexport async function recordLastAgent(\n boxId: string,\n kind: 'claude' | 'codex' | 'opencode',\n path: string = STATE_FILE,\n): Promise<void> {\n await mutateState(\n (state) => ({\n version: 1,\n boxes: state.boxes.map((b) => (b.id === boxId ? { ...b, lastAgent: kind } : b)),\n }),\n path,\n );\n}\n\n/**\n * Set (or clear) a box's cosmetic `displayName`. A locked read-modify-write so\n * it can't clobber a concurrent state change. Trims the input; an empty/blank\n * value clears the label (falls back to `name`). No-op when the box isn't in\n * state (a race with `destroy`). The label is display/lookup-only — it does not\n * touch the container, git branch, or URL. Reused by the CLI and the hub.\n */\nexport async function setBoxDisplayName(\n boxId: string,\n displayName: string | undefined,\n path: string = STATE_FILE,\n): Promise<void> {\n const trimmed = displayName?.trim();\n const next = trimmed ? trimmed : undefined;\n await mutateState(\n (state) => ({\n version: 1,\n boxes: state.boxes.map((b) => {\n if (b.id !== boxId) return b;\n if (next) return { ...b, displayName: next };\n const rest = { ...b };\n delete rest.displayName;\n return rest;\n }),\n }),\n path,\n );\n}\n\n/**\n * Persist a box's last resolved SSH target (`box.ssh`). A locked\n * read-modify-write so it can't clobber a concurrent state change. No-op when\n * the box isn't in state (a race with `destroy`). Works for any provider — the\n * docker localhost sshd (host `127.0.0.1` + ephemeral `port`) and cloud\n * providers (Hetzner VPS IP) both land here. `syncAgentboxSshConfig` reads it\n * back to regenerate `~/.agentbox/ssh/config` offline, without re-resolving the\n * target from the provider.\n */\nexport async function recordBoxSsh(\n boxId: string,\n ssh: { host: string; user: string; identityFile?: string; port?: number },\n path: string = STATE_FILE,\n): Promise<void> {\n await mutateState(\n (state) => ({\n version: 1,\n boxes: state.boxes.map((b) => (b.id === boxId ? { ...b, ssh } : b)),\n }),\n path,\n );\n}\n\n/**\n * Atomically allocate the next per-project index AND persist `record` claiming\n * it, under the state lock. Returns the reserved index (also stamped onto the\n * persisted record).\n *\n * Callers bake this index into on-disk paths (`<id>-<n>-<mnemonic>` box dir,\n * socket, snapshot), and host helpers re-derive those paths from the *recorded*\n * index — so the index must be settled before the paths are built. Allocating\n * with an unlocked `readState` and bumping a clash at record time would desync\n * the recorded index from the box's actual directory (status/ctl reads would\n * then miss it). Reserving up front, under the lock, guarantees the index a\n * create uses for its dirs is exactly the one in state.json, with no two\n * concurrent creates in the same project claiming the same number.\n */\nexport async function reserveProjectIndex(\n record: BoxRecord,\n projectRoot: string,\n path: string = STATE_FILE,\n): Promise<number> {\n let index = 1;\n await mutateState((state) => {\n index = allocateProjectIndex(state, projectRoot);\n const reserved: BoxRecord = { ...record, projectRoot, projectIndex: index };\n return {\n version: 1,\n boxes: [...state.boxes.filter((b) => b.id !== record.id), reserved],\n };\n }, path);\n return index;\n}\n\n/**\n * Build a `DockerBoxFields` payload from the flat Docker-specific fields\n * still living on `BoxRecord` for back-compat. Pure function, no\n * filesystem; safe for both `readState` migration and `recordBox` mirror.\n *\n * Once every reader uses `box.docker?.<field>` (the rest of 7.1), the\n * flat fields can be dropped and this projection becomes the canonical\n * shape. Until then, every write produces both shapes from the same\n * source so they can't drift.\n */\nfunction projectDockerFields(box: BoxRecord): DockerBoxFields {\n return {\n container: box.container,\n image: box.image,\n snapshotDir: box.snapshotDir ?? null,\n socketPath: box.socketPath,\n claudeConfigVolume: box.claudeConfigVolume,\n codexConfigVolume: box.codexConfigVolume,\n opencodeConfigVolume: box.opencodeConfigVolume,\n vscodeServerVolume: box.vscodeServerVolume,\n cursorServerVolume: box.cursorServerVolume,\n vncHostPort: box.vncHostPort,\n webHostPort: box.webHostPort,\n portlessAlias: box.portlessAlias,\n portlessUrl: box.portlessUrl,\n portlessVncAlias: box.portlessVncAlias,\n portlessVncUrl: box.portlessVncUrl,\n dockerVolume: box.dockerVolume,\n dockerCacheShared: box.dockerCacheShared,\n checkpointImage: box.checkpointImage,\n };\n}\n\nexport async function removeBoxRecord(id: string, path: string = STATE_FILE): Promise<boolean> {\n let removed = false;\n await mutateState((state) => {\n const next = state.boxes.filter((b) => b.id !== id);\n removed = next.length !== state.boxes.length;\n return { version: 1, boxes: next };\n }, path);\n return removed;\n}\n\n/**\n * Resolve a user-supplied identifier against the state file. Matching\n * precedence mirrors `docker`'s container reference resolution:\n *\n * 1. exact id\n * 2. unique id prefix\n * 3. exact name\n * 4. exact displayName (cosmetic label)\n * 5. exact container name\n *\n * Returns `'ambiguous'` if step 2 finds more than one match (steps 1, 3, 4\n * are exact-match so they cannot be ambiguous on their own).\n */\nexport function findBox(idOrName: string, state: StateFile): FindBoxResult {\n const q = idOrName.trim();\n if (q.length === 0) return { kind: 'none' };\n\n const exactId = state.boxes.find((b) => b.id === q);\n if (exactId) return { kind: 'ok', box: exactId };\n\n const prefixMatches = state.boxes.filter((b) => b.id.startsWith(q));\n if (prefixMatches.length === 1) return { kind: 'ok', box: prefixMatches[0]! };\n if (prefixMatches.length > 1) return { kind: 'ambiguous', matches: prefixMatches };\n\n const byName = state.boxes.find((b) => b.name === q);\n if (byName) return { kind: 'ok', box: byName };\n\n // A renamed box is addressable by its cosmetic `displayName`. Lowest-precedence\n // exact match (after id/name) so a label that happens to equal another box's\n // id/name never shadows it; first match wins on displayName collisions.\n const byDisplayName = state.boxes.find((b) => b.displayName === q);\n if (byDisplayName) return { kind: 'ok', box: byDisplayName };\n\n // For docker records `container` is the docker container name; for cloud\n // records it's `cloud:<sandboxId>` (post 7.2 — no more synthetic\n // agentbox-cloud-* prefix). Either form is a valid byContainer lookup\n // key for `findBox`.\n const byContainer = state.boxes.find((b) => b.container === q);\n if (byContainer) return { kind: 'ok', box: byContainer };\n\n return { kind: 'none' };\n}\n\n/**\n * Next monotonic 1-based index for the given project. Reads only `state.boxes`\n * — caller is responsible for persisting the assignment. Boxes without\n * `projectRoot` are ignored (legacy records); boxes in *other* projects are\n * also ignored. Indices are never recycled, so a destroyed #2 leaves a gap.\n */\nexport function allocateProjectIndex(state: StateFile, projectRoot: string): number {\n let max = 0;\n for (const b of state.boxes) {\n if (b.projectRoot !== projectRoot) continue;\n if (typeof b.projectIndex === 'number' && b.projectIndex > max) {\n max = b.projectIndex;\n }\n }\n return max + 1;\n}\n\n/**\n * Auto-pick when a command's `[box]` argument is omitted. Returns the unique\n * box for `projectRoot`, an `ambiguous` carrying all candidates so the CLI can\n * print a chooser, or `none`.\n */\nexport function autoPickProjectBox(state: StateFile, projectRoot: string): FindBoxResult {\n const matches = state.boxes.filter((b) => b.projectRoot === projectRoot);\n if (matches.length === 0) return { kind: 'none' };\n if (matches.length === 1) return { kind: 'ok', box: matches[0]! };\n return { kind: 'ambiguous', matches };\n}\n\n/**\n * Top-level resolver every CLI command goes through. Combines numeric-index\n * lookup with the legacy `findBox` matcher:\n *\n * - `ref === undefined` and `projectRoot` known → autoPickProjectBox.\n * - `ref` is a pure positive integer and `projectRoot` known → resolve as\n * project index. **Never** falls through to `findBox` on miss, so\n * `agentbox open 3` is reserved for the index and won't accidentally\n * match a hex id like `3abc…`.\n * - Otherwise → `findBox` (id → prefix → name → container).\n */\nexport function resolveBoxRef(\n ref: string | undefined,\n state: StateFile,\n projectRoot: string | undefined,\n): FindBoxResult {\n if (ref === undefined) {\n if (projectRoot === undefined) return { kind: 'none' };\n return autoPickProjectBox(state, projectRoot);\n }\n const trimmed = ref.trim();\n if (projectRoot !== undefined && /^[1-9][0-9]*$/.test(trimmed)) {\n const idx = Number.parseInt(trimmed, 10);\n const hit = state.boxes.find((b) => b.projectRoot === projectRoot && b.projectIndex === idx);\n return hit ? { kind: 'ok', box: hit } : { kind: 'none' };\n }\n return findBox(trimmed, state);\n}\n","import { execa } from 'execa';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport interface DetectedGitRepo {\n kind: 'root' | 'nested';\n /** Absolute host path of the repo working tree (== `<workspace>` for root). */\n hostMainRepo: string;\n /** Path relative to the workspace where the repo lives. Empty string for root. */\n relPathFromWorkspace: string;\n}\n\n/**\n * Look for `.git` directories at the workspace root and at every 1st-level\n * subdirectory. Worktree-form `.git` files (regular file containing\n * `gitdir: …`) are intentionally skipped — turning an existing worktree into\n * another worktree gets weird, and the user case for it is rare.\n *\n * Pure host-side detection: it only tells callers where the repos are. Docker\n * boxes create the worktree inside the container against the bind-mounted\n * `.git/`; cloud boxes clone from a bundle. Either way this is the host probe.\n */\nexport async function detectGitRepos(workspace: string): Promise<DetectedGitRepo[]> {\n const out: DetectedGitRepo[] = [];\n if (await isGitDir(join(workspace, '.git'))) {\n out.push({ kind: 'root', hostMainRepo: workspace, relPathFromWorkspace: '' });\n }\n let entries: Array<{ name: string; isDirectory: () => boolean }>;\n try {\n entries = await readdir(workspace, { withFileTypes: true });\n } catch {\n return out;\n }\n for (const e of entries) {\n if (!e.isDirectory() || e.name.startsWith('.')) continue;\n const sub = join(workspace, e.name);\n if (await isGitDir(join(sub, '.git'))) {\n out.push({ kind: 'nested', hostMainRepo: sub, relPathFromWorkspace: e.name });\n }\n }\n return out;\n}\n\nasync function isGitDir(path: string): Promise<boolean> {\n try {\n const s = await stat(path);\n return s.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Pick `<base>`, `<base>-2`, `<base>-3`, … until git reports no such branch\n * exists. Avoids collision when the user reruns `agentbox create -n same-name`\n * after destroying — the destroyed box's branch still lives in the host repo.\n */\nexport async function pickFreshBranch(hostMainRepo: string, base: string): Promise<string> {\n let candidate = base;\n let suffix = 2;\n while (await branchExists(hostMainRepo, candidate)) {\n candidate = `${base}-${String(suffix++)}`;\n if (suffix > 100) throw new GitWorktreeError(`could not find a free branch name near ${base}`);\n }\n return candidate;\n}\n\nasync function branchExists(hostMainRepo: string, name: string): Promise<boolean> {\n const result = await execa(\n 'git',\n ['-C', hostMainRepo, 'show-ref', '--verify', '--quiet', `refs/heads/${name}`],\n { reject: false },\n );\n return result.exitCode === 0;\n}\n\nexport class GitWorktreeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GitWorktreeError';\n }\n}\n","/**\n * The host command that opens a URL or file path in the OS default handler.\n *\n * macOS ships `open`; Linux uses `xdg-open` (from `xdg-utils`, present on any\n * desktop install). We deliberately return only the binary name and let each\n * call site keep its own spawn semantics (sync/async, stdio, detached) — the\n * single platform decision lives here so adding a host platform is a one-line\n * change. Callers already treat a non-zero exit / ENOENT as \"couldn't\n * auto-open\" and print the target, so an absent `xdg-open` degrades cleanly.\n */\nexport function hostOpenCommand(): string {\n return process.platform === 'linux' ? 'xdg-open' : 'open';\n}\n","import { promises as fs } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { pruneOrphanClaudeSshConfigs } from './claude-app-config.js';\nimport { readState } from './state.js';\n\n/**\n * Host-side SSH-config manager for cloud boxes. AgentBox owns a dedicated file\n * `~/.agentbox/ssh/config` holding one `Host <alias>` block per SSH-capable box,\n * and injects a single managed `Include ~/.agentbox/ssh/config` line into the\n * user's `~/.ssh/config` — so our churn stays out of their hand-maintained\n * config. The owned file is regenerated wholesale from `state.json`\n * (`syncAgentboxSshConfig`), which self-heals stale/destroyed boxes and reads\n * only persisted state (no provider calls, never wakes a paused box).\n *\n * Daytona's SSH gateway authenticates per-token (the User field carries an\n * ephemeral 60-min token from `sb.createSshAccess(60)`), so `agentbox code`\n * re-resolves + re-syncs on every invocation to keep the alias mapped to a live\n * token.\n */\n\nexport interface SshAliasOptions {\n /** Host alias the user (and VS Code Remote-SSH) refers to — the box name, e.g. `myname`. */\n alias: string;\n /** Daytona SSH gateway, typically `ssh.app.daytona.io`. */\n hostname: string;\n /** Ephemeral Daytona token (used as the SSH User). Rotates every call. */\n user: string;\n /**\n * Per-box private key path for providers that authenticate by identity\n * file (docker localhost sshd, Hetzner). Omit for token-in-User auth\n * (Daytona) — without this field VSCode's Remote-SSH would try ~/.ssh/id_*\n * defaults and fail with \"permission denied\" against a Hetzner VPS that only\n * trusts the per-box key under `~/.agentbox/boxes/<id>/ssh/id_ed25519`.\n */\n identityFile?: string;\n /**\n * Non-default SSH port. Docker publishes its in-box sshd on an ephemeral\n * `127.0.0.1:<port>`; omit for cloud providers reachable on 22.\n */\n port?: number;\n}\n\nfunction sshConfigPath(): string {\n return join(homedir(), '.ssh', 'config');\n}\n\n/** AgentBox-owned SSH config file `Include`d from `~/.ssh/config`. */\nexport function agentboxSshConfigPath(): string {\n return join(homedir(), '.agentbox', 'ssh', 'config');\n}\n\nfunction stateFilePath(): string {\n return join(homedir(), '.agentbox', 'state.json');\n}\n\nconst INCLUDE_BEGIN = '# BEGIN agentbox ssh include';\nconst INCLUDE_END = '# END agentbox ssh include';\n\nfunction beginMarker(alias: string): string {\n return `# BEGIN agentbox cloud box ${alias}`;\n}\n\nfunction endMarker(alias: string): string {\n return `# END agentbox cloud box ${alias}`;\n}\n\n/**\n * Stable `~/.ssh/config` Host alias for a box: the box name itself. Box names\n * are already kebab-safe, so `ssh <boxname>` works and external apps (Codex's\n * `codex://…?name=<alias>` deep link, Claude desktop) get a clean, memorable\n * host. Our BEGIN/END-marked managed block keeps this entry isolated from any\n * user-authored `Host <boxname>` so the two coexist.\n */\nexport function agentboxAliasFor(boxName: string): string {\n return boxName;\n}\n\nasync function readFileOrEmpty(path: string): Promise<string> {\n try {\n return await fs.readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return '';\n throw err;\n }\n}\n\nfunction buildBlock(opts: SshAliasOptions): string {\n // `UserKnownHostsFile /dev/null` + `LogLevel ERROR` is the Vagrant / dev-tool\n // convention: many sandboxes sit behind one DNS name, so pinning a host key\n // locally generates noise + false-positive HostKeyVerificationFailed errors.\n const lines: string[] = [\n beginMarker(opts.alias),\n `Host ${opts.alias}`,\n ` HostName ${opts.hostname}`,\n ` User ${opts.user}`,\n ];\n if (opts.port) {\n lines.push(` Port ${String(opts.port)}`);\n }\n if (opts.identityFile) {\n // `IdentitiesOnly yes` stops ssh-agent from offering unrelated keys\n // first — some sshd configs cap auth attempts and would lock us out\n // before the right key is tried.\n lines.push(` IdentityFile ${opts.identityFile}`);\n lines.push(` IdentitiesOnly yes`);\n }\n lines.push(\n ` StrictHostKeyChecking accept-new`,\n ` UserKnownHostsFile /dev/null`,\n ` LogLevel ERROR`,\n endMarker(opts.alias),\n '',\n );\n return lines.join('\\n');\n}\n\n/**\n * Old versions wrote per-box `# BEGIN agentbox cloud box <alias>` … `# END …`\n * blocks directly into `~/.ssh/config`. We now own `~/.agentbox/ssh/config`, so\n * strip any such inline leftovers whenever we touch `~/.ssh/config`. AgentBox is\n * unreleased → clean removal, no deprecation shim.\n */\nfunction stripLegacyInlineBlocks(contents: string): string {\n const pattern =\n /^# BEGIN agentbox cloud box .*\\n[\\s\\S]*?^# END agentbox cloud box .*\\n?/gm;\n return contents.replace(pattern, '');\n}\n\nfunction hasIncludeBlock(contents: string): boolean {\n return (\n contents.includes(INCLUDE_BEGIN) || contents.includes(`Include ${agentboxSshConfigPath()}`)\n );\n}\n\n/**\n * Ensure `~/.ssh/config` contains exactly one managed `Include\n * ~/.agentbox/ssh/config` block, prepended to the top. Prepend (not append)\n * because OpenSSH applies the first value it sees per keyword — putting the\n * Include first lets AgentBox's box entries win over any later user `Host *`\n * defaults. Also strips any legacy inline per-box blocks. Idempotent.\n */\nexport async function ensureSshInclude(): Promise<void> {\n const path = sshConfigPath();\n await fs.mkdir(join(homedir(), '.ssh'), { recursive: true, mode: 0o700 });\n const existing = stripLegacyInlineBlocks(await readFileOrEmpty(path));\n let next = existing;\n if (!hasIncludeBlock(existing)) {\n const block = `${INCLUDE_BEGIN}\\nInclude ${agentboxSshConfigPath()}\\n${INCLUDE_END}\\n`;\n next = existing.length === 0 ? block : `${block}\\n${existing}`;\n }\n await fs.writeFile(path, next, { mode: 0o600 });\n // Re-assert mode in case the file existed with broader perms.\n await fs.chmod(path, 0o600);\n}\n\n/**\n * Regenerate the AgentBox-owned `~/.agentbox/ssh/config` from `state.json`: one\n * `Host <name>` block per box that carries a resolved `box.ssh` target. Reads\n * only persisted state — no provider calls, never wakes a paused box — so a\n * destroyed box's block simply disappears on the next sync. Also ensures the\n * `Include` line in `~/.ssh/config`.\n */\nexport async function syncAgentboxSshConfig(statePath: string = stateFilePath()): Promise<void> {\n const state = await readState(statePath);\n const blocks: string[] = [];\n for (const box of state.boxes) {\n const ssh = box.ssh;\n if (!ssh) continue;\n blocks.push(\n buildBlock({\n alias: agentboxAliasFor(box.name),\n hostname: ssh.host,\n user: ssh.user,\n identityFile: ssh.identityFile,\n port: ssh.port,\n }),\n );\n }\n const header =\n '# Managed by agentbox — regenerated on box create/start/destroy.\\n' +\n '# Do not edit; changes are overwritten. Disable with `agentbox config set ssh.autoConfig false`.\\n\\n';\n const path = agentboxSshConfigPath();\n await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });\n await fs.writeFile(path, header + blocks.join('\\n'), { mode: 0o600 });\n await fs.chmod(path, 0o600);\n await ensureSshInclude();\n\n // Sweep Claude desktop's sshConfigs (written by `open --in claude`) of\n // entries whose box is gone — piggybacking on the sync means every destroy\n // path prunes (CLI, hub, dashboard), and any later sync self-heals one that\n // didn't. Aliases are keyed by box NAME (an entry survives a transiently\n // ssh-less record). Best-effort: a corrupt settings.json must never break\n // box lifecycle.\n try {\n pruneOrphanClaudeSshConfigs(new Set(state.boxes.map((b) => agentboxAliasFor(b.name))));\n } catch {\n /* best-effort */\n }\n}\n\n/**\n * True when `~/.ssh/config` has a user-authored `Host <alias>` stanza. With the\n * Include prepended, AgentBox's entry is read first so it wins — but a foreign\n * `Host <alias>` is still worth flagging to the user in case they expected their\n * own entry to take effect.\n */\nexport async function hasUnmanagedHostConflict(alias: string): Promise<boolean> {\n const contents = stripLegacyInlineBlocks(await readFileOrEmpty(sshConfigPath()));\n if (contents === '') return false;\n return contents.split('\\n').some((line) => {\n const m = /^\\s*Host\\s+(.+?)\\s*$/.exec(line);\n if (!m) return false;\n return m[1]!.split(/\\s+/).includes(alias);\n });\n}\n\nexport interface SshTarget {\n user: string;\n host: string;\n /** Path from `-i <path>` if the argv carries one (Hetzner). Undefined for\n * Daytona where auth is via token-in-User. */\n identityFile?: string;\n}\n\n/**\n * Pluck the SSH connect target (and identity file, if any) out of an argv\n * returned by a provider's `attachArgv` / `buildAttach`. The argv shape is\n * `ssh [-i <path>] [-o ...] <user>@<host> [command...]` — we walk from the\n * end to find the user@host token and scan forward for `-i`.\n */\nexport function parseSshTarget(argv: readonly string[]): SshTarget | undefined {\n let target: { user: string; host: string } | undefined;\n for (let i = argv.length - 1; i >= 0; i--) {\n const v = argv[i];\n if (!v || v.startsWith('-')) continue;\n const at = v.indexOf('@');\n if (at <= 0) continue;\n target = { user: v.slice(0, at), host: v.slice(at + 1) };\n break;\n }\n if (!target) return undefined;\n let identityFile: string | undefined;\n for (let i = 0; i < argv.length - 1; i++) {\n if (argv[i] === '-i') {\n identityFile = argv[i + 1];\n break;\n }\n }\n return { ...target, identityFile };\n}\n\n/**\n * Read back the `HostName` / `IdentityFile` from the managed block for `alias`\n * in `~/.agentbox/ssh/config`, if one exists. Used by `inspect` to surface the\n * SSH connection details without re-deriving them from a provider (which would\n * require bringing the box online). Returns undefined when no managed block is\n * present for the alias.\n */\nexport async function readAgentboxSshAlias(\n alias: string,\n): Promise<{ hostName?: string; identityFile?: string } | undefined> {\n const contents = await readFileOrEmpty(agentboxSshConfigPath());\n if (contents === '') return undefined;\n const begin = beginMarker(alias);\n const end = endMarker(alias);\n const escape = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const match = new RegExp(`^${escape(begin)}\\\\n([\\\\s\\\\S]*?)${escape(end)}`, 'm').exec(contents);\n if (!match) return undefined;\n const body = match[1] ?? '';\n const field = (name: string): string | undefined =>\n new RegExp(`^\\\\s*${name}\\\\s+(.+)$`, 'm').exec(body)?.[1]?.trim();\n return { hostName: field('HostName'), identityFile: field('IdentityFile') };\n}\n","/**\n * Writer for the Claude desktop app's own settings (`~/.claude/settings.json`)\n * — the app-local analogue of Codex's `codex://settings/connections/ssh/add`\n * deep link, which Claude.app doesn't have. The app reads SSH environments\n * from a `sshConfigs` array in its user settings (schema verified against\n * Claude.app v1.19367): `{ id, name, sshHost, sshPort?, sshIdentityFile?,\n * startDirectory? }`, where `sshHost` may be an alias from `~/.ssh/config` —\n * which is exactly what AgentBox maintains per box.\n *\n * This file is the user's REAL Claude Code settings: preserve every key we\n * don't own, and fail loud (never overwrite) when it exists but doesn't parse.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nexport interface ClaudeSshConfigEntry {\n /** Unique id; the app matches configs across settings sources by it. */\n id: string;\n /** Display name shown in the app's Environment dropdown. */\n name: string;\n /** \"user@host\", \"host\", or an alias from ~/.ssh/config. */\n sshHost: string;\n sshPort?: number;\n sshIdentityFile?: string;\n /** Default working directory on the remote (tilde-expanded by the app). */\n startDirectory?: string;\n}\n\nexport function claudeSettingsPath(): string {\n return join(homedir(), '.claude', 'settings.json');\n}\n\n/** The sshConfigs entry for a box: the alias carries port + identity file. */\nexport function claudeSshEntryFor(alias: string, boxName: string): ClaudeSshConfigEntry {\n return {\n id: `agentbox-${alias}`,\n name: `AgentBox: ${boxName}`,\n sshHost: alias,\n startDirectory: '/workspace',\n };\n}\n\ninterface ClaudeSettings {\n sshConfigs?: unknown[];\n [key: string]: unknown;\n}\n\nfunction readSettings(path: string): ClaudeSettings {\n if (!existsSync(path)) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, 'utf8'));\n } catch (err) {\n throw new Error(\n `${path} exists but is not valid JSON (${err instanceof Error ? err.message : String(err)}) — ` +\n `not touching it. Fix the file and retry.`,\n );\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${path} is not a JSON object — not touching it. Fix the file and retry.`);\n }\n return parsed as ClaudeSettings;\n}\n\nfunction writeSettings(path: string, settings: ClaudeSettings): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(settings, null, 2) + '\\n');\n}\n\nfunction entryId(e: unknown): string | undefined {\n if (e !== null && typeof e === 'object' && typeof (e as { id?: unknown }).id === 'string') {\n return (e as { id: string }).id;\n }\n return undefined;\n}\n\n/**\n * Insert or replace (by `id`) one entry in `sshConfigs`, preserving every\n * other entry and every other settings key. Throws on an unparseable file.\n */\nexport function upsertClaudeSshConfig(entry: ClaudeSshConfigEntry): void {\n const path = claudeSettingsPath();\n const settings = readSettings(path);\n const configs = Array.isArray(settings.sshConfigs) ? settings.sshConfigs : [];\n const idx = configs.findIndex((e) => entryId(e) === entry.id);\n if (idx >= 0) {\n configs[idx] = entry;\n } else {\n configs.push(entry);\n }\n settings.sshConfigs = configs;\n writeSettings(path, settings);\n}\n\n/**\n * Drop every AgentBox-owned (`agentbox-`-prefixed) entry whose alias no longer\n * matches a live box. Called (best-effort) from `syncAgentboxSshConfig`, which\n * every lifecycle path runs — CLI destroy, hub/dashboard destroys via\n * `provider.destroy`+sync, and any later create/start — so an entry left by a\n * path that skipped the sync is swept on the next one. Foreign entries (no\n * `agentbox-` prefix) are never touched.\n */\nexport function pruneOrphanClaudeSshConfigs(liveAliases: ReadonlySet<string>): number {\n return removeClaudeSshConfigs(\n (id) => id.startsWith('agentbox-') && !liveAliases.has(id.slice('agentbox-'.length)),\n );\n}\n\n/**\n * Drop every `sshConfigs` entry whose id matches `predicate`. No-op when the\n * file is missing, has no `sshConfigs`, or nothing matches — the file is only\n * rewritten on a change. Throws on an unparseable file (callers treat this as\n * best-effort).\n */\nexport function removeClaudeSshConfigs(predicate: (id: string) => boolean): number {\n const path = claudeSettingsPath();\n if (!existsSync(path)) return 0;\n const settings = readSettings(path);\n if (!Array.isArray(settings.sshConfigs)) return 0;\n const kept = settings.sshConfigs.filter((e) => {\n const id = entryId(e);\n return id === undefined || !predicate(id);\n });\n const removed = settings.sshConfigs.length - kept.length;\n if (removed === 0) return 0;\n settings.sshConfigs = kept;\n writeSettings(path, settings);\n return removed;\n}\n","import type { BoxRecord, Provider } from '@agentbox/core';\nimport { recordBoxSsh } from './state.js';\nimport { agentboxAliasFor, parseSshTarget, syncAgentboxSshConfig } from './ssh-config.js';\n\n/**\n * Resolve + persist a cloud box's SSH connection target and regenerate\n * `~/.agentbox/ssh/config`. Lives in sandbox-core (not the CLI) so BOTH the CLI\n * commands AND the hub can write the SSH config after create/start/resume — the\n * caller supplies the already-resolved `Provider` (the CLI via `providerForBox`,\n * the hub via its own provider seam), so this code takes no dependency on either\n * one's provider registry.\n */\n\nexport interface CloudSshAlias {\n /** Host alias written to `~/.ssh/config` (the box name). */\n alias: string;\n /** SSH host — VPS IP (Hetzner) or gateway domain (Daytona). */\n host: string;\n /** SSH user — `vscode` (Hetzner) or an ephemeral token (Daytona). */\n user: string;\n /**\n * Per-box private key path when the provider authenticates by identity file\n * (Hetzner). Undefined for token-in-User providers (Daytona) — callers that\n * need a persistent connection (external apps) should treat its absence as\n * \"not supported\".\n */\n identityFile?: string;\n}\n\nexport interface CloudSshOptions {\n /**\n * Bring the box online (resume/start) before resolving the target. Default\n * true. Callers that already brought the box online (e.g. `agentbox code`\n * after its own wait-ready) pass false to skip a redundant lifecycle pass.\n */\n bringOnline?: boolean;\n /** Optional progress logger for the bring-online path (CLI passes clack's `log.info`). */\n logInfo?: (msg: string) => void;\n}\n\n/**\n * Resolve a cloud box's SSH connection target WITHOUT touching `~/.ssh/config`.\n * Lets callers inspect the target (e.g. gate on a persistent `identityFile`)\n * before deciding to persist an alias.\n *\n * The SSH-support check runs FIRST, before any lifecycle action — so an\n * unsupported provider (e.g. Docker, which has no `buildAttach`) errors without\n * resuming/starting the box. `buildAttach(..., { noTmux: true })` yields the\n * plain `ssh ... <user>@<host>` argv; the identity path (if any) is parsed\n * straight out of it so we never hardcode a provider-specific key path.\n */\nexport async function resolveCloudSshTarget(\n box: BoxRecord,\n provider: Provider,\n opts: CloudSshOptions = {},\n): Promise<CloudSshAlias> {\n if (!provider.buildAttach) {\n throw new Error(`cloud provider '${provider.name}' does not support SSH attach`);\n }\n\n if (opts.bringOnline ?? true) {\n const state = await provider.probeState(box);\n if (state === 'paused') {\n opts.logInfo?.('box is paused; resuming');\n await provider.resume(box);\n } else if (state === 'stopped') {\n opts.logInfo?.('box is stopped; starting');\n await provider.start(box);\n } else if (state === 'missing') {\n throw new Error(`cloud sandbox for ${box.name} is missing; was it deleted?`);\n }\n }\n\n const spec = await provider.buildAttach(box, 'shell', { noTmux: true });\n const target = parseSshTarget(spec.argv);\n if (!target) {\n throw new Error(`could not parse <user>@<host> from cloud SSH argv: ${spec.argv.join(' ')}`);\n }\n const alias = agentboxAliasFor(box.name);\n return { alias, host: target.host, user: target.user, identityFile: target.identityFile };\n}\n\n/**\n * Bring a cloud box online, persist its resolved SSH target to `box.ssh`,\n * and regenerate `~/.agentbox/ssh/config` (+ the `~/.ssh/config` Include),\n * returning the connection target. Shared by `agentbox code` (VS Code\n * Remote-SSH), `agentbox open` (sshfs mount), and `agentbox shell --ssh-config`\n * (external app handoff) — all three need the same alias mapped to a live SSH\n * target. These are explicit user actions, so they write regardless of the\n * `ssh.autoConfig` toggle (which only governs the proactive create/start path).\n */\nexport async function ensureCloudSshAlias(\n box: BoxRecord,\n provider: Provider,\n opts: CloudSshOptions = {},\n): Promise<CloudSshAlias> {\n const conn = await resolveCloudSshTarget(box, provider, opts);\n await recordBoxSsh(box.id, {\n host: conn.host,\n user: conn.user,\n identityFile: conn.identityFile,\n });\n await syncAgentboxSshConfig();\n return conn;\n}\n\n/**\n * Proactive, default-on SSH-config write on create/start/resume — gated by the\n * `ssh.autoConfig` config key so a user who manages `~/.ssh/config` themselves\n * can opt out. Only persistent-identity providers qualify (Hetzner/DigitalOcean:\n * a per-box identity file that survives across sessions); Daytona's ephemeral\n * token and Docker/Vercel/E2B (no SSH) are skipped. Best-effort: a failure here\n * must never break the lifecycle command/action that triggered it — but it is no\n * longer swallowed silently, so `logWarn` surfaces the reason (CLI stderr, hub log).\n *\n * The box is assumed already online (create just finished, or start/resume\n * brought it up), so `bringOnline: false` avoids a redundant lifecycle pass.\n * Re-resolving on start is what refreshes a Hetzner box's changed public IP.\n */\nexport async function autoWriteSshConfig(\n box: BoxRecord,\n provider: Provider,\n enabled: boolean,\n logWarn?: (msg: string) => void,\n): Promise<void> {\n if (!enabled) return;\n try {\n const conn = await resolveCloudSshTarget(box, provider, { bringOnline: false });\n if (!conn.identityFile) return;\n await recordBoxSsh(box.id, {\n host: conn.host,\n user: conn.user,\n identityFile: conn.identityFile,\n });\n await syncAgentboxSshConfig();\n } catch (err) {\n // Best-effort: SSH-config auto-write must never break create/start. But\n // surface the reason rather than swallowing it (this masked the hub-create\n // gap for a whole release).\n logWarn?.(\n `ssh-config auto-write for ${box.name} failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n","/**\n * Per-box SSH key minting, shared by every provider that authenticates a box\n * over SSH by identity file: the docker localhost sshd and the Hetzner VPS both\n * mint a fresh ed25519 keypair per box and never let the private key leave the\n * host. The public key is installed into the box's `authorized_keys` (docker via\n * `docker exec`, Hetzner via cloud-init).\n */\n\nimport { mkdir, readFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { execa } from 'execa';\n\nexport interface MintedSshKey {\n /** Directory holding the key files. */\n dir: string;\n /** Absolute path to the private key. */\n privatePath: string;\n /** Absolute path to the public key. */\n publicPath: string;\n /** Public key contents (one OpenSSH-format line). */\n publicKey: string;\n}\n\n/**\n * Mint a fresh ed25519 keypair into `targetDir/id_ed25519` (+ `.pub`). The\n * directory is created if missing (0700). `comment` is embedded in the public\n * key so the key is identifiable in `authorized_keys` on a forensic look.\n *\n * Reuses the existing keypair when `targetDir/id_ed25519` is already present\n * (idempotent across `agentbox start`), reading its `.pub` back — callers on the\n * restart path can call this blindly without clobbering the key the box already\n * trusts.\n */\nexport async function mintSshKey(targetDir: string, comment: string): Promise<MintedSshKey> {\n const dir = resolve(targetDir);\n const priv = join(dir, 'id_ed25519');\n const pub = `${priv}.pub`;\n await mkdir(dir, { recursive: true, mode: 0o700 });\n\n const existing = await readFile(pub, 'utf8').catch(() => null);\n if (existing !== null) {\n return { dir, privatePath: priv, publicPath: pub, publicKey: existing.trim() };\n }\n\n // `ssh-keygen -N ''` for no passphrase; `-q` to suppress the random art.\n await execa('ssh-keygen', ['-t', 'ed25519', '-N', '', '-C', comment, '-f', priv, '-q'], {\n stdio: 'pipe',\n });\n\n const publicKey = (await readFile(pub, 'utf8')).trim();\n return { dir, privatePath: priv, publicPath: pub, publicKey };\n}\n","/**\n * Provider-agnostic box git + service-control helpers, shared by the host CLI\n * (`agentbox git …` / `agentbox services …`) and the hub backend so the argv and\n * RPC-param contracts never drift between the two frontends.\n *\n * Credentialed git RPCs (push / pull-fetch) carry a one-time host-initiated\n * token; minting is a relay concern, so the caller injects it via\n * `deps.hostInitiatedArgs`. Keeping the mint out of this module is deliberate:\n * `@agentbox/relay` depends on `@agentbox/sandbox-core`, so this package must not\n * reach back to relay/ctl (that would be a dependency cycle).\n *\n * The predicted `GitRpcParams` built here MUST match, byte-for-byte, what the\n * in-box `agentbox-ctl git` sends, or the relay's params-hash binding rejects\n * the minted token. This mirrors `buildParams` in `packages/ctl/src/commands/git.ts`.\n */\nimport type { BoxRecord, ExecResult, GitRpcParams, Provider } from '@agentbox/core';\nimport { isScratchBranch, SCRATCH_BRANCH_PREFIX } from '@agentbox/core';\n\n/** The box workspace is always mounted here; ctl mirrors `process.cwd()` into `params.path`. */\nexport const BOX_WORKSPACE = '/workspace';\n\n/**\n * Mint a `--host-initiated-token <tok>` argv fragment bound to a git RPC's\n * `(method, params)`. Returns `[]` when no token could be minted — the call\n * still proceeds through the relay's normal prompt path (and `agentbox/*`\n * scratch pushes auto-allow with no prompt regardless).\n */\nexport type HostInitiatedArgs = (method: string, params: GitRpcParams) => Promise<string[]>;\n\nexport interface BoxGitDeps {\n hostInitiatedArgs?: HostInitiatedArgs;\n}\n\nfunction run(provider: Provider, box: BoxRecord, argv: string[]): Promise<ExecResult> {\n return provider.exec(box, argv, { cwd: BOX_WORKSPACE });\n}\n\n/** Normalize a user-supplied name to an `agentbox/<name>` scratch branch (idempotent). */\nexport function scratchBranchName(name: string): string {\n const trimmed = name.trim();\n return isScratchBranch(trimmed) ? trimmed : `${SCRATCH_BRANCH_PREFIX}${trimmed}`;\n}\n\n/** `git checkout <branch>` — switch the box's worktree. No relay: local to the worktree. */\nexport function boxGitCheckout(\n provider: Provider,\n box: BoxRecord,\n branch: string,\n extraArgs: string[] = [],\n): Promise<ExecResult> {\n return run(provider, box, ['git', 'checkout', branch, ...extraArgs]);\n}\n\n/**\n * `git checkout -b agentbox/<name> [from]` — create AND switch onto a fresh\n * scratch branch (from HEAD by default, or the given base ref). Local to the\n * worktree; for docker the branch lands in the bind-mounted host `.git/`\n * immediately, for cloud it stays in-box until pushed to the host.\n */\nexport function boxGitNewBranch(\n provider: Provider,\n box: BoxRecord,\n name: string,\n from?: string,\n): Promise<ExecResult> {\n const argv = ['git', 'checkout', '-b', scratchBranchName(name)];\n if (from && from.trim()) argv.push(from.trim());\n return run(provider, box, argv);\n}\n\n/** Build the `{ path, remote?, args? }` ctl sends for a git.push / git.fetch RPC. */\nfunction gitRpcParams(remote: string | undefined, extraArgs: string[]): GitRpcParams {\n const params: GitRpcParams = { path: BOX_WORKSPACE };\n if (remote) params.remote = remote;\n if (extraArgs.length > 0) params.args = extraArgs;\n return params;\n}\n\n/** `agentbox-ctl git push` — push the box's branch to the remote via the host relay. */\nexport async function boxGitPush(\n provider: Provider,\n box: BoxRecord,\n opts: { remote?: string; force?: boolean; args?: string[] },\n deps: BoxGitDeps = {},\n): Promise<ExecResult> {\n // `--force` is a real remote-push flag; ctl normalizes it back onto the args\n // tail, so it must be part of the predicted params hash (force last, matching\n // the host CLI).\n const extraArgs = [...(opts.args ?? []), ...(opts.force ? ['--force'] : [])];\n const params = gitRpcParams(opts.remote, extraArgs);\n const tokenArgs = deps.hostInitiatedArgs ? await deps.hostInitiatedArgs('git.push', params) : [];\n const argv = ['agentbox-ctl', 'git', 'push', ...tokenArgs];\n if (opts.remote) argv.push('--remote', opts.remote);\n argv.push(...extraArgs);\n return run(provider, box, argv);\n}\n\n/**\n * `agentbox-ctl git pull` — fetch via the relay then merge in /workspace. Only\n * `git.fetch` crosses the relay (the merge is local, no creds), so the token is\n * scoped to `git.fetch`. `--ff-only` is consumed by ctl (not forwarded to the\n * relay) so it stays out of the predicted params hash.\n */\nexport async function boxGitPull(\n provider: Provider,\n box: BoxRecord,\n opts: { remote?: string; ffOnly?: boolean; args?: string[] },\n deps: BoxGitDeps = {},\n): Promise<ExecResult> {\n const extraArgs = opts.args ?? [];\n const params = gitRpcParams(opts.remote, extraArgs);\n const tokenArgs = deps.hostInitiatedArgs ? await deps.hostInitiatedArgs('git.fetch', params) : [];\n const argv = ['agentbox-ctl', 'git', 'pull', ...tokenArgs];\n if (opts.remote) argv.push('--remote', opts.remote);\n if (opts.ffOnly) argv.push('--ff-only');\n argv.push(...extraArgs);\n return run(provider, box, argv);\n}\n\n/**\n * `agentbox-ctl git push --host-only` — land the box's branch in the host's\n * *local* repo, publishing nothing. The relay skips its confirm/token gate\n * (that gate guards remote pushes), so no host-initiated token is needed.\n */\nexport function boxGitPushHost(\n provider: Provider,\n box: BoxRecord,\n opts: { as?: string; force?: boolean; args?: string[] } = {},\n): Promise<ExecResult> {\n const argv = ['agentbox-ctl', 'git', 'push', '--host-only'];\n if (opts.as) argv.push('--as', opts.as);\n if (opts.force) argv.push('--force');\n argv.push(...(opts.args ?? []));\n return run(provider, box, argv);\n}\n\n// ── service control (in-box supervisor) ──\n// The argv is single-sourced here; parsing the `--json` StatusReply stays in the\n// callers (they can import `@agentbox/ctl`; this module can't — cycle, see above).\n\n/** `agentbox-ctl status --json` — dump the live task/service/port snapshot. */\nexport function servicesStatusArgv(): string[] {\n return ['agentbox-ctl', 'status', '--json'];\n}\n\n/** Run the live status pull and return the raw exec result (caller parses stdout). */\nexport function boxServicesStatusRaw(provider: Provider, box: BoxRecord): Promise<ExecResult> {\n return run(provider, box, servicesStatusArgv());\n}\n\n/** `agentbox-ctl restart <name>` — restart one supervised service. */\nexport function restartServiceArgv(name: string): string[] {\n return ['agentbox-ctl', 'restart', name];\n}\n\n/** Restart a single supervised service by name. */\nexport function boxRestartService(provider: Provider, box: BoxRecord, name: string): Promise<ExecResult> {\n return run(provider, box, restartServiceArgv(name));\n}\n\n/**\n * Restart every named service in sequence (host-side loop — no in-box wire op,\n * so it works on already-baked boxes). Returns each service's exec result so the\n * caller can report partial failures. Sequential (not parallel) to keep the box\n * from thrashing when services depend on one another.\n */\nexport async function boxRestartServices(\n provider: Provider,\n box: BoxRecord,\n names: string[],\n): Promise<{ name: string; result: ExecResult }[]> {\n const out: { name: string; result: ExecResult }[] = [];\n for (const name of names) {\n out.push({ name, result: await boxRestartService(provider, box, name) });\n }\n return out;\n}\n","/**\n * Shared shape for a provider health-check row, produced by each provider's\n * `doctorChecks()` and consumed by `agentbox doctor` / the install wizard, plus\n * the `ProviderModule` contract the CLI loads each `@agentbox/sandbox-<name>`\n * through.\n *\n * Lives in sandbox-core (not apps/cli) so each provider package can own its own\n * probes and login/credential surface without depending on the CLI — a new\n * provider ships all of this in its own package and the CLI dispatches to it\n * generically via a lazy `import()`.\n */\n\nimport type { CloudBackend, Provider } from '@agentbox/core';\n\n/**\n * `info` is for rows that are intentionally inert (e.g. an integration the\n * user hasn't enabled). It surfaces as a distinct glyph but rolls up like\n * `ok` so it never pushes the overall doctor status to \"warn\".\n */\nexport type CheckStatus = 'ok' | 'info' | 'warn' | 'fail';\n\nexport interface CheckResult {\n label: string;\n status: CheckStatus;\n detail: string;\n hint?: string;\n}\n\n/** Normalized credential state used by the install wizard's re-auth prompt. */\nexport interface CredStatusSummary {\n configured: boolean;\n /** Optional detail shown in the \"already configured (…)\" line (e.g. auth kind). */\n label?: string;\n}\n\n/**\n * Outcome of a non-interactive `setCredentials` call (the headless path the hub\n * drives). `status` reflects the store *after* the attempt, so a caller can\n * report `configured` without a second read.\n */\nexport interface CredSetResult {\n ok: boolean;\n /** One-line failure reason when `ok` is false (e.g. a rejected token). */\n error?: string;\n status: CredStatusSummary;\n}\n\n/**\n * The uniform surface every `@agentbox/sandbox-<name>` package exposes as\n * `export const providerModule`. The CLI's provider loader resolves this via a\n * lazy `import()` and drives create / doctor / install / checkpoint through it,\n * so adding a provider needs no per-provider `switch` arm in the CLI.\n */\nexport interface ProviderModule {\n /** The `Provider` implementation (lifecycle, exec, attach, checkpoint…). */\n provider: Provider;\n /** Cloud backend (host-side executor). Absent for the local docker provider. */\n backend?: CloudBackend;\n /**\n * First-run credential gate. Called before `create`/`claude`/etc. hand out\n * the provider. Absent for docker (no login). `force` re-runs the flow.\n */\n ensureCredentials?: (opts?: { force?: boolean }) => Promise<void>;\n /** Normalized credential state for the install wizard. Absent for docker. */\n readCredStatus?: () => Promise<CredStatusSummary> | CredStatusSummary;\n /**\n * Non-interactive credential write (the headless path a hub/API driver uses,\n * bypassing the TTY-gated `ensureCredentials` prompts). Validates the given\n * fields against the cloud, then persists them to `~/.agentbox/secrets.env`.\n * The `fields` shape is provider-specific (e.g. `{ apiKey }`, `{ token }`,\n * `{ token, teamId?, projectId? }`). Absent for docker (no login). Never\n * returns the secret values.\n */\n setCredentials?: (fields: Record<string, string>) => Promise<CredSetResult>;\n /**\n * CURRENT build-context fingerprint of the provider's base image/snapshot,\n * for staleness nagging. Absent for docker (its base self-heals).\n */\n currentBaseFingerprintLive?: (\n claudeInstall?: 'native' | 'npm',\n ) => Promise<string | undefined>;\n /** Local, offline-safe health probes for `agentbox doctor`. */\n doctorChecks: () => Promise<CheckResult[]>;\n}\n\n/** First line of a multi-line string (for compact error summaries). */\nexport function firstLine(s: string): string {\n const i = s.indexOf('\\n');\n return i === -1 ? s : s.slice(0, i);\n}\n\n/** Compact one-line summary of an unknown thrown value. */\nexport function errSummary(err: unknown): string {\n return err instanceof Error ? firstLine(err.message) : String(err);\n}\n","/**\n * Shared writer for the managed cloud-credential store at\n * `~/.agentbox/secrets.env`. Every cloud provider (`daytona`, `hetzner`,\n * `vercel`, `e2b`) persists its API keys/tokens here so the per-provider\n * env-loaders pick them up for every command. The write logic was copy-pasted\n * across four `credentials.ts` files (`writeManaged` / `persistCredentials`);\n * this consolidates it.\n *\n * The file is a plain `KEY=value` env file (optionally `export KEY=value`),\n * mode 0600, written atomically (temp + rename, atomic on the same filesystem).\n */\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, resolve } from 'node:path';\n\n/** Canonical path of the managed secrets file: `~/.agentbox/secrets.env`. */\nexport function secretsEnvPath(): string {\n return resolve(homedir(), '.agentbox', 'secrets.env');\n}\n\n/**\n * Atomically rewrite a set of managed keys in `~/.agentbox/secrets.env`: strip\n * every prior value for a `managedKeys` entry (whether written as `KEY=` or\n * `export KEY=`), then append exactly the keys in `record`. Unrelated lines the\n * user dropped in the file are preserved untouched. Also mirrors the change into\n * `process.env` — every `managedKeys` entry is cleared first, then `record` is\n * applied — so the current process uses the new values immediately (and a stale\n * alternate auth method, e.g. an old JWT when switching to an API key, is gone).\n *\n * File is written mode 0600.\n */\nexport function writeManagedSecrets(\n managedKeys: readonly string[],\n record: Record<string, string>,\n): void {\n for (const k of managedKeys) delete process.env[k];\n for (const [k, v] of Object.entries(record)) process.env[k] = v;\n\n const path = secretsEnvPath();\n mkdirSync(dirname(path), { recursive: true });\n\n let existing = '';\n if (existsSync(path)) {\n try {\n existing = readFileSync(path, 'utf8');\n } catch {\n existing = '';\n }\n }\n\n const kept = existing\n .split(/\\r?\\n/)\n .filter((line) => {\n const stripped = line.startsWith('export ') ? line.slice('export '.length) : line;\n const eq = stripped.indexOf('=');\n if (eq <= 0) return true;\n const key = stripped.slice(0, eq).trim();\n return !managedKeys.includes(key);\n })\n .join('\\n')\n .replace(/\\s+$/u, '');\n\n const lines = Object.entries(record).map(([k, v]) => `${k}=${v}`);\n const body = (kept ? `${kept}\\n` : '') + lines.join('\\n') + '\\n';\n\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, body, { mode: 0o600 });\n try {\n chmodSync(tmp, 0o600);\n } catch {\n // chmod best-effort; writeFileSync mode already covers most filesystems.\n }\n renameSync(tmp, path);\n try {\n chmodSync(path, 0o600);\n } catch {\n // ignore — already attempted on the temp file\n }\n}\n\n/**\n * Mask a secret for display: keep the first and last 4 chars, hide the middle.\n * Short values are fully masked. Never returns the raw secret.\n */\nexport function maskSecret(value: string): string {\n if (value.length <= 8) return '*'.repeat(value.length);\n return `${value.slice(0, 4)}…${'*'.repeat(8)}${value.slice(-4)}`;\n}\n","/**\n * The external-provider plugin registry: `~/.agentbox/plugins.json`.\n *\n * A community provider ships as its own npm package (`agentbox-provider-<name>`)\n * built against `@madarco/agentbox-provider-sdk`. The user installs it themselves, then\n * `agentbox plugin add <pkg>` validates it and records it here; the CLI and the\n * host relay both read this file to resolve + lazily `import()` the package at\n * runtime (a true variable specifier — built-ins are bundle-inlined, external\n * providers are not).\n *\n * Concurrency + durability mirror `state.ts`: an O_EXCL lockfile guards the\n * read-modify-write, and writes are atomic (temp + rename). Reads have a sync\n * variant so the CLI's synchronous `isKnownProvider`/name-list checks can\n * consult it without going async.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\n\nexport const PLUGINS_FILE = join(homedir(), '.agentbox', 'plugins.json');\n\n/**\n * `SDK_API_VERSION` majors this CLI can load. A plugin built against an SDK\n * whose major is not listed is refused at `plugin add` and skipped at load\n * (with a warning) rather than crashing the CLI. Extend this array when the CLI\n * keeps back-compat with an older provider contract.\n */\n// v2: BoxRecord.cloud.ssh moved to top-level BoxRecord.ssh (+port, docker sshd\n// fields). v1 plugins still load — only ones reading box.cloud.ssh notice.\nexport const SUPPORTED_SDK_API_VERSIONS: readonly number[] = [1, 2];\n\nexport function isSupportedApiVersion(v: number): boolean {\n return SUPPORTED_SDK_API_VERSIONS.includes(v);\n}\n\n/** One registered external provider package. */\nexport interface PluginRecord {\n /** Package name as installed (e.g. `agentbox-provider-digitalocean`). */\n packageName: string;\n /** Absolute path to the package's resolved entry module, recorded at add time. */\n resolvedEntry: string;\n /** Package version at add time (informational). */\n version: string;\n /** Provider names this package contributes (from each `providerModule.provider.name`). */\n providers: string[];\n /** `SDK_API_VERSION` the package declared (compat gate). */\n apiVersion: number;\n /** ISO timestamp the package was added. */\n addedAt: string;\n}\n\nexport interface PluginsFile {\n version: 1;\n plugins: PluginRecord[];\n}\n\nconst EMPTY: PluginsFile = { version: 1, plugins: [] };\n\nconst LOCK_STALE_MS = 15_000;\nconst LOCK_ACQUIRE_TIMEOUT_MS = 20_000;\nconst LOCK_RETRY_MS = 25;\n\n/** Exclusive cross-process lock around `${path}.lock` (mirrors state.ts). */\nasync function withFileLock<T>(path: string, fn: () => Promise<T>): Promise<T> {\n const lockPath = `${path}.lock`;\n await mkdir(dirname(path), { recursive: true });\n const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS;\n let held = false;\n while (!held) {\n try {\n const fh = await open(lockPath, 'wx');\n await fh.writeFile(`${String(process.pid)}\\n`);\n await fh.close();\n held = true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;\n try {\n const st = await stat(lockPath);\n if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {\n await rm(lockPath, { force: true });\n continue;\n }\n } catch {\n continue;\n }\n if (Date.now() >= deadline) break;\n await delay(LOCK_RETRY_MS);\n }\n }\n try {\n return await fn();\n } finally {\n if (held) await rm(lockPath, { force: true }).catch(() => {});\n }\n}\n\nfunction normalize(raw: unknown): PluginsFile {\n const parsed = raw as PluginsFile;\n if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.plugins)) {\n // Unrecognized shape → treat as empty (a fresh registry), never throw:\n // a corrupt plugins.json must not brick every CLI command.\n return { ...EMPTY };\n }\n return parsed;\n}\n\n/** Synchronous read for the CLI's sync name-list / validation checks. Missing file → empty. */\nexport function readPluginRegistrySync(path: string = PLUGINS_FILE): PluginsFile {\n try {\n if (!existsSync(path)) return { ...EMPTY };\n return normalize(JSON.parse(readFileSync(path, 'utf8')));\n } catch {\n return { ...EMPTY };\n }\n}\n\nexport async function readPluginRegistry(path: string = PLUGINS_FILE): Promise<PluginsFile> {\n try {\n return normalize(JSON.parse(await readFile(path, 'utf8')));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { ...EMPTY };\n return { ...EMPTY };\n }\n}\n\n/**\n * Read for a read-modify-WRITE. Unlike the lenient readers (which degrade a\n * corrupt file to empty so the CLI never bricks), this REFUSES to proceed when\n * an existing file is unparseable/unrecognized — otherwise `addPluginRecord`\n * would overwrite a recoverable `plugins.json` and silently drop every other\n * registered plugin. A genuinely missing file (ENOENT) is still an empty start.\n */\nasync function readForWrite(path: string): Promise<PluginsFile> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { ...EMPTY };\n throw err;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new Error(\n `refusing to modify a corrupt plugin registry at ${path} (${(err as Error).message}) — fix or delete the file and retry.`,\n );\n }\n const p = parsed as PluginsFile;\n if (!p || p.version !== 1 || !Array.isArray(p.plugins)) {\n throw new Error(\n `refusing to modify an unrecognized plugin registry at ${path} — fix or delete the file and retry.`,\n );\n }\n return p;\n}\n\nasync function writeRegistry(file: PluginsFile, path: string = PLUGINS_FILE): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const tmp = `${path}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, JSON.stringify(file, null, 2) + '\\n', 'utf8');\n await rename(tmp, path);\n}\n\n/** Upsert a plugin by `packageName` (idempotent re-add updates the record). */\nexport async function addPluginRecord(\n record: PluginRecord,\n path: string = PLUGINS_FILE,\n): Promise<void> {\n await withFileLock(path, async () => {\n const file = await readForWrite(path);\n const next = file.plugins.filter((p) => p.packageName !== record.packageName);\n next.push(record);\n await writeRegistry({ version: 1, plugins: next }, path);\n });\n}\n\n/**\n * Remove a plugin by package name OR by a provider name it contributes.\n * Returns the removed record(s) count.\n */\nexport async function removePluginRecord(\n nameOrPackage: string,\n path: string = PLUGINS_FILE,\n): Promise<number> {\n let removed = 0;\n await withFileLock(path, async () => {\n const file = await readForWrite(path);\n const next = file.plugins.filter((p) => {\n const match = p.packageName === nameOrPackage || p.providers.includes(nameOrPackage);\n if (match) removed += 1;\n return !match;\n });\n await writeRegistry({ version: 1, plugins: next }, path);\n });\n return removed;\n}\n\n/** All provider names contributed by registered plugins (sync). */\nexport function pluginProviderNames(path: string = PLUGINS_FILE): string[] {\n return readPluginRegistrySync(path).plugins.flatMap((p) => p.providers);\n}\n\n/** The plugin record that contributes `providerName`, or null (sync). */\nexport function pluginForProvider(\n providerName: string,\n path: string = PLUGINS_FILE,\n): PluginRecord | null {\n return (\n readPluginRegistrySync(path).plugins.find((p) => p.providers.includes(providerName)) ?? null\n );\n}\n","import { mkdtemp, readFile, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, join } from 'node:path';\nimport { applyReplacements, deriveBoxHost, type ResolvedCarryEntry } from '@agentbox/core';\n\n/**\n * Box facts used to fill `{{AGENTBOX_*}}` placeholders in carried files. The\n * placeholder *names* match the in-box `agentbox-ctl render` whitelist; here the\n * values come from the create context (the box is named but not yet booted).\n */\nexport interface CarryBoxContext {\n name?: string;\n id?: string;\n kind?: string;\n /** Host workspace path (mirrors in-box AGENTBOX_HOST_WORKSPACE). */\n hostWorkspace?: string;\n projectRoot?: string;\n}\n\n/** Build the whitelist placeholder context (and derive AGENTBOX_BOX_HOST). */\nexport function carryPlaceholderContext(ctx: CarryBoxContext): Record<string, string> {\n const out: Record<string, string> = {};\n if (ctx.name) out.AGENTBOX_BOX_NAME = ctx.name;\n if (ctx.id) out.AGENTBOX_BOX_ID = ctx.id;\n if (ctx.kind) out.AGENTBOX_BOX_KIND = ctx.kind;\n if (ctx.hostWorkspace) out.AGENTBOX_HOST_WORKSPACE = ctx.hostWorkspace;\n if (ctx.projectRoot) out.AGENTBOX_PROJECT_ROOT = ctx.projectRoot;\n return deriveBoxHost(out);\n}\n\n/** Whether an entry opts into host-side rendering (file entries only). */\nfunction wantsRender(e: ResolvedCarryEntry): boolean {\n return e.kind === 'file' && (!!e.replaceEnvs || (e.replace?.length ?? 0) > 0);\n}\n\n/**\n * Render carry entries that opt into `replaceEnvs`/`replace`: read each file\n * host-side, apply the substitutions, write the result to a temp file, and\n * repoint `absSrc` at it so the existing per-provider tar/copy step transfers\n * the rendered content. Entries without replace options pass through unchanged.\n * Returns a new array (inputs are not mutated).\n */\nexport async function renderCarryEntries(\n entries: ResolvedCarryEntry[],\n ctx: CarryBoxContext,\n onLog?: (line: string) => void,\n): Promise<ResolvedCarryEntry[]> {\n if (!entries.some(wantsRender)) return entries;\n\n const context = carryPlaceholderContext(ctx);\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-carry-render-'));\n const out: ResolvedCarryEntry[] = [];\n for (const [i, entry] of entries.entries()) {\n if (!wantsRender(entry)) {\n out.push(entry);\n continue;\n }\n const content = await readFile(entry.absSrc, 'utf8');\n const rendered = applyReplacements(content, {\n env: entry.replaceEnvs,\n rules: entry.replace,\n context,\n onWarn: (msg) => onLog?.(`carry: ${entry.rawSrc}: ${msg}`),\n });\n const tmp = join(stage, `${String(i)}-${basename(entry.absSrc)}`);\n await writeFile(tmp, rendered, 'utf8');\n out.push({ ...entry, absSrc: tmp, bytes: Buffer.byteLength(rendered) });\n const what = [\n ...(entry.replaceEnvs ? ['env'] : []),\n ...(entry.replace?.length ? [`${String(entry.replace.length)} rule(s)`] : []),\n ].join('+');\n onLog?.(`carry: rendered ${entry.rawSrc} (${what})`);\n }\n return out;\n}\n","/**\n * `RecordingSyncTransport` — the parity net for the sync refactor. Every concern\n * module is a pure function of `(ctx, transport, …)`, so a concern's entire\n * observable effect IS its ordered sequence of transport calls. This fake\n * `SyncTransport` records that sequence deterministically — no host FS, no git,\n * no relay, no docker, no randomness — so a concern can be golden-snapshotted\n * and a refactor that changes what we emit fails the snapshot.\n *\n * Mirrors the `MockCloudBackend` (`@agentbox/sandbox-cloud`) pattern: a\n * reference double shipped in `src/` and driven by tests.\n */\n\nimport type {\n PushOptions,\n SyncExecOptions,\n SyncExecResult,\n SyncTransport,\n TransportCaps,\n VolumeHostSource,\n} from '@agentbox/core';\n\n/** One recorded transport call, in invocation order. */\nexport interface RecordedOp {\n op:\n | 'exec'\n | 'applyTarball'\n | 'pushTree'\n | 'pushFile'\n | 'pullTree'\n | 'pullFile'\n | 'readText'\n | 'ensureVolume'\n | 'seedVolumeFromHost';\n /** Normalized, snapshot-stable arguments for this call. */\n args: Record<string, unknown>;\n}\n\nexport interface RecordingTransportOptions {\n /** Override capability flags (default: docker-like). */\n caps?: Partial<TransportCaps>;\n /**\n * Whether the volume primitives are present. Default true (docker-like). Set\n * false to model an ephemeral cloud backend (no `ensureVolume` /\n * `seedVolumeFromHost`), so a concern that feature-detects them takes the\n * push-every-create branch.\n */\n withVolumes?: boolean;\n /** Canned `exec` result. Default `{ exitCode: 0, stdout: '', stderr: '' }`. */\n execResult?: (cmd: string[], opts?: SyncExecOptions) => SyncExecResult;\n /** Canned `readText` responses keyed by box path. Default: null (absent). */\n readText?: (boxPath: string) => string | null;\n}\n\nexport interface RecordingSyncTransport extends SyncTransport {\n /** Recorded calls in invocation order. */\n readonly ops: ReadonlyArray<RecordedOp>;\n /** Drop the recorded ops (between assertions in one test). */\n clear(): void;\n}\n\nconst DEFAULT_CAPS: TransportCaps = {\n persistentVolumes: true,\n helperContainer: true,\n ephemeralFs: false,\n};\n\nexport function makeRecordingTransport(\n opts: RecordingTransportOptions = {},\n): RecordingSyncTransport {\n const ops: RecordedOp[] = [];\n const caps: TransportCaps = { ...DEFAULT_CAPS, ...opts.caps };\n const withVolumes = opts.withVolumes ?? true;\n const push = (op: RecordedOp['op'], args: Record<string, unknown>) => ops.push({ op, args });\n\n const base: SyncTransport = {\n caps,\n async exec(cmd: string[], execOpts?: SyncExecOptions): Promise<SyncExecResult> {\n push('exec', { cmd, opts: execOpts });\n return opts.execResult?.(cmd, execOpts) ?? { exitCode: 0, stdout: '', stderr: '' };\n },\n async applyTarball(hostTarPath: string, boxDestDir: string, o?: PushOptions): Promise<void> {\n push('applyTarball', { hostTarPath, boxDestDir, opts: o });\n },\n async pushTree(hostSrcDir: string, boxDestDir: string, o?: PushOptions): Promise<void> {\n push('pushTree', { hostSrcDir, boxDestDir, opts: o });\n },\n async pushFile(hostSrcPath: string, boxDestPath: string, o?: PushOptions): Promise<void> {\n push('pushFile', { hostSrcPath, boxDestPath, opts: o });\n },\n async pullTree(boxSrcDir: string, hostDestDir: string, o?: { exclude?: string[] }): Promise<void> {\n push('pullTree', { boxSrcDir, hostDestDir, opts: o });\n },\n async pullFile(boxSrcPath: string, hostDestPath: string): Promise<void> {\n push('pullFile', { boxSrcPath, hostDestPath });\n },\n async readText(boxPath: string): Promise<string | null> {\n push('readText', { boxPath });\n return opts.readText?.(boxPath) ?? null;\n },\n };\n\n if (withVolumes) {\n base.ensureVolume = async (name: string): Promise<{ volumeId: string }> => {\n push('ensureVolume', { name });\n return { volumeId: `vol-${name}` };\n };\n base.seedVolumeFromHost = async (volume: string, sources: VolumeHostSource[]): Promise<void> => {\n push('seedVolumeFromHost', { volume, sources });\n };\n }\n\n return {\n ...base,\n get ops() {\n return ops;\n },\n clear(): void {\n ops.length = 0;\n },\n };\n}\n","/**\n * The per-tool sync registry. `AGENT_SYNC_SPECS` is the data-driven table the\n * driver and both providers iterate instead of hardcoding three per-tool blocks\n * (`sandbox-docker/create.ts:623-763`, `sandbox-cloud/cloud-provider.ts:705-819`).\n *\n * Values here are the single source of truth mirrored by the docker constants\n * (`SHARED_*_VOLUME`, `*_FORWARDED_ENV_KEYS`, `*_CREDENTIALS_BACKUP_FILE`) and\n * the cloud `AGENT_SPECS`; a cross-check test in `@agentbox/sandbox-cloud`\n * (which can see both packages) guards against drift until those constants are\n * re-exported from here.\n */\n\nimport { join } from 'node:path';\nimport { STATE_DIR } from '../state.js';\nimport type { AgentId, AgentSyncSpec } from './agents/types.js';\n\nconst CLAUDE_BOX_DIR = '/home/vscode/.claude';\nconst CODEX_BOX_DIR = '/home/vscode/.codex';\nconst OPENCODE_BOX_DIR = '/home/vscode/.local/share/opencode';\n\nexport const AGENT_SYNC_SPECS: readonly AgentSyncSpec[] = [\n {\n id: 'claude',\n aliases: ['claude-code'],\n sessionName: 'claude',\n dockerVolume: 'agentbox-claude-config',\n staticPaths: [\n {\n hostHomeRel: ['.claude'],\n boxDir: CLAUDE_BOX_DIR,\n // Static-stage excludes (single source of truth; consumed by\n // `host-stage.ts:stageClaudeStaticForUpload`). `node_modules` drops\n // host-platform binaries; `.credentials.json` ships separately; the\n // rest is per-machine runtime/history state the in-box claude\n // regenerates (`workflows` is seeded per-box at create time, not baked).\n exclude: [\n 'node_modules',\n '.credentials.json',\n 'projects',\n 'workflows',\n 'sessions',\n 'history.jsonl',\n 'file-history',\n 'shell-snapshots',\n 'backups',\n 'session-env',\n 'paste-cache',\n 'cache',\n 'telemetry',\n 'tasks',\n 'downloads',\n 'chrome',\n 'ide',\n 'debug',\n 'mcp-needs-auth-cache.json',\n 'stats-cache.json',\n ],\n },\n ],\n credential: {\n boxRelPath: '.credentials.json',\n boxAbsPath: `${CLAUDE_BOX_DIR}/.credentials.json`,\n hostBackup: join(STATE_DIR, 'claude-credentials.json'),\n cloudMountPath: '/home/vscode/.agentbox-creds/claude',\n cloudSubpath: 'claude/',\n realShape: 'claude-oauth',\n },\n forwardedEnvKeys: [\n 'ANTHROPIC_API_KEY',\n 'CLAUDE_CODE_OAUTH_TOKEN',\n 'CLAUDE_EFFORT',\n 'ANTHROPIC_MODEL',\n ],\n boxRunEnv: () => ({}),\n caps: { resume: true, teleport: 'full', activitySource: 'scraper' },\n },\n {\n id: 'codex',\n aliases: [],\n sessionName: 'codex',\n dockerVolume: 'agentbox-codex-config',\n staticPaths: [\n {\n hostHomeRel: ['.codex'],\n boxDir: CODEX_BOX_DIR,\n // Static-stage excludes (single source of truth; consumed by\n // `host-stage.ts:stageCodexStaticForUpload`). `auth.json` ships\n // separately; `state_*.sqlite*` is the resume-cwd index (rebuilt in-box);\n // `packages`/`plugins/.plugin-appserver`/`computer-use` are heavy\n // macOS-only artifacts; the rest is host-only session/log/cache state.\n exclude: [\n 'auth.json',\n 'sessions',\n 'log',\n 'history.jsonl',\n 'hooks.json',\n 'state_*.sqlite*',\n 'logs_*.sqlite*',\n 'external_agent_session_imports.json',\n 'sqlite',\n 'cache',\n 'vendor_imports',\n 'tmp',\n '.tmp',\n '.codex-global-state.json',\n '.codex-global-state.json.bak',\n '.personality_migration',\n 'shell_snapshots',\n 'session_index.jsonl',\n 'models_cache.json',\n 'installation_id',\n 'version.json',\n 'packages',\n 'plugins/.plugin-appserver',\n 'computer-use',\n 'archived_sessions',\n ],\n },\n ],\n credential: {\n boxRelPath: 'auth.json',\n boxAbsPath: `${CODEX_BOX_DIR}/auth.json`,\n hostBackup: join(STATE_DIR, 'codex-credentials.json'),\n cloudMountPath: '/home/vscode/.agentbox-creds/codex',\n cloudSubpath: 'codex/',\n realShape: 'nonempty-json',\n },\n forwardedEnvKeys: ['OPENAI_API_KEY'],\n boxRunEnv: () => ({}),\n caps: { resume: true, teleport: 'full', activitySource: 'scraper' },\n },\n {\n id: 'opencode',\n aliases: [],\n sessionName: 'opencode',\n dockerVolume: 'agentbox-opencode-config',\n // The three-XDG-dir layout as DATA: the generic seed loop reproduces\n // `ensureOpencodeVolume`'s three-source rsync (data + config→config +\n // state→.state/opencode newest-wins) with no tool-specific control flow.\n staticPaths: [\n {\n hostHomeRel: ['.local', 'share', 'opencode'],\n boxDir: OPENCODE_BOX_DIR,\n // Static-stage excludes for the data tree (single source of truth;\n // consumed by `host-stage.ts:stageOpencodeStaticForUpload`). `auth.json`\n // ships separately; the rest is host-only runtime state.\n exclude: [\n 'auth.json',\n 'storage',\n 'log',\n 'project',\n 'cache',\n 'bin',\n 'repos',\n 'snapshot',\n 'config',\n 'opencode.db',\n 'opencode.db-shm',\n 'opencode.db-wal',\n ],\n },\n { hostHomeRel: ['.config', 'opencode'], boxDir: OPENCODE_BOX_DIR, relocToSubpath: 'config' },\n {\n hostHomeRel: ['.local', 'state', 'opencode'],\n boxDir: OPENCODE_BOX_DIR,\n relocToSubpath: '.state/opencode',\n update: true,\n exclude: ['locks'],\n },\n ],\n credential: {\n boxRelPath: 'auth.json',\n boxAbsPath: `${OPENCODE_BOX_DIR}/auth.json`,\n hostBackup: join(STATE_DIR, 'opencode-credentials.json'),\n cloudMountPath: '/home/vscode/.agentbox-creds/opencode',\n cloudSubpath: 'opencode/',\n realShape: 'nonempty-json',\n },\n forwardedEnvKeys: [\n 'ANTHROPIC_API_KEY',\n 'OPENAI_API_KEY',\n 'OPENROUTER_API_KEY',\n 'GEMINI_API_KEY',\n 'GOOGLE_GENERATIVE_AI_API_KEY',\n 'GOOGLE_API_KEY',\n 'GROQ_API_KEY',\n ],\n boxRunEnv: () => ({\n OPENCODE_CONFIG_DIR: `${OPENCODE_BOX_DIR}/config`,\n XDG_STATE_HOME: `${OPENCODE_BOX_DIR}/.state`,\n }),\n caps: { resume: false, teleport: 'stub', activitySource: 'plugin' },\n },\n];\n\n/** Resolve a spec by canonical id or any alias (e.g. `'claude-code'` → the claude spec). */\nexport function resolveAgentSpec(name: string): AgentSyncSpec {\n const spec = AGENT_SYNC_SPECS.find((s) => s.id === name || s.aliases.includes(name));\n if (!spec) throw new Error(`no agent sync spec for '${name}'`);\n return spec;\n}\n\n/** The canonical ids, in registry order. */\nexport function agentIds(): AgentId[] {\n return AGENT_SYNC_SPECS.map((s) => s.id);\n}\n","/**\n * `SyncContext` — the runtime values a concern needs that aren't the transport\n * or its per-call plan. Assembled once by the provider (docker/cloud) at create\n * or session-start and threaded through every concern, so concern signatures\n * stay `(ctx, transport, plan?)`.\n *\n * The interface itself is a Tier-1 contract that lives in `@agentbox/core` (so\n * the `ProviderSync` facade there can also name it); it's re-exported here so\n * existing `@agentbox/sandbox-core` importers are unchanged. The builder\n * `makeSyncContext` stays here — it defaults `hostHome` to the OS home dir.\n */\n\nimport { homedir } from 'node:os';\nimport type { SyncContext } from '@agentbox/core';\n\nexport type { SyncContext } from '@agentbox/core';\n\nexport interface SyncContextInit {\n boxName: string;\n boxId: string;\n provider: 'docker' | 'cloud';\n hostWorkspace: string;\n projectRoot?: string;\n boxWorkspace?: string;\n hostHome?: string;\n onLog?: (line: string) => void;\n}\n\n/** Build a `SyncContext` with the conventional defaults filled in. */\nexport function makeSyncContext(init: SyncContextInit): SyncContext {\n return {\n boxName: init.boxName,\n boxId: init.boxId,\n provider: init.provider,\n hostWorkspace: init.hostWorkspace,\n projectRoot: init.projectRoot ?? init.hostWorkspace,\n boxWorkspace: init.boxWorkspace ?? '/workspace',\n hostHome: init.hostHome ?? homedir(),\n onLog: init.onLog ?? (() => {}),\n };\n}\n","/**\n * Concern: env/config files (`.env`, `secrets.toml`, `agentbox.yaml`, …) copied\n * host→box into `/workspace` at create, gitignore-bypassing.\n *\n * Unifies docker `copyHostEnvFilesToBox` (`sandbox-docker/host-export.ts`) and\n * cloud `uploadEnvFiles` (`sandbox-cloud/env-files.ts`): the host-side `find` +\n * `tar --null -T -` pack is identical across providers and lives here; the only\n * difference — how the tarball is extracted into the box — is the transport's\n * `applyTarball`. Both providers now delegate here, injecting their transport.\n *\n * Best-effort: a scan/pack failure or empty match set logs and returns the count\n * rather than throwing — a missing optional secret must not abort a healthy box.\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 { SyncTransport } from '@agentbox/core';\nimport type { SyncContext } from '../context.js';\n\n/**\n * Default env/config file basename globs. These are almost always gitignored,\n * so a normal gitignore-aware pull skips them; this list opts them back in.\n * `agentbox.yaml` is included so an in-box `/agentbox-setup`-generated file\n * lands on the host even before it's committed.\n */\nexport const DEFAULT_ENV_PATTERNS = [\n '.env',\n '.env.*',\n '.envrc',\n '.dev.vars',\n 'secrets.toml',\n 'local.settings.json',\n 'appsettings.*.json',\n 'agentbox.yaml',\n];\n\n/** Directories the env-file `find` prunes — heavy or never-relevant. */\nexport const ENV_PRUNE_DIRS = [\n 'node_modules',\n '.git',\n '.venv',\n 'venv',\n '__pycache__',\n 'dist',\n '.next',\n 'build',\n];\n\nfunction nameGroup(names: string[]): string[] {\n const out: string[] = [];\n names.forEach((n, i) => {\n if (i > 0) out.push('-o');\n out.push('-name', n);\n });\n return out;\n}\n\n/**\n * Host-side `find` argv enumerating env/config files by basename glob, pruning\n * `ENV_PRUNE_DIRS`. Rooted at `.` (run with cwd = the host workspace) with\n * `-print0` (BSD `find` on macOS has no `-printf`); `./relpath` entries feed\n * `tar -C <workspace> --null -T -` directly.\n */\nexport function buildHostEnvFindArgs(patterns: string[]): string[] {\n return [\n 'find',\n '.',\n '(',\n '-type',\n 'd',\n '(',\n ...nameGroup(ENV_PRUNE_DIRS),\n ')',\n '-prune',\n ')',\n '-o',\n '(',\n '-type',\n 'f',\n '(',\n ...nameGroup(patterns),\n ')',\n '-print0',\n ')',\n ];\n}\n\n/**\n * Raw `find` output relative to `workspaceDir` — `./relpath` entries, NUL-split,\n * NO `./` stripping. This is what feeds `tar -C <workspaceDir> --null -T -`\n * (which handles `./relpath` directly), so `pushEnvFiles` uses it verbatim to\n * stay byte-identical to the pre-refactor copy. Empty on a scan failure or empty\n * pattern set (best-effort).\n */\nasync function findEnvFilesForTar(workspaceDir: string, patterns: string[]): Promise<string[]> {\n if (patterns.length === 0) return [];\n const found = await execa('find', buildHostEnvFindArgs(patterns).slice(1), {\n cwd: workspaceDir,\n reject: false,\n });\n if (found.exitCode !== 0) return [];\n return String(found.stdout)\n .split('\\0')\n .filter((p) => p.length > 0);\n}\n\n/**\n * Run `buildHostEnvFindArgs` against `workspaceDir` and return the matched\n * relative paths with the leading `./` stripped — the display/preview form used\n * by the setup wizard's multiselect. Pure host-side helper (no box mutation).\n * Empty on a scan failure or empty pattern set (best-effort).\n */\nexport async function scanHostEnvFiles(workspaceDir: string, patterns: string[]): Promise<string[]> {\n const raw = await findEnvFilesForTar(workspaceDir, patterns);\n return raw.map((p) => p.replace(/^\\.\\//, '')).filter((p) => p.length > 0);\n}\n\nexport interface PushEnvFilesResult {\n /** Number of files written into the box. 0 when nothing matched. */\n copied: number;\n}\n\n/**\n * Copy the host's env/config files (selected by `patterns`) into the box's\n * `/workspace`, gitignore-bypassing. Files land owned by uid 1000 (`vscode`).\n */\nexport async function pushEnvFiles(\n ctx: SyncContext,\n transport: SyncTransport,\n patterns: string[],\n): Promise<PushEnvFilesResult> {\n const list = await findEnvFilesForTar(ctx.hostWorkspace, patterns);\n if (list.length === 0) return { copied: 0 };\n\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-envfiles-'));\n const localTar = join(stage, 'envfiles.tar');\n try {\n const packed = await execa(\n 'tar',\n ['-C', ctx.hostWorkspace, '--null', '-T', '-', '-cf', localTar],\n { input: list.join('\\0'), reject: false },\n );\n if (packed.exitCode !== 0) {\n ctx.onLog(`warning: env-file tar pack failed: ${String(packed.stderr).slice(0, 300)}`);\n return { copied: 0 };\n }\n try {\n await transport.applyTarball(localTar, ctx.boxWorkspace, { uid: 1000 });\n } catch (err) {\n ctx.onLog(\n `warning: env-file copy into box failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n return { copied: 0 };\n }\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n return { copied: list.length };\n}\n","/**\n * Concern: files (`carry:` block from `agentbox.yaml`) copied host→box to\n * declared destinations that may live anywhere in the box (not constrained to\n * /workspace).\n *\n * carry is the most provider-divergent concern, so this module deliberately\n * unifies only the *decision* logic — the pure `planCarryEntry` below — and\n * leaves each provider's *apply* mechanism byte-identical:\n * - docker `copyOneEntry` (`sandbox-docker/host-export.ts`): `streamTarPipe`\n * (stdin, no temp file) + separate `docker exec --user 0:0` calls.\n * - cloud `uploadOneEntry` (`sandbox-cloud/carry.ts`): a staged temp tar +\n * `uploadFile` + ONE combined bash command (splitting/nesting it reintroduces\n * a Vercel `$(...)`/`while` hang — see the note in that file).\n *\n * Both apply paths share the same up-front decisions (`~/`→`/home/vscode`\n * expansion, file-vs-dir, exclude, uid/mode defaults, rename-needed,\n * parent-chain-needed). Those live here so the two providers can't drift.\n */\n\nimport type { ResolvedCarryEntry } from '@agentbox/core';\n\n/** Hardcoded in-box home — boxes always run as the `vscode` user (uid 1000). */\nexport const BOX_HOME = '/home/vscode';\n\n/** dirname() that always uses '/' regardless of host OS (the box is linux). */\nexport function dirnameUnix(p: string): string {\n const i = p.lastIndexOf('/');\n if (i <= 0) return '/';\n return p.slice(0, i);\n}\n\n/** basename() that always uses '/' regardless of host OS (the box is linux). */\nexport function basenameUnix(p: string): string {\n const i = p.lastIndexOf('/');\n return i < 0 ? p : p.slice(i + 1);\n}\n\n/**\n * The shared, byte-for-byte carry decisions both providers apply. Everything\n * here is a pure function of the entry; nothing touches the host FS or the box.\n */\nexport interface CarryPlan {\n /** `absDest` with `~/` expanded to `/home/vscode` (host-side, never in-box). */\n boxDest: string;\n /** True for a `dir` entry, false for a `file` entry. */\n isDir: boolean;\n /**\n * Dir to `mkdir -p` before extracting: the dest itself for a dir, the dest's\n * parent for a file. Trailing slashes on the dest are stripped first.\n */\n parentDir: string;\n /** tar `--exclude` patterns (dir entries only; empty for files). */\n exclude: string[];\n /** chown target uid:uid inside the box. Default 1000 (`vscode`); 0 = root. */\n uid: number;\n /** Zero-padded octal `chmod -R` arg, or undefined when no mode is set. */\n mode?: string;\n /** Source basename inside the packed tar (file entries only; '' for dirs). */\n fileBase: string;\n /** Dest basename (file entries only; '' for dirs). */\n destBase: string;\n /** File dest basename differs from the source → `mv` after extract. */\n renameNeeded: boolean;\n /**\n * Dest is under `$HOME` with a non-`$HOME` immediate parent, so the\n * root-created parent chain must be chowned back to `uid`. System paths\n * (`/etc/*`, …) are left untouched.\n */\n parentChainNeeded: boolean;\n}\n\n/**\n * Compute the shared carry decisions for one entry. Returns `null` for a\n * `missing` (optional + absent-on-host) entry, which both providers skip.\n */\nexport function planCarryEntry(entry: ResolvedCarryEntry): CarryPlan | null {\n if (entry.kind === 'missing') return null;\n\n // ~/ expands to /home/vscode at this layer (host-side), NOT inside the box's\n // shell — so we never depend on the executing user's $HOME (which is /root\n // when the docker path runs `--user 0:0`).\n const boxDest = entry.absDest.startsWith('~/')\n ? `${BOX_HOME}/${entry.absDest.slice(2)}`\n : entry.absDest;\n const boxDestNoSlash = boxDest.endsWith('/') ? boxDest.slice(0, -1) : boxDest;\n\n const isDir = entry.kind === 'dir';\n const parentDir = isDir ? boxDestNoSlash : dirnameUnix(boxDestNoSlash);\n const exclude = isDir ? (entry.exclude ?? []) : [];\n // Default uid 1000 (in-box vscode); explicit `user: 0` lands root:root.\n const uid = entry.user ?? 1000;\n const mode = entry.mode !== undefined ? entry.mode.toString(8).padStart(4, '0') : undefined;\n\n const fileBase = isDir ? '' : basenameUnix(entry.absSrc);\n const destBase = isDir ? '' : basenameUnix(boxDest);\n const renameNeeded = !isDir && fileBase !== destBase;\n\n // `mkdir -p` runs as root, so any new dirs between $HOME and dirname(dest) are\n // root-owned. Only walk when the dest is under $HOME — system paths keep their\n // existing ownership.\n const parentChainNeeded =\n boxDest.startsWith(`${BOX_HOME}/`) && dirnameUnix(boxDest) !== BOX_HOME;\n\n return {\n boxDest,\n isDir,\n parentDir,\n exclude,\n uid,\n mode,\n fileBase,\n destBase,\n renameNeeded,\n parentChainNeeded,\n };\n}\n","/**\n * Claude-specific host/box path helpers, shared by every provider's sync layer.\n *\n * Moved here (from `@agentbox/sandbox-docker`'s `host-stage.ts`) so the cloud\n * dynamic-sync path can reuse them without importing the docker package — the\n * dependency leak the sync refactor closes. `host-stage.ts` re-exports these for\n * its existing importers, so nothing else moves.\n */\n\nimport { readdir, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Claude Code keys per-project state (memory, sessions, history) under\n * `~/.claude/projects/<encoded>/`, where `<encoded>` is the project's absolute\n * path with every non-alphanumeric char replaced by `-`. Inside every box the\n * workspace is `/workspace`, so its key is always `-workspace`. We duplicate\n * the rule here (rather than importing apps/cli's `encodeClaudeProjectsDir`)\n * because the sync layer must not depend on the CLI package.\n */\nexport function encodeClaudeProjectsKey(absPath: string): string {\n return absPath.replace(/[^a-zA-Z0-9]/g, '-');\n}\n\n/** In-box Claude project dir for `/workspace` (fixed for every box). */\nexport const BOX_CLAUDE_PROJECT_DIR = '/home/vscode/.claude/projects/-workspace';\n\n/**\n * Resolve the host's `~/.claude/projects/<encode(hostWorkspace)>/memory` dir,\n * or `null` when it's absent or empty (so callers no-op rather than seed an\n * empty tree). `hostHome` is overridable for tests.\n */\nexport async function resolveClaudeMemoryDir(\n hostWorkspace: string,\n hostHome: string = homedir(),\n): Promise<string | null> {\n if (hostWorkspace.length === 0) return null;\n const memDir = join(\n hostHome,\n '.claude',\n 'projects',\n encodeClaudeProjectsKey(hostWorkspace),\n 'memory',\n );\n if (!(await pathExists(memDir))) return null;\n try {\n const entries = await readdir(memDir);\n if (entries.length === 0) return null;\n } catch {\n return null;\n }\n return memDir;\n}\n","/**\n * Host-side symlink pre-scan shared by the skills/agents-volume seed and the\n * claude static stage. Pure filesystem inspection (no docker, no box), so it\n * lives in the sync layer and both providers reuse it. Moved here from\n * `@agentbox/sandbox-docker`'s `claude.ts`, which re-exports it for its existing\n * importers.\n */\n\nimport { readdir, realpath, stat } from 'node:fs/promises';\nimport { isAbsolute, join, relative } from 'node:path';\n\nfunction isUnder(parent: string, child: string): boolean {\n const rel = relative(parent, child);\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));\n}\n\n/**\n * Walk `root` and return rsync-style relative paths of every symlink the\n * in-container sync can't dereference, so we can `--exclude` them. Two cases\n * abort the whole sync under `--copy-unsafe-links` if left in:\n *\n * - Broken on the host (e.g. claude's `debug/latest` once an older debug file\n * is reaped).\n * - Valid on the host but pointing OUTSIDE the trees the helper container\n * mounts (`reachableRoots`: `~/.claude` itself and, when present, `~/.agents`\n * at `/.agents`). The referent then has \"no referent\" inside the box — e.g. a\n * dev's `~/.claude/skills/*` symlinked into an agentbox source checkout.\n *\n * A symlinked directory whose target IS reachable can still hide an unsyncable\n * link one level down: `~/.claude/skills/<name>` -> `~/.agents/skills/<name>`\n * (reachable) whose `SKILL.md` is an ABSOLUTE link into a repo checkout (not\n * mounted). rsync's `--copy-unsafe-links` dereferences the reachable dir link\n * and descends into it, then aborts on the nested absolute link. So when a\n * symlink resolves into a reachable tree we recurse into the resolved target,\n * reporting nested findings under the symlink's path as rsync transfers it\n * (the link name in `root`, not the resolved `~/.agents` path). An ancestry\n * guard (`onPath`) blocks symlink cycles without suppressing the same resolved\n * dir reached under a *different* virtual prefix — e.g. two skills symlinked to\n * one shared target must each report their nested unsyncable link, or rsync\n * still aborts on the prefix we skipped.\n */\nexport async function findUnsyncableSymlinks(\n root: string,\n reachableRoots: string[],\n): Promise<string[]> {\n // realpath the reachable roots so a symlinked ancestor (e.g. macOS\n // /var -> /private/var) doesn't make a containment check spuriously fail.\n const reachable = await Promise.all(\n reachableRoots.map(async (r) => {\n try {\n return await realpath(r);\n } catch {\n return r;\n }\n }),\n );\n const unsyncable: string[] = [];\n // Resolved dirs currently on the recursion path. Guards against symlink\n // cycles (a link pointing at an ancestor) while still allowing the same dir\n // to be re-walked under a different virtual prefix once this branch unwinds.\n const onPath = new Set<string>();\n // `realDir` is the filesystem directory to read; `virtualDir` is its path as\n // rsync sees it under `root` (they diverge once we follow a symlinked dir).\n async function walk(realDir: string, virtualDir: string): Promise<void> {\n if (onPath.has(realDir)) return;\n onPath.add(realDir);\n try {\n let entries;\n try {\n entries = await readdir(realDir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const ent of entries) {\n const realFull = join(realDir, ent.name);\n const virtualFull = virtualDir ? join(virtualDir, ent.name) : ent.name;\n if (ent.isSymbolicLink()) {\n let real: string;\n try {\n real = await realpath(realFull);\n } catch {\n unsyncable.push(virtualFull); // broken on the host\n continue;\n }\n if (!reachable.some((r) => isUnder(r, real))) {\n unsyncable.push(virtualFull); // target not mounted in the box\n continue;\n }\n // Reachable target: rsync will dereference + descend, so check inside\n // it too for nested unsyncable links, keyed to the symlink's path.\n const st = await stat(real).catch(() => null);\n if (st?.isDirectory()) await walk(real, virtualFull);\n } else if (ent.isDirectory()) {\n await walk(realFull, virtualFull);\n }\n }\n } finally {\n onPath.delete(realDir);\n }\n }\n await walk(root, '');\n return unsyncable;\n}\n","/**\n * Concern: skills — the shared `~/.agents` tree (`~/.agents/skills/<name>`, the\n * cross-agent Agent Skills location) seeded host→box so the in-box agents see\n * the same skill set the host does.\n *\n * On docker this is a persistent shared volume seeded from the host via the\n * transport's `seedVolumeFromHost` (a throwaway rsync helper container). Cloud\n * has no helper container (`caps.helperContainer === false`) — its static config\n * is baked into the prepare-time snapshot via `stageAgentsStaticForUpload` — so\n * cloud never calls this.\n *\n * The host is authoritative and the sync is additive (no `--delete`). Skills\n * routinely symlink files into checkouts, so the seed dereferences reachable\n * links (`copyUnsafeLinks`) and excludes the ones the box can't resolve (broken\n * on the host or pointing outside the mounted tree — see `findUnsyncableSymlinks`),\n * or rsync aborts with \"symlink has no referent\".\n */\n\nimport { stat } from 'node:fs/promises';\nimport type { SyncTransport } from '@agentbox/core';\nimport { findUnsyncableSymlinks } from '../host-links.js';\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface SeedAgentsVolumeArgs {\n /** Transport bound to the box's provider. Must expose `seedVolumeFromHost`. */\n transport: SyncTransport;\n /** The shared agents-config volume name (already ensured to exist). */\n volume: string;\n /** Host `~/.agents` dir. */\n hostAgents: string;\n /**\n * Sync host → volume when true AND the host `~/.agents` exists. When false or\n * absent, the volume is only made writable by the in-box `vscode` user.\n */\n syncFromHost: boolean;\n onLog?: (line: string) => void;\n}\n\nexport interface SeedAgentsVolumeResult {\n /** True when the rsync helper ran (syncFromHost was true AND host had `~/.agents`). */\n synced: boolean;\n}\n\n/**\n * Seed (or make writable) the shared `~/.agents` volume via the transport's\n * persistent-volume seam. The caller owns volume creation + `created`\n * detection; this owns the host→volume sync decision so both providers (only\n * docker today) share it.\n */\nexport async function seedAgentsVolume(args: SeedAgentsVolumeArgs): Promise<SeedAgentsVolumeResult> {\n const seed = args.transport.seedVolumeFromHost;\n if (!seed) throw new Error('seedAgentsVolume requires a transport with seedVolumeFromHost');\n\n const willSync = args.syncFromHost && (await pathExists(args.hostAgents));\n if (!willSync) {\n // No host ~/.agents to sync — an empty source set still makes the (possibly\n // freshly created, root-owned) volume root writable by the in-box vscode\n // user. Best-effort: a failed chown must not abort box creation (the sync\n // path below, by contrast, propagates — a botched skills sync is worth\n // surfacing).\n try {\n await seed.call(args.transport, args.volume, []);\n } catch (err) {\n args.onLog?.(\n `skills: volume writable-chown failed (ignored): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return { synced: false };\n }\n\n // `--copy-unsafe-links` dereferences a skill's symlinks pointing outside\n // ~/.agents into real files; the ones it can't resolve (broken / out-of-tree)\n // are excluded so the sync doesn't abort with \"symlink has no referent\".\n const excludes = (await findUnsyncableSymlinks(args.hostAgents, [args.hostAgents])).map(\n (rel) => `/${rel}`,\n );\n await seed.call(args.transport, args.volume, [\n { hostDir: args.hostAgents, destSubpath: '', exclude: excludes, copyUnsafeLinks: true },\n ]);\n if (excludes.length > 0) {\n args.onLog?.(`skills: excluded ${String(excludes.length)} unsyncable symlink(s) from ~/.agents`);\n }\n return { synced: true };\n}\n","/**\n * Concern: credentials — the per-agent login secrets (`~/.claude/.credentials.json`\n * for claude, `auth.json` for codex/opencode) that ride separately from static\n * config because they change per login and must never be baked into a shared\n * snapshot.\n *\n * What lives here is the provider-neutral core of the concern:\n * - the pure host-side guards (`isRealAgentCredential`, `hostClaudeBackupExpired`,\n * `hostBackupHasCredentials`) — the \"is this blob real / expired?\" decisions,\n * driven by the registry's `credential.realShape` so the per-agent switch has\n * one home;\n * - the box→host extract (`extractCredentials`) expressed against the\n * `SyncTransport.readText` seam, so cloud's `extractCloudAgentCredentials`\n * becomes a thin transport-injecting wrapper;\n * - the seed-once marker name (`SEED_MARKER`) shared by the cloud volume seed.\n *\n * What deliberately does NOT live here (yet): the *seed* mechanisms. Docker\n * seeds claude via a throwaway root helper container that bidirectionally syncs\n * the shared config volume with the host backup (`syncClaudeCredentials`,\n * `SYNC_SCRIPT`) — it predates any running box, so it has no `SyncTransport`\n * (box-bound) analog and no polymorphic caller; codex/opencode ride the whole-\n * dir volume rsync. Cloud seeds via `seedCredentialsOne` (marker/force gate +\n * `uploadFile` + a volume-vs-ephemeral extract split). Those stay in their\n * providers; their transport-seam collapse folds into the Phase 7 driver, the\n * same call carry's apply mechanism and skills' box→host pull already made.\n */\n\nimport { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport type { SyncTransport } from '@agentbox/core';\nimport { AGENT_SYNC_SPECS, resolveAgentSpec } from '../registry.js';\nimport type { AgentId } from '../agents/types.js';\n\n/** Agents whose credentials we extract from a box back to the host. Mirrors `AgentId`. */\nexport type CredentialAgentKind = AgentId;\n\n/**\n * Marker filename written inside a cloud agent's credentials subpath recording\n * when we last seeded it (a single ISO-8601 timestamp on disk). Absent marker =\n * first time on this volume → seed. Volume/idempotency-only: ephemeral cloud\n * backends can't persist it and push every create; docker uses a content check\n * (real-vs-empty) instead of a marker.\n */\nexport const SEED_MARKER = '.agentbox-seeded-at';\n\n/** Host backup of the claude OAuth blob — the registry is the single source of truth. */\nconst CLAUDE_HOST_BACKUP = resolveAgentSpec('claude').credential.hostBackup;\n\n/**\n * True iff `text` looks like a real (usable) credential for `agent`, not an\n * empty/placeholder file. Used so the box→host extract never clobbers a good\n * host backup with an empty box file. The per-agent shape comes from the\n * registry (`credential.realShape`): claude requires a non-empty\n * `claudeAiOauth.refreshToken`; codex/opencode auth files just have to parse as\n * a non-empty JSON object. Unknown agents fall back to the JSON-object check\n * (never throws — matches the pre-registry `if (agent === 'claude')` switch).\n */\nexport function isRealAgentCredential(agent: CredentialAgentKind, text: string): boolean {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return false;\n }\n if (typeof parsed !== 'object' || parsed === null) return false;\n const spec = AGENT_SYNC_SPECS.find((s) => s.id === agent);\n if (spec?.credential.realShape === 'claude-oauth') {\n const rt = (parsed as { claudeAiOauth?: { refreshToken?: unknown } }).claudeAiOauth?.refreshToken;\n return typeof rt === 'string' && rt.length > 0;\n }\n return Object.keys(parsed as Record<string, unknown>).length > 0;\n}\n\n/**\n * True iff the claude host backup holds an OAuth blob whose access token is\n * already expired (`claudeAiOauth.expiresAt`, ms epoch, < now). A missing\n * `expiresAt` (or unreadable file) → false: we only report a *known* expiry, so\n * callers don't nag when the box could still refresh the token itself. `now` is\n * injectable for tests. Claude is the only agent with a token-expiry gate (codex\n * / opencode auth files carry no comparable field).\n */\nexport async function hostClaudeBackupExpired(\n path: string = CLAUDE_HOST_BACKUP,\n now: number = Date.now(),\n): Promise<boolean> {\n try {\n const parsed = JSON.parse(await readFile(path, 'utf8')) as {\n claudeAiOauth?: { expiresAt?: unknown };\n };\n const exp = parsed?.claudeAiOauth?.expiresAt;\n return typeof exp === 'number' && Number.isFinite(exp) && exp < now;\n } catch {\n return false;\n }\n}\n\n/**\n * True iff the claude host backup file holds a real OAuth blob (a non-empty\n * `claudeAiOauth.refreshToken`). Used to decide whether to offer an interactive\n * sign-in before creating a box. Tolerant of a missing or garbage file — returns\n * false.\n */\nexport async function hostBackupHasCredentials(\n path: string = CLAUDE_HOST_BACKUP,\n): Promise<boolean> {\n try {\n const parsed = JSON.parse(await readFile(path, 'utf8')) as {\n claudeAiOauth?: { refreshToken?: unknown };\n };\n const rt = parsed?.claudeAiOauth?.refreshToken;\n return typeof rt === 'string' && rt.length > 0;\n } catch {\n return false;\n }\n}\n\nexport interface ExtractCredentialsOptions {\n onLog?: (line: string) => void;\n /** Override host backup paths per agent (tests). Defaults to the registry `hostBackup`. */\n backups?: Partial<Record<AgentId, string>>;\n}\n\n/**\n * Extract each agent's login credential from a running box back to the host\n * backups under `~/.agentbox/`, so the next box (seeded from those backups)\n * inherits the login. The provider-neutral core of docker's\n * `syncClaudeCredentials` extract direction and cloud's\n * `extractCloudAgentCredentials`, expressed against `transport.readText`.\n *\n * Reads the canonical in-box path (`credential.boxAbsPath`) via\n * `transport.readText`; only writes the host backup (mode 0600) when the content\n * passes `isRealAgentCredential`, so an empty / not-logged-in box never clobbers\n * a good backup. Best-effort per agent (never throws). Returns the agents whose\n * backup was updated.\n */\nexport async function extractCredentials(\n transport: SyncTransport,\n opts: ExtractCredentialsOptions = {},\n): Promise<AgentId[]> {\n const log = opts.onLog ?? (() => {});\n const extracted: AgentId[] = [];\n for (const spec of AGENT_SYNC_SPECS) {\n const hostBackup = opts.backups?.[spec.id] ?? spec.credential.hostBackup;\n try {\n // `readText` is `cat <path> 2>/dev/null` with noRetry → null on a missing\n // file; tolerate that silently. `!text` also covers an empty stdout.\n const text = await transport.readText(spec.credential.boxAbsPath);\n if (!text || !isRealAgentCredential(spec.id, text)) continue;\n await mkdir(dirname(hostBackup), { recursive: true });\n await writeFile(hostBackup, text, { mode: 0o600 });\n await chmod(hostBackup, 0o600).catch(() => {});\n extracted.push(spec.id);\n log(`extracted ${spec.id} login from box to ${hostBackup}`);\n } catch (err) {\n log(\n `WARN: ${spec.id} credential extract failed (${err instanceof Error ? err.message : String(err)}) — skipping`,\n );\n }\n }\n return extracted;\n}\n","/**\n * Concern: git / workspace — seed the box's per-box worktree(s) from the host at\n * create, and resync them with the host's current state on session restart\n * (box-wins on every conflict). This is the concrete `box-wins-content-hash`\n * conflict policy the reconciler contract (`@agentbox/core` `sync/reconciler.ts`)\n * anticipates as its first consumer.\n *\n * This file holds the provider-neutral *resync* half: the pure untracked-overlay\n * classifier + the `resyncWorkspace` orchestration, driven entirely through the\n * `WorkspaceResyncPorts` seam so it's a pure function of its I/O (golden-tested\n * against a scripted fake). The docker/cloud providers supply the ports. Docker\n * is the only implementation today; a cloud one closes the \"Phase 2\" gap (a\n * cloud box gets no workspace resync yet). Workspace *seed* (worktree add +\n * bind-mount replay) stays docker-specific — it has no cloud analog (cloud\n * clones) — and is not moved.\n */\n\nimport { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type {\n RepoResyncResult,\n ResyncWorktree,\n WorkspaceResyncPorts,\n} from '@agentbox/core';\n\n/**\n * Sentinel token the box-side probe emits for a path that exists but is NOT a\n * plain file (a dir or symlink) — always a conflict so we never clobber it.\n */\nexport const NON_REGULAR_TOKEN = '-';\n\n/**\n * Classify a host untracked file against what the box already has at that path.\n * `boxToken` is the box-side probe result: `undefined` when the path is absent\n * in the box (safe to copy), {@link NON_REGULAR_TOKEN} when it exists but isn't\n * a plain file, otherwise the sha256 of the box file's contents. `hostHash` is\n * the sha256 of the host file. A byte-identical file is a no-op (neither copied\n * nor reported); anything else that already exists is a conflict the box keeps\n * (box wins — the host change is shadowed, no marker left).\n */\nexport function classifyUntrackedOverlay(\n boxToken: string | undefined,\n hostHash: string,\n): 'copy' | 'identical' | 'conflict' {\n if (boxToken === undefined) return 'copy';\n if (boxToken === NON_REGULAR_TOKEN) return 'conflict';\n return boxToken === hostHash ? 'identical' : 'conflict';\n}\n\n/** Split a `-z` (NUL-delimited) git output into non-empty entries. */\nfunction splitNul(s: string): string[] {\n return s.split('\\0').filter((p) => p.length > 0);\n}\n\n/** Conflicted (unmerged) paths in the box worktree, if any. */\nasync function unmergedPaths(ports: WorkspaceResyncPorts, ct: string): Promise<string[]> {\n const r = await ports.boxGit(ct, ['diff', '--name-only', '--diff-filter=U', '-z']);\n return r.exitCode === 0 ? splitNul(r.stdout) : [];\n}\n\n/**\n * Resync each box worktree with the host's current state: merge the host's\n * checked-out branch into the box's per-box branch, then overlay the host's\n * uncommitted (stash) + untracked changes. The box wins every conflict — the\n * host change is skipped (no markers left) and the affected paths are returned\n * so the caller can warn the agent.\n *\n * Provider-neutral: all I/O goes through {@link WorkspaceResyncPorts}. On docker\n * the host `.git/` is bind-mounted so the host branch ref is already present in\n * the box and the merge needs no fetch (the same property create-time carry-over\n * relies on). Best-effort throughout — a step that fails is logged and skipped\n * rather than aborting the box start.\n */\nexport async function resyncWorkspace(\n worktrees: ResyncWorktree[],\n ports: WorkspaceResyncPorts,\n onLog?: (line: string) => void,\n): Promise<RepoResyncResult[]> {\n const log = onLog ?? (() => {});\n const results: RepoResyncResult[] = [];\n\n for (const w of worktrees) {\n const ct = w.containerPath;\n const hostMain = w.hostMainRepo;\n const boxBranch = w.branch;\n const res: RepoResyncResult = { containerPath: ct, mergeConflicts: [], overlaySkipped: [] };\n\n // --- host state (host-side git; no side effects on the worktree) ---\n const hostRef = await ports.resolveHostRef(hostMain);\n if (!hostRef) {\n log(`resync: ${ct}: could not resolve host ref; skipping`);\n results.push(res);\n continue;\n }\n const hostStashSha = await ports.createHostStash(hostMain);\n const hostUntracked = await ports.listHostUntracked(hostMain);\n\n // --- merge host commits into the box branch (skip when merging self) ---\n if (hostRef !== boxBranch) {\n // Stash the box's own uncommitted tracked changes so the merge can run;\n // restored on top afterward (box keeps them). Untracked box files stay.\n const status = await ports.boxGit(ct, ['status', '--porcelain']);\n const boxDirty = status.stdout\n .split('\\n')\n .some((line) => line.length > 0 && !line.startsWith('??'));\n let boxStashed = false;\n if (boxDirty) {\n const push = await ports.boxGit(ct, ['stash', 'push', '-m', 'agentbox-resync']);\n boxStashed = push.exitCode === 0;\n }\n\n const newCommits = await ports.boxGit(ct, ['rev-list', '--count', `${boxBranch}..${hostRef}`]);\n const n = newCommits.exitCode === 0 ? newCommits.stdout.trim() : '?';\n const merge = await ports.boxGit(ct, ['merge', '--no-commit', hostRef]);\n const mergeInProgress =\n (await ports.boxGit(ct, ['rev-parse', '-q', '--verify', 'MERGE_HEAD'])).exitCode === 0;\n const conflicts = await unmergedPaths(ports, ct);\n if (conflicts.length > 0) {\n await ports.boxGit(ct, ['checkout', '--ours', '--', ...conflicts]);\n await ports.boxGit(ct, ['add', '--', ...conflicts]);\n res.mergeConflicts.push(...conflicts);\n }\n if (mergeInProgress) {\n await ports.boxGit(ct, [\n '-c',\n 'user.name=agentbox',\n '-c',\n 'user.email=agentbox@users.noreply.github.com',\n 'commit',\n '--no-edit',\n ]);\n log(\n `resync: ${ct}: merged ${n} new host commit(s) from ${hostRef}` +\n (conflicts.length > 0 ? ` (${String(conflicts.length)} conflict(s) kept box version)` : ''),\n );\n } else if (merge.exitCode === 0) {\n log(`resync: ${ct}: ${n === '0' ? 'already up to date' : `fast-forwarded to ${hostRef}`}`);\n } else {\n // Hard failure (e.g. an untracked box file would be overwritten). Leave\n // the box untouched.\n await ports.boxGit(ct, ['merge', '--abort']);\n log(`resync: ${ct}: merge skipped (${(merge.stderr || merge.stdout).trim().split('\\n')[0]})`);\n }\n\n if (boxStashed) {\n const pop = await ports.boxGit(ct, ['stash', 'pop']);\n if (pop.exitCode !== 0) {\n // Box's uncommitted edits clash with the merged host change. Keep the\n // box's version (stash side = --theirs), drop the dangling stash.\n const popConflicts = await unmergedPaths(ports, ct);\n for (const p of popConflicts) {\n await ports.boxGit(ct, ['checkout', '--theirs', '--', p]);\n await ports.boxGit(ct, ['reset', '-q', '--', p]);\n }\n await ports.boxGit(ct, ['stash', 'drop']);\n }\n }\n }\n\n // --- overlay host uncommitted (stash) on top, box wins on conflict ---\n if (hostStashSha) {\n const apply = await ports.boxGit(ct, ['stash', 'apply', hostStashSha]);\n if (apply.exitCode !== 0) {\n const conflicts = await unmergedPaths(ports, ct);\n for (const p of conflicts) {\n // ours = box working tree, theirs = host stash → keep box, unstage.\n await ports.boxGit(ct, ['checkout', '--ours', '--', p]);\n await ports.boxGit(ct, ['reset', '-q', '--', p]);\n }\n if (conflicts.length > 0) res.overlaySkipped.push(...conflicts);\n }\n }\n\n // --- overlay host untracked files; box wins only when it actually differs ---\n if (hostUntracked.length > 0) {\n // Probe the box for each host path. A path absent in the box is copied; a\n // path present and byte-identical is a no-op (NOT a conflict — this is the\n // common case right after create-time seeding copied these same untracked\n // files in); a path present but differing (or a non-regular file we won't\n // clobber) is the box's version we keep and report.\n const boxTokens = await ports.probeUntrackedTokens(ct, hostUntracked);\n const toCopy: string[] = [];\n let identical = 0;\n for (const p of hostUntracked) {\n const boxToken = boxTokens.get(p);\n let hostHash = '';\n if (boxToken !== undefined && boxToken !== NON_REGULAR_TOKEN) {\n try {\n hostHash = await ports.hashHostFile(hostMain, p);\n } catch {\n // Host file vanished/unreadable since `ls-files` — can't copy it and\n // the box already has its own version; keep the box's, don't report.\n identical++;\n continue;\n }\n }\n const verdict = classifyUntrackedOverlay(boxToken, hostHash);\n if (verdict === 'copy') toCopy.push(p);\n else if (verdict === 'conflict') res.overlaySkipped.push(p);\n else identical++;\n }\n if (identical > 0) {\n log(`resync: ${ct}: ${String(identical)} untracked host file(s) already identical in box (no-op)`);\n }\n if (toCopy.length > 0) {\n const tar = await ports.packHostFiles(hostMain, toCopy);\n if (tar) {\n await ports.applyTarToBox(ct, tar);\n log(`resync: ${ct}: copied ${String(toCopy.length)} untracked host file(s)`);\n }\n }\n }\n\n results.push(res);\n }\n\n return results;\n}\n\n/**\n * The host-side half of {@link WorkspaceResyncPorts} — read-only git probes on\n * the host's own repo (checked-out ref, an uncommitted-changes stash sha, the\n * gitignore-respecting untracked list, a file content hash, and a tar pack of\n * chosen files). Host git is provider-neutral: it's the host's real repo whether\n * the box is docker or cloud, so both providers reuse these verbatim while\n * supplying their own box-side ports (`boxGit`/`probeUntrackedTokens`/\n * `applyTarToBox`). Each method reproduces the pre-refactor docker\n * `resyncWorkspaceFromHost` command byte-for-byte.\n *\n * The cloud live-box resync (Phase 7.5) reuses `listHostUntracked`/`hashHostFile`/\n * `packHostFiles` unchanged and overrides `resolveHostRef`/`createHostStash`\n * (its host ref/stash are pre-fetched into the box, not merged from a bind mount).\n */\nexport function makeHostGitPorts(): Pick<\n WorkspaceResyncPorts,\n 'resolveHostRef' | 'createHostStash' | 'listHostUntracked' | 'hashHostFile' | 'packHostFiles'\n> {\n return {\n async resolveHostRef(hostMain) {\n const hostBranchProbe = await execa(\n 'git',\n ['-C', hostMain, 'symbolic-ref', '--short', '-q', 'HEAD'],\n { reject: false },\n );\n const hostRef =\n hostBranchProbe.exitCode === 0 && hostBranchProbe.stdout.trim()\n ? hostBranchProbe.stdout.trim()\n : (await execa('git', ['-C', hostMain, 'rev-parse', 'HEAD'], { reject: false })).stdout.trim();\n return hostRef || null;\n },\n async createHostStash(hostMain) {\n const stash = await execa('git', ['-C', hostMain, 'stash', 'create'], { reject: false });\n return stash.exitCode === 0 ? stash.stdout.trim() || null : null;\n },\n async listHostUntracked(hostMain) {\n const untracked = await execa(\n 'git',\n ['-C', hostMain, 'ls-files', '--others', '--exclude-standard', '-z'],\n { reject: false },\n );\n return untracked.exitCode === 0 ? splitNul(untracked.stdout) : [];\n },\n async hashHostFile(hostMain, relPath) {\n return createHash('sha256').update(await readFile(join(hostMain, relPath))).digest('hex');\n },\n async packHostFiles(hostMain, relPaths) {\n const tarOut = await execa('tar', ['-C', hostMain, '--null', '-T', '-', '-cf', '-'], {\n input: relPaths.join('\\0'),\n encoding: 'buffer',\n reject: false,\n });\n return tarOut.exitCode === 0 ? (tarOut.stdout as Buffer) : null;\n },\n };\n}\n","/**\n * Concern: dynamic Claude config — the global `~/.claude/workflows/` scripts and\n * the current project's `memory/` tree. Unlike the static config\n * (plugins/skills/settings) that the cloud path bakes into the prepare-time\n * snapshot, these change between runs and must be refreshed per-box at create —\n * like credentials.\n *\n * These pieces are provider-neutral and pure where possible, so both the docker\n * volume sync and the cloud `seedDynamicConfig` reuse them:\n *\n * - `buildHostSyncManifest` hashes every file in each set on the host.\n * - `computeSyncDelta` diffs that against the manifest the box already\n * carries (captured by any checkpoint/snapshot), yielding the minimal set\n * of files to upload + delete and the manifest to write back.\n * - `stageDynamicSyncTarball` packs only the changed files into one tarball\n * whose members are laid out by set name, so the box `cp -a`s each set into\n * place without tar touching shared parent-dir perms.\n *\n * The box stores its manifest at {@link BOX_DYNAMIC_SYNC_MANIFEST}. Because it\n * lives on the box filesystem it rides along in every checkpoint, so a\n * checkpoint boot naturally syncs only what changed on the host since.\n *\n * Moved here (from `@agentbox/sandbox-docker`'s `dynamic-sync.ts`) so the cloud\n * path reuses it without importing the docker package. `sandbox-docker`\n * re-exports these for its existing importers.\n */\n\nimport { createHash } from 'node:crypto';\nimport { copyFile, mkdir, mkdtemp, readdir, readFile, rm, stat } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { execa } from 'execa';\nimport {\n BOX_CLAUDE_PROJECT_DIR,\n resolveClaudeMemoryDir,\n} from '../agents/claude/paths.js';\n\n/** In-box destination for the global workflow scripts. */\nexport const BOX_WORKFLOWS_DIR = '/home/vscode/.claude/workflows';\n\n/** In-box path of the per-box dynamic-sync manifest (rides along in checkpoints). */\nexport const BOX_DYNAMIC_SYNC_MANIFEST = '/home/vscode/.agentbox/dynamic-sync.json';\n\n/** In-box destination for the current project's rekeyed memory. */\nexport const BOX_MEMORY_DIR = `${BOX_CLAUDE_PROJECT_DIR}/memory`;\n\nexport type DynamicSyncSetName = 'workflows' | 'memory';\n\n/** A set's box destination dir + per-file content hashes (relpath -> sha256 hex). */\nexport interface DynamicSyncSet {\n dst: string;\n files: Record<string, string>;\n}\n\n/** Persisted shape written to {@link BOX_DYNAMIC_SYNC_MANIFEST}. */\nexport interface DynamicSyncManifest {\n version: 1;\n syncedAt?: string;\n sets: Record<DynamicSyncSetName, DynamicSyncSet>;\n}\n\n/** Host-side set: like {@link DynamicSyncSet} plus the source dir to read bytes from. */\ninterface HostSyncSet extends DynamicSyncSet {\n /** Absolute host source dir, or null when this set has nothing on the host. */\n hostDir: string | null;\n}\n\nexport interface HostSyncManifest {\n sets: Record<DynamicSyncSetName, HostSyncSet>;\n}\n\nexport interface DynamicSyncUpload {\n set: DynamicSyncSetName;\n /** Path relative to the set's dir. */\n rel: string;\n /** Absolute host source file. */\n absSrc: string;\n /** Absolute box destination file (`dst/rel`). */\n dst: string;\n}\n\nexport interface DynamicSyncDeletion {\n set: DynamicSyncSetName;\n rel: string;\n /** Absolute box file to remove. */\n dst: string;\n}\n\nexport interface DynamicSyncDelta {\n uploads: DynamicSyncUpload[];\n deletions: DynamicSyncDeletion[];\n /** Manifest to persist into the box after applying the delta (host state). */\n nextManifest: DynamicSyncManifest;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Recursively collect regular-file relpaths under `root` (posix-separated). */\nasync function walkFiles(root: string, prefix = ''): Promise<string[]> {\n let entries;\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch {\n return [];\n }\n const out: string[] = [];\n for (const ent of entries) {\n const rel = prefix ? `${prefix}/${ent.name}` : ent.name;\n const full = join(root, ent.name);\n if (ent.isDirectory()) {\n out.push(...(await walkFiles(full, rel)));\n } else if (ent.isFile()) {\n out.push(rel);\n } else if (ent.isSymbolicLink()) {\n // Follow only symlinks that resolve to a regular file (e.g. a workflow\n // symlinked from a checkout); ignore dangling/dir links.\n try {\n const s = await stat(full);\n if (s.isFile()) out.push(rel);\n } catch {\n /* skip dangling */\n }\n }\n }\n return out;\n}\n\nasync function hashFile(absPath: string): Promise<string> {\n const buf = await readFile(absPath);\n return createHash('sha256').update(buf).digest('hex');\n}\n\nasync function buildHostSet(\n name: DynamicSyncSetName,\n hostDir: string | null,\n boxDst: string,\n): Promise<HostSyncSet> {\n if (hostDir === null) return { dst: boxDst, files: {}, hostDir: null };\n const rels = await walkFiles(hostDir);\n const files: Record<string, string> = {};\n for (const rel of rels) {\n files[rel] = await hashFile(join(hostDir, rel));\n }\n return { dst: boxDst, files, hostDir };\n}\n\n/**\n * Hash the host's workflow + memory sets. `workspacePath` is the host-absolute\n * project path (used to locate the project's memory dir); `hostHome` is\n * overridable for tests. Sets with nothing on the host get an empty `files` map\n * and `hostDir: null` so the diff can still emit deletions for them.\n */\nexport async function buildHostSyncManifest(\n workspacePath: string,\n hostHome: string = homedir(),\n): Promise<HostSyncManifest> {\n const workflowsDir = join(hostHome, '.claude', 'workflows');\n const workflowsHost = (await pathExists(workflowsDir)) ? workflowsDir : null;\n const memoryHost = await resolveClaudeMemoryDir(workspacePath, hostHome);\n const [workflows, memory] = await Promise.all([\n buildHostSet('workflows', workflowsHost, BOX_WORKFLOWS_DIR),\n buildHostSet('memory', memoryHost, BOX_MEMORY_DIR),\n ]);\n return { sets: { workflows, memory } };\n}\n\nconst SET_NAMES: DynamicSyncSetName[] = ['workflows', 'memory'];\n\n/**\n * Diff the host manifest against the manifest the box already carries. A file\n * is uploaded when its hash differs (new or changed); a file in the box\n * manifest absent on the host is deleted. Pure — no IO, no clock.\n */\nexport function computeSyncDelta(\n host: HostSyncManifest,\n box: DynamicSyncManifest | null,\n): DynamicSyncDelta {\n const uploads: DynamicSyncUpload[] = [];\n const deletions: DynamicSyncDeletion[] = [];\n const nextSets = {} as Record<DynamicSyncSetName, DynamicSyncSet>;\n\n for (const name of SET_NAMES) {\n const hostSet = host.sets[name];\n const boxFiles = box?.sets?.[name]?.files ?? {};\n for (const [rel, hash] of Object.entries(hostSet.files)) {\n if (boxFiles[rel] !== hash) {\n uploads.push({\n set: name,\n rel,\n absSrc: join(hostSet.hostDir as string, rel),\n dst: `${hostSet.dst}/${rel}`,\n });\n }\n }\n for (const rel of Object.keys(boxFiles)) {\n if (!(rel in hostSet.files)) {\n deletions.push({ set: name, rel, dst: `${hostSet.dst}/${rel}` });\n }\n }\n nextSets[name] = { dst: hostSet.dst, files: hostSet.files };\n }\n\n return { uploads, deletions, nextManifest: { version: 1, sets: nextSets } };\n}\n\nexport interface StagedTarball {\n /** Absolute path to the .tar.gz, or null when there was nothing to upload. */\n tarballPath: string | null;\n /** Remove the staging dir + tarball. Idempotent. */\n cleanup(): Promise<void>;\n}\n\n/**\n * Pack the upload files into one gzip tarball laid out by set name\n * (`workflows/<rel>`, `memory/<rel>`). The box extracts into a staging dir and\n * `cp -a`s each set into its destination, so tar never touches the perms of\n * shared parent dirs (`/`, `/home`). Returns `{ tarballPath: null }` when\n * `uploads` is empty.\n */\nexport async function stageDynamicSyncTarball(\n uploads: DynamicSyncUpload[],\n): Promise<StagedTarball> {\n if (uploads.length === 0) {\n return { tarballPath: null, cleanup: async () => {} };\n }\n const stageDir = await mkdtemp(join(tmpdir(), 'agentbox-dynsync-stage-'));\n let tarballPath: string | null = null;\n try {\n for (const up of uploads) {\n const target = join(stageDir, up.set, up.rel);\n await mkdir(dirname(target), { recursive: true });\n await copyFile(up.absSrc, target);\n }\n tarballPath = join(tmpdir(), `agentbox-dynsync-${basename(stageDir)}.tar.gz`);\n // COPYFILE_DISABLE=1: stop macOS bsdtar from emitting AppleDouble sidecars.\n await execa('tar', ['-czf', tarballPath, '-C', stageDir, '.'], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n const tp = tarballPath;\n return {\n tarballPath: tp,\n cleanup: async () => {\n await rm(stageDir, { recursive: true, force: true });\n await rm(tp, { force: true });\n },\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n","/**\n * Stage the host's agent-config trees (`~/.claude`, `~/.codex`,\n * `~/.config/opencode` + `~/.local/share/opencode`) into filtered tarballs any\n * provider can ship into a remote sandbox.\n *\n * Per agent we produce **two** tarballs:\n *\n * - **static**: plugins, skills, settings, marketplaces, prompts, config —\n * stuff that's stable across re-auths. The cloud path bakes this into the\n * published Daytona snapshot once (`agentbox daytona publish-snapshot`),\n * so it ships into the sandbox FS at snapshot capture time, never the\n * S3-backed FUSE volume.\n *\n * - **credentials**: the renewable OAuth/auth files only (a handful of KB).\n * The cloud path uploads these into a per-org `agentbox-credentials`\n * volume on every create (cheap) and `agentbox daytona resync` refreshes\n * them after a re-auth — without touching the snapshot.\n *\n * Each `stage*ForUpload(opts)` returns a `StageResult`:\n * - `tarballPath`: absolute path to a `.tar.gz`, or `null` when the host has\n * nothing relevant to stage (no `~/.claude` etc., or no credentials file).\n * - `cleanup()`: removes the staging dir + the tarball; ALWAYS call after\n * the upload completes, even on error.\n * - `warnings`: non-fatal user-facing messages (the codex Keychain landmine\n * surfaces here).\n *\n * Requires `rsync` and `tar` on the host. macOS + every common Linux distro\n * ship both.\n */\n\nimport { copyFile, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { basename, join, relative } from 'node:path';\nimport { execa } from 'execa';\nimport {\n addProjectAlias,\n filterHostHooks,\n setInstallMethodNative,\n trustWorkspace,\n} from './claude-hooks-filter.js';\nimport { resolveAgentSpec } from './registry.js';\nimport { sanitizeCodexConfigForBox } from './codex-config.js';\n\n/**\n * Portable host backup of the claude OAuth creds — the single source of truth is\n * the registry (`credential.hostBackup`), which resolves to\n * `~/.agentbox/claude-credentials.json`. The docker provider's\n * `syncClaudeCredentials` mirrors the macOS Keychain into this same path.\n */\nconst CREDENTIALS_BACKUP_FILE = resolveAgentSpec('claude').credential.hostBackup;\n\nexport interface StageResult {\n /** Absolute path to the .tar.gz, or null when there was nothing to stage. */\n tarballPath: string | null;\n /** Remove the staging dir + tarball. Idempotent. */\n cleanup(): Promise<void>;\n /** Non-fatal messages (e.g. codex Keychain landmine). */\n warnings: string[];\n}\n\n/** Workspace path inside every cloud sandbox — matches the Docker model. */\nconst CLOUD_WORKSPACE = '/workspace';\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function findBrokenSymlinks(root: string): Promise<string[]> {\n const broken: string[] = [];\n async function walk(dir: string): Promise<void> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const ent of entries) {\n const full = join(dir, ent.name);\n if (ent.isSymbolicLink()) {\n try {\n await stat(full);\n } catch {\n broken.push(relative(root, full));\n }\n } else if (ent.isDirectory()) {\n await walk(full);\n }\n }\n }\n await walk(root);\n return broken;\n}\n\nasync function mkStageDir(prefix: string): Promise<string> {\n return mkdtemp(join(tmpdir(), `agentbox-${prefix}-stage-`));\n}\n\nfunction emptyResult(warnings: string[] = []): StageResult {\n return { tarballPath: null, cleanup: async () => {}, warnings };\n}\n\nasync function tarballFromDir(stageDir: string, agent: string): Promise<string> {\n const tarballPath = join(tmpdir(), `agentbox-${agent}-${basename(stageDir)}.tar.gz`);\n // COPYFILE_DISABLE=1: macOS's bsdtar (the system `tar`) walks extended attrs\n // and emits AppleDouble `._<name>` sidecars for any file with xattrs, which\n // then pollute the volume inside the cloud sandbox (claude reads ~/.claude\n // top-level and chokes on those bogus entries). The env knob makes Apple's\n // copyfile() helpers a no-op, so tar produces a clean POSIX archive.\n await execa('tar', ['-czf', tarballPath, '-C', stageDir, '.'], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n return tarballPath;\n}\n\nfunction makeCleanup(paths: string[]): () => Promise<void> {\n return async () => {\n for (const p of paths) {\n await rm(p, { recursive: true, force: true });\n }\n };\n}\n\n/**\n * Stage one file into a tarball whose only entry is that file at the tarball\n * root. Used for the credentials-only variants.\n */\nasync function stageSingleFileTarball(\n agent: string,\n sourcePath: string,\n tarballEntryName: string,\n): Promise<StageResult> {\n const stageDir = await mkStageDir(agent);\n let tarballPath: string | null = null;\n try {\n await copyFile(sourcePath, join(stageDir, tarballEntryName));\n tarballPath = await tarballFromDir(stageDir, agent);\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n// ---------- claude ----------\n\nexport interface StageClaudeOptions {\n /** Defaults to `homedir()`. Override for tests. */\n hostHome?: string;\n /**\n * The host-absolute workspace path being mounted as `/workspace` in the\n * box. When set, host-keyed `projects[<hostWorkspace>]` in `_claude.json`\n * gets duplicated to `projects['/workspace']` so MCP servers, history,\n * and trust state line up with the host's view of this project.\n */\n hostWorkspace?: string;\n}\n\n// Static-stage rsync excludes are registry data (single source of truth,\n// drift-guarded by the registry test). Bare patterns, mapped to `--exclude=`\n// at the rsync call; per-run broken-symlink excludes are appended there.\nconst CLAUDE_STATIC_EXCLUDES = resolveAgentSpec('claude').staticPaths[0]?.exclude ?? [];\n\n/**\n * Build the in-box `_claude.json` from the host's `~/.claude.json` (or a\n * sensible default when the host has no Claude config). Shared between the\n * full static tarball (prepare-time bake) and the json-only overlay\n * (create-time refresh).\n *\n * The defaults set `hasCompletedOnboarding: true` — a user who has installed\n * AgentBox has accepted Claude Code's onboarding implicitly, and the box's\n * Claude must not block on the theme picker. When the host *does* have a\n * `~/.claude.json`, the existing `hasCompletedOnboarding` / `theme` pass\n * through unchanged (the filter chain only touches hooks/install/projects/\n * trust).\n */\nasync function buildBoxClaudeJsonFromHost(opts: {\n hostHome: string;\n hostWorkspace?: string;\n}): Promise<unknown> {\n const { hostHome, hostWorkspace } = opts;\n const hostClaudeJson = join(hostHome, '.claude.json');\n let working: unknown;\n if (await pathExists(hostClaudeJson)) {\n try {\n working = JSON.parse(await readFile(hostClaudeJson, 'utf8'));\n } catch {\n working = null;\n }\n }\n if (working === undefined || working === null) {\n working = {\n installMethod: 'native',\n autoUpdates: false,\n autoUpdatesProtectedForNative: true,\n // Pre-accept onboarding so the in-box Claude doesn't show the theme\n // picker on first run. AgentBox installing implies the user has\n // already used Claude Code on the host.\n hasCompletedOnboarding: true,\n projects: { [CLOUD_WORKSPACE]: { hasTrustDialogAccepted: true } },\n };\n } else {\n working = filterHostHooks(working, hostHome).data;\n working = setInstallMethodNative(working).data;\n if (hostWorkspace) {\n working = addProjectAlias(working, hostWorkspace, CLOUD_WORKSPACE).data;\n }\n working = trustWorkspace(working, CLOUD_WORKSPACE).data;\n // Belt-and-suspenders for hosts that have ~/.claude.json but haven't\n // completed onboarding (e.g. a CI runner or a fresh dev machine that's\n // never opened Claude interactively).\n if (typeof working === 'object' && working !== null) {\n const w = working as Record<string, unknown>;\n if (w['hasCompletedOnboarding'] !== true) w['hasCompletedOnboarding'] = true;\n }\n }\n return working;\n}\n\n/**\n * Tarball with **only** `_claude.json` at the root, built from the host's\n * current `~/.claude.json` state. Used at cloud create-time to overlay the\n * box's onboarding state, so a stale prepare-time snapshot doesn't trap the\n * in-box Claude at the theme picker. E2B (which doesn't bake `_claude.json`\n * at prepare-time at all) relies on this overlay for any onboarding state.\n *\n * Returns a real tarball even when the host has no `~/.claude.json` — the\n * default falls back to a minimal pre-onboarded shape (see\n * {@link buildBoxClaudeJsonFromHost}).\n */\nexport async function stageClaudeJsonOnlyForUpload(\n opts: StageClaudeOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const stageDir = await mkStageDir('claude-json-only');\n let tarballPath: string | null = null;\n try {\n const claudeJson = await buildBoxClaudeJsonFromHost({\n hostHome,\n hostWorkspace: opts.hostWorkspace,\n });\n await writeFile(join(stageDir, '_claude.json'), JSON.stringify(claudeJson, null, 2));\n tarballPath = await tarballFromDir(stageDir, 'claude-json-only');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n/**\n * Filtered tarball of `~/.claude/` (+ `~/.claude.json` as `_claude.json` at\n * tarball root) **excluding** `.credentials.json`. Extracts into\n * `/home/vscode/.claude/` on the sandbox FS at snapshot-bake time.\n *\n * Mirrors `ensureClaudeVolume`'s rsync excludes (drops `node_modules`),\n * filters host-path hooks out of `settings.json` / `_claude.json`, coerces\n * install-method to native, aliases the host workspace path to `/workspace`,\n * and pre-trusts `/workspace`. Plugin `installed_plugins.json` and\n * `known_marketplaces.json` get their host-home `installPath` values rewritten\n * to the box's `/home/vscode/.claude/`.\n */\nexport async function stageClaudeStaticForUpload(\n opts: StageClaudeOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostClaude = join(hostHome, '.claude');\n if (!(await pathExists(hostClaude))) return emptyResult();\n\n const stageDir = await mkStageDir('claude-static');\n let tarballPath: string | null = null;\n try {\n // rsync host ~/.claude → stage. --copy-unsafe-links dereferences user\n // skill symlinks; --exclude=node_modules drops host-platform binaries\n // (fsevents.node, esbuild, ...). Broken symlinks would abort the whole\n // sync under --copy-unsafe-links, so pre-scan and exclude them.\n //\n // Drop runtime/history state so the snapshot bake doesn't capture\n // per-machine session data the in-box claude will regenerate anyway.\n const broken = await findBrokenSymlinks(hostClaude);\n const excludes = [\n ...CLAUDE_STATIC_EXCLUDES.map((p) => `--exclude=${p}`),\n ...broken.map((r) => `--exclude=/${r}`),\n ];\n await execa('rsync', [\n '-a',\n '--copy-unsafe-links',\n ...excludes,\n `${hostClaude}/`,\n `${stageDir}/`,\n ]);\n\n // settings.json: filter host-path hooks; rewrite in place when changed.\n const settingsPath = join(stageDir, 'settings.json');\n if (await pathExists(settingsPath)) {\n try {\n const parsed = JSON.parse(await readFile(settingsPath, 'utf8'));\n const filtered = filterHostHooks(parsed, hostHome);\n if (filtered.removedCommands.length > 0) {\n await writeFile(settingsPath, JSON.stringify(filtered.data, null, 2));\n }\n } catch {\n // Leave the rsynced copy if parse failed.\n }\n }\n\n // _claude.json — sourced from $HOME/.claude.json (which lives outside\n // ~/.claude). Apply the same filter chain `ensureClaudeVolume` uses:\n // host-path hooks, install-method=native, host->/workspace project alias,\n // and /workspace trust pre-accept. The Dockerfile.box bakes a symlink\n // `~/.claude.json -> ~/.claude/_claude.json` so the in-box claude reads\n // through to this file at runtime.\n const claudeJson = await buildBoxClaudeJsonFromHost({\n hostHome,\n hostWorkspace: opts.hostWorkspace,\n });\n await writeFile(join(stageDir, '_claude.json'), JSON.stringify(claudeJson, null, 2));\n\n // plugins/*.json: rewrite host-home installPath/installLocation values to\n // the box's /home/vscode/.claude/plugins/ tree. Without this, claude\n // resolves plugin paths to /Users/<you>/... inside the box and the\n // marketplace fails to load.\n const pluginsDir = join(stageDir, 'plugins');\n if (await pathExists(pluginsDir)) {\n try {\n const entries = await readdir(pluginsDir, { withFileTypes: true });\n for (const ent of entries) {\n if (!ent.isFile() || !ent.name.endsWith('.json')) continue;\n const file = join(pluginsDir, ent.name);\n const raw = await readFile(file, 'utf8');\n const replaced = raw\n .split(`${hostHome}/.claude/plugins/`)\n .join('/home/vscode/.claude/plugins/');\n if (replaced !== raw) await writeFile(file, replaced);\n }\n } catch {\n // Best-effort: a broken plugins/ dir mustn't sink the whole seed.\n }\n }\n\n tarballPath = await tarballFromDir(stageDir, 'claude-static');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n/**\n * Tarball with **only** `.credentials.json` (sourced from\n * `~/.agentbox/claude-credentials.json`, the portable backup the Docker\n * provider's `syncClaudeCredentials` mirrors from the macOS Keychain). The\n * cloud path extracts this into `/home/vscode/.agentbox-creds/claude/` on the\n * shared `agentbox-credentials` volume; a baked symlink in the snapshot at\n * `~/.claude/.credentials.json` resolves through to it at runtime.\n *\n * Returns an empty result when no backup exists (the in-box claude falls back\n * to interactive sign-in).\n */\nexport async function stageClaudeCredentialsForUpload(): Promise<StageResult> {\n if (!(await pathExists(CREDENTIALS_BACKUP_FILE))) return emptyResult();\n return stageSingleFileTarball('claude-creds', CREDENTIALS_BACKUP_FILE, '.credentials.json');\n}\n\n// ---------- codex ----------\n\nexport interface StageCodexOptions {\n hostHome?: string;\n}\n\n// Registry data (single source of truth, drift-guarded by the registry test).\n// Bare patterns mapped to `--exclude=` at the rsync call. Highlights: the\n// `state_*.sqlite*` threads index is the resume-cwd source (rebuilt in-box from\n// rollouts, so seeding it would trap a teleported session at the host cwd);\n// `packages`/`plugins/.plugin-appserver`/`computer-use` are heavy macOS-only\n// artifacts that balloon the staged tarball (~800 MB → ~0.5 MB).\nconst CODEX_STATIC_EXCLUDES = resolveAgentSpec('codex').staticPaths[0]?.exclude ?? [];\n\nconst CODEX_KEYCHAIN_WARNING =\n 'codex: ~/.codex/auth.json missing. On macOS the codex CLI defaults to ' +\n 'storing the OAuth token in the system Keychain, which isn\\'t reachable ' +\n 'from a remote sandbox. To share creds with cloud boxes either:\\n' +\n ' - add `cli_auth_credentials_store = \"file\"` to ~/.codex/config.toml ' +\n 'then re-run `codex login`, or\\n' +\n ' - set OPENAI_API_KEY in your environment, or\\n' +\n ' - run `codex login --with-api-key` for a file-backed login.\\n' +\n 'Skipping codex seed; in-box codex will prompt for sign-in.';\n\n/**\n * Filtered tarball of `~/.codex/` **excluding** `auth.json`. Extracts into\n * `/home/vscode/.codex/` on the sandbox FS at snapshot-bake time.\n *\n * `-L` dereferences EVERY symlink (codex sprouts links into `~/.nvm` for the\n * `applypatch` argv0 trick and into `~/.agents/skills/*`); produces a\n * symlink-free archive suitable for the FUSE-backed Daytona volume and the\n * sandbox FS alike. Broken symlinks would abort rsync under `-L`, so pre-scan\n * and skip them.\n */\n/**\n * Best-effort, in-place sanitize of a staged `config.toml`: drops host-only-path\n * `mcp_servers` / `notify` / local marketplaces via {@link\n * sanitizeCodexConfigForBox}. A missing file, a parse failure, or any IO error\n * leaves the file untouched — staging must never fail on config sanitization.\n */\nasync function sanitizeStagedCodexConfig(configPath: string, hostHome: string): Promise<void> {\n try {\n if (!(await pathExists(configPath))) return;\n const { text, changed } = sanitizeCodexConfigForBox(await readFile(configPath, 'utf8'), hostHome);\n if (changed) await writeFile(configPath, text);\n } catch {\n // leave the rsynced copy as-is\n }\n}\n\nexport async function stageCodexStaticForUpload(\n opts: StageCodexOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostCodex = join(hostHome, '.codex');\n if (!(await pathExists(hostCodex))) return emptyResult();\n\n const stageDir = await mkStageDir('codex-static');\n let tarballPath: string | null = null;\n try {\n const codexBroken = await findBrokenSymlinks(hostCodex);\n await execa('rsync', [\n '-a',\n '-L',\n ...codexBroken.map((r) => `--exclude=/${r}`),\n ...CODEX_STATIC_EXCLUDES.map((p) => `--exclude=${p}`),\n `${hostCodex}/`,\n `${stageDir}/`,\n ]);\n // Strip host-only-path entries (desktop-Codex.app MCP servers like\n // node_repl, a macOS notify helper, local-source marketplaces) from the\n // staged config.toml so the in-box codex doesn't try to exec macOS paths.\n // Best-effort: a parse failure leaves the rsynced copy intact.\n await sanitizeStagedCodexConfig(join(stageDir, 'config.toml'), hostHome);\n tarballPath = await tarballFromDir(stageDir, 'codex-static');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n// ---------- agents (shared ~/.agents skills) ----------\n\n/**\n * Filtered tarball of `~/.agents/` (the cross-agent \"Agent Skills\" dir).\n * Extracts into `/home/vscode/.agents/` on the sandbox FS at snapshot-bake time\n * so the in-box agents (codex reads `~/.agents/skills` directly) see the same\n * skill set the host does. `-L` dereferences each skill's symlinks into real\n * files; broken ones are excluded so the sync can't abort.\n */\nexport async function stageAgentsStaticForUpload(\n opts: { hostHome?: string } = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostAgents = join(hostHome, '.agents');\n if (!(await pathExists(hostAgents))) return emptyResult();\n\n const stageDir = await mkStageDir('agents-static');\n let tarballPath: string | null = null;\n try {\n const broken = await findBrokenSymlinks(hostAgents);\n await execa('rsync', [\n '-a',\n '-L',\n ...broken.map((r) => `--exclude=/${r}`),\n `${hostAgents}/`,\n `${stageDir}/`,\n ]);\n tarballPath = await tarballFromDir(stageDir, 'agents-static');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n/**\n * Tarball with **only** `auth.json`. Prefers the cloud backup\n * `~/.agentbox/codex-credentials.json` (a login captured from a previous cloud\n * box by `extractCloudAgentCredentials`); falls back to the host's real\n * `~/.codex/auth.json` so a fresh project still bootstraps from a host login.\n * Surfaces the macOS Keychain landmine as a warning when neither exists — see\n * `CODEX_KEYCHAIN_WARNING`.\n */\nexport async function stageCodexCredentialsForUpload(\n opts: StageCodexOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n // Prefer the cloud backup under <hostHome>/.agentbox. Derive it from hostHome\n // (rather than the module-load `CODEX_CREDENTIALS_BACKUP_FILE` constant) so the\n // path tracks the active home: production uses the real home — identical to the\n // constant — while tests/callers can redirect the whole lookup via hostHome.\n const cloudBackup = join(hostHome, '.agentbox', 'codex-credentials.json');\n if (await pathExists(cloudBackup)) {\n return stageSingleFileTarball('codex-creds', cloudBackup, 'auth.json');\n }\n const hostAuth = join(hostHome, '.codex', 'auth.json');\n if (!(await pathExists(hostAuth))) return emptyResult([CODEX_KEYCHAIN_WARNING]);\n return stageSingleFileTarball('codex-creds', hostAuth, 'auth.json');\n}\n\n// ---------- opencode ----------\n\nexport interface StageOpencodeOptions {\n hostHome?: string;\n}\n\n// Registry data (single source of truth, drift-guarded by the registry test).\n// Bare patterns mapped to `--exclude=` at the rsync call. `auth.json` ships\n// separately; the rest is host-only runtime state.\nconst OPENCODE_DATA_EXCLUDES = resolveAgentSpec('opencode').staticPaths[0]?.exclude ?? [];\n\n/**\n * Filtered tarball of opencode static config. Layout extracts into\n * `/home/vscode/.local/share/opencode/`:\n *\n * ./<data files> ← from ~/.local/share/opencode/ (minus auth.json)\n * ./config/<config files> ← from ~/.config/opencode/\n *\n * `auth.json` is **excluded** — it ships separately via the credentials\n * variant.\n */\nexport async function stageOpencodeStaticForUpload(\n opts: StageOpencodeOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostData = join(hostHome, '.local', 'share', 'opencode');\n const hostConfig = join(hostHome, '.config', 'opencode');\n const hasData = await pathExists(hostData);\n const hasConfig = await pathExists(hostConfig);\n if (!hasData && !hasConfig) return emptyResult();\n\n const stageDir = await mkStageDir('opencode-static');\n let tarballPath: string | null = null;\n try {\n // `-L` dereferences every symlink — Daytona's FUSE volumes reject symlink\n // creation, and the sandbox FS doesn't care either way. Broken symlinks\n // would abort rsync under `-L`, so pre-scan and skip them.\n if (hasData) {\n const dataBroken = await findBrokenSymlinks(hostData);\n await execa('rsync', [\n '-a',\n '-L',\n ...dataBroken.map((r) => `--exclude=/${r}`),\n ...OPENCODE_DATA_EXCLUDES.map((p) => `--exclude=${p}`),\n `${hostData}/`,\n `${stageDir}/`,\n ]);\n }\n if (hasConfig) {\n const configStage = join(stageDir, 'config');\n const cfgBroken = await findBrokenSymlinks(hostConfig);\n await execa('rsync', [\n '-a',\n '-L',\n ...cfgBroken.map((r) => `--exclude=/${r}`),\n `${hostConfig}/`,\n `${configStage}/`,\n ]);\n }\n tarballPath = await tarballFromDir(stageDir, 'opencode-static');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n/**\n * Tarball with **only** `auth.json`. Prefers the cloud backup\n * `~/.agentbox/opencode-credentials.json` (captured from a previous cloud box);\n * falls back to the host's real `~/.local/share/opencode/auth.json`. Returns an\n * empty result when neither exists.\n */\nexport async function stageOpencodeCredentialsForUpload(\n opts: StageOpencodeOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n // Cloud backup under <hostHome>/.agentbox, derived from hostHome (see the\n // codex stager above) so the path tracks the active home and tests stay\n // hermetic; production matches OPENCODE_CREDENTIALS_BACKUP_FILE.\n const cloudBackup = join(hostHome, '.agentbox', 'opencode-credentials.json');\n if (await pathExists(cloudBackup)) {\n return stageSingleFileTarball('opencode-creds', cloudBackup, 'auth.json');\n }\n const hostAuth = join(hostHome, '.local', 'share', 'opencode', 'auth.json');\n if (!(await pathExists(hostAuth))) return emptyResult();\n return stageSingleFileTarball('opencode-creds', hostAuth, 'auth.json');\n}\n\n/**\n * Tarball with **only** the selected-model state (`model.json`, sourced from\n * `~/.local/state/opencode/model.json`). Extracts to a box's state dir so a\n * fresh box inherits the host's active model instead of OpenCode's default.\n * Returns an empty result when the host has never picked a model.\n */\nexport async function stageOpencodeStateForUpload(\n opts: StageOpencodeOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostModel = join(hostHome, '.local', 'state', 'opencode', 'model.json');\n if (!(await pathExists(hostModel))) return emptyResult();\n return stageSingleFileTarball('opencode-state', hostModel, 'model.json');\n}\n\n// ---------- all-agent static bake (shared across cloud prepare paths) ----------\n\n/** Box-side dir each tool's static tarball extracts into. Provider-neutral —\n * the same target on every backend (docker model). */\nconst CLAUDE_STATIC_BOX_DIR = '/home/vscode/.claude';\nconst CODEX_STATIC_BOX_DIR = '/home/vscode/.codex';\nconst OPENCODE_STATIC_BOX_DIR = '/home/vscode/.local/share/opencode';\nconst AGENTS_STATIC_BOX_DIR = '/home/vscode/.agents';\n\nexport interface AgentStaticStage {\n kind: 'claude' | 'codex' | 'opencode' | 'agents';\n /** Absolute box path the static tarball extracts into. */\n extractDir: string;\n staged: StageResult;\n}\n\n/**\n * Stage all four host static-config trees in parallel, each paired with the\n * box-side dir it extracts into. This is the single source of truth for the\n * cloud prepare paths (vercel / hetzner / daytona / e2b): every provider walks\n * this list and supplies only its own upload + extract transport, never its own\n * copy of the producer→dir mapping. The caller must `staged.cleanup()` each\n * result after the build has picked the tarball up.\n */\nexport async function stageAllAgentStatic(\n opts: { hostWorkspace?: string } = {},\n): Promise<AgentStaticStage[]> {\n const [claude, codex, opencode, agents] = await Promise.all([\n stageClaudeStaticForUpload({ hostWorkspace: opts.hostWorkspace }),\n stageCodexStaticForUpload(),\n stageOpencodeStaticForUpload(),\n stageAgentsStaticForUpload(),\n ]);\n return [\n { kind: 'claude', extractDir: CLAUDE_STATIC_BOX_DIR, staged: claude },\n { kind: 'codex', extractDir: CODEX_STATIC_BOX_DIR, staged: codex },\n { kind: 'opencode', extractDir: OPENCODE_STATIC_BOX_DIR, staged: opencode },\n { kind: 'agents', extractDir: AGENTS_STATIC_BOX_DIR, staged: agents },\n ];\n}\n","export interface HookFilterResult<T = unknown> {\n data: T;\n removedCommands: string[];\n}\n\n/**\n * Predicate for the filter: does `command` look like it points at a host path\n * outside the project, i.e. under the user's host home directory?\n *\n * Uses `.includes(hostHome + '/')` so we also catch shell-quoted forms like\n * `bash -c '/Users/marco/.config/iterm2/cc-status'`. The trailing slash gates\n * against false matches on similar-prefix home dirs (e.g. `/Users/marco`\n * shouldn't match `/Users/marco-other/...`).\n *\n * Returns false when `hostHome` is empty so we degrade safely if no home is\n * resolvable for some reason.\n */\nexport function isHostPathHookCommand(command: string, hostHome: string): boolean {\n if (typeof command !== 'string' || command.length === 0) return false;\n if (hostHome.length === 0) return false;\n return command.includes(hostHome + '/');\n}\n\ninterface HookLeaf {\n type?: string;\n command?: string;\n [k: string]: unknown;\n}\n\ninterface HookMatcherEntry {\n hooks?: unknown;\n [k: string]: unknown;\n}\n\n/**\n * Walk Claude Code's documented `hooks.<Trigger>[].hooks[]` structure and drop\n * any leaf `{ type: 'command', command: '<host-path>' }` whose `command` matches\n * {@link isHostPathHookCommand}. Empty `hooks: []` arrays and their matcher\n * wrappers are left intact — they don't break Claude and avoiding recursive\n * cleanup keeps the filter predictable.\n *\n * Returns a deep clone; input is not mutated. Tolerant of unexpected shapes\n * (string, number, null at any level): unrecognized branches pass through\n * unchanged, removed count stays accurate.\n */\nexport function filterHostHooks<T = unknown>(data: T, hostHome: string): HookFilterResult<T> {\n // structuredClone is in node >= 17; the repo targets node20, so this is safe.\n const clone = structuredClone(data) as unknown;\n const removedCommands: string[] = [];\n\n if (clone === null || typeof clone !== 'object' || Array.isArray(clone)) {\n return { data: clone as T, removedCommands };\n }\n\n const top = clone as { hooks?: unknown };\n const hooksRoot = top.hooks;\n if (hooksRoot === null || typeof hooksRoot !== 'object' || Array.isArray(hooksRoot)) {\n return { data: clone as T, removedCommands };\n }\n\n for (const triggerName of Object.keys(hooksRoot as Record<string, unknown>)) {\n const triggerValue = (hooksRoot as Record<string, unknown>)[triggerName];\n if (!Array.isArray(triggerValue)) continue;\n for (const entry of triggerValue) {\n if (entry === null || typeof entry !== 'object') continue;\n const matcher = entry as HookMatcherEntry;\n const inner = matcher.hooks;\n if (!Array.isArray(inner)) continue;\n // In-place filter on the cloned array.\n for (let i = inner.length - 1; i >= 0; i--) {\n const leaf = inner[i] as HookLeaf | null;\n if (leaf === null || typeof leaf !== 'object') continue;\n if (\n leaf.type === 'command' &&\n typeof leaf.command === 'string' &&\n isHostPathHookCommand(leaf.command, hostHome)\n ) {\n removedCommands.push(leaf.command);\n inner.splice(i, 1);\n }\n }\n }\n }\n\n return { data: clone as T, removedCommands };\n}\n\nexport interface SetInstallMethodNativeResult<T = unknown> {\n data: T;\n applied: boolean;\n}\n\nexport interface AddProjectAliasResult<T = unknown> {\n data: T;\n aliased: boolean;\n}\n\nexport interface TrustWorkspaceResult<T = unknown> {\n data: T;\n trusted: boolean;\n}\n\n/**\n * Force `projects[workspacePath].hasTrustDialogAccepted = true` in a parsed\n * `~/.claude.json`, creating the `projects` map and the project entry if\n * absent.\n *\n * The box is a sandbox: the agent is created explicitly to work in\n * `/workspace`, and the box is isolated from the host — so the folder-trust\n * dialog is pointless there. More importantly, Claude Code, when it opens an\n * *untrusted* folder, sends a malformed first API request that Anthropic\n * rejects with `400 role 'system' is not supported on this model`. Pre-trusting\n * the box's workspace skips the dialog *and* dodges that bug.\n *\n * Returns a deep-cloned, modified copy plus a flag for whether anything\n * changed (`false` when it was already trusted). Input is not mutated; no-op\n * for non-object data or an empty path.\n */\nexport function trustWorkspace<T = unknown>(\n data: T,\n workspacePath: string,\n): TrustWorkspaceResult<T> {\n const clone = structuredClone(data) as unknown;\n if (clone === null || typeof clone !== 'object' || Array.isArray(clone)) {\n return { data: clone as T, trusted: false };\n }\n if (workspacePath.length === 0) return { data: clone as T, trusted: false };\n const obj = clone as { projects?: unknown };\n if (obj.projects === null || typeof obj.projects !== 'object' || Array.isArray(obj.projects)) {\n obj.projects = {};\n }\n const projects = obj.projects as Record<string, unknown>;\n const existing = projects[workspacePath];\n const entry =\n existing !== null && typeof existing === 'object' && !Array.isArray(existing)\n ? (existing as Record<string, unknown>)\n : {};\n if (entry.hasTrustDialogAccepted === true) {\n projects[workspacePath] = entry;\n return { data: clone as T, trusted: false };\n }\n entry.hasTrustDialogAccepted = true;\n projects[workspacePath] = entry;\n return { data: clone as T, trusted: true };\n}\n\n/**\n * Claude Code keys project-scoped state (history, mcpServers, enabledPlugins,\n * trust prompts) under `projects[<absolute-workspace-path>]` in\n * `~/.claude.json`. On the host the key is something like\n * `/Users/marco/Projects/foo`; inside the box the workspace is always\n * `/workspace`. Without rewriting, the box never sees the host's project-\n * scoped settings.\n *\n * Copy (don't move) the host-keyed entry to `toPath` if present. Existing\n * `projects[toPath]` is preserved by merging the host entry on top — host\n * is authoritative for keys it sets; box-only keys (e.g. session ids\n * accumulated inside earlier boxes) stay intact.\n *\n * No-op (returns `aliased: false`) when:\n * - data isn't an object, or `projects` isn't an object\n * - fromPath equals toPath\n * - projects[fromPath] doesn't exist or isn't an object\n *\n * Returns a deep-cloned, modified copy; input is not mutated.\n */\nexport function addProjectAlias<T = unknown>(\n data: T,\n fromPath: string,\n toPath: string,\n): AddProjectAliasResult<T> {\n const clone = structuredClone(data) as unknown;\n if (clone === null || typeof clone !== 'object' || Array.isArray(clone)) {\n return { data: clone as T, aliased: false };\n }\n if (fromPath === toPath || fromPath.length === 0 || toPath.length === 0) {\n return { data: clone as T, aliased: false };\n }\n const obj = clone as { projects?: unknown };\n const projects = obj.projects;\n if (projects === null || typeof projects !== 'object' || Array.isArray(projects)) {\n return { data: clone as T, aliased: false };\n }\n const projectsMap = projects as Record<string, unknown>;\n const src = projectsMap[fromPath];\n if (src === null || typeof src !== 'object' || Array.isArray(src)) {\n return { data: clone as T, aliased: false };\n }\n const existing = projectsMap[toPath];\n if (existing !== null && typeof existing === 'object' && !Array.isArray(existing)) {\n projectsMap[toPath] = { ...(existing as Record<string, unknown>), ...(src as Record<string, unknown>) };\n } else {\n projectsMap[toPath] = structuredClone(src);\n }\n return { data: clone as T, aliased: true };\n}\n\n/**\n * Force the install-method fields in a parsed `~/.claude.json` to match the\n * box's native install. Sets exactly what `claude install` writes:\n * installMethod: \"native\"\n * autoUpdates: false\n * autoUpdatesProtectedForNative: true\n *\n * Without this, the in-box claude reports\n * `Running native installation but config install method is 'not set'` in\n * /status — the host's value (often `npm-global` on Mac, or absent) doesn't\n * match the box's `~/.local/bin/claude` install location, and merely\n * clearing the field leaves it unset rather than fixing it.\n *\n * Returns a deep-cloned, fixed copy plus a flag indicating whether any of\n * the three fields actually changed. Input is not mutated.\n */\nexport function setInstallMethodNative<T = unknown>(data: T): SetInstallMethodNativeResult<T> {\n const clone = structuredClone(data) as unknown;\n if (clone === null || typeof clone !== 'object' || Array.isArray(clone)) {\n return { data: clone as T, applied: false };\n }\n const obj = clone as Record<string, unknown>;\n const changed =\n obj.installMethod !== 'native' ||\n obj.autoUpdates !== false ||\n obj.autoUpdatesProtectedForNative !== true;\n obj.installMethod = 'native';\n obj.autoUpdates = false;\n obj.autoUpdatesProtectedForNative = true;\n return { data: clone as T, applied: changed };\n}\n","import { homedir } from 'node:os';\nimport { parse, stringify } from 'smol-toml';\n\n/**\n * Sanitize the host's `~/.codex/config.toml` before it is seeded into a box.\n *\n * The host config routinely points at host-only absolute paths — the desktop\n * Codex.app's bundled MCP servers (`/Applications/Codex.app/...`), a macOS\n * `notify` helper, and local-source plugin marketplaces under the host home.\n * None of those exist in the Linux box, so in-box codex emits startup warnings\n * (`MCP client for \\`node_repl\\` failed to start: No such file or directory`,\n * etc.). We strip exactly the entries whose paths cannot resolve in the box and\n * leave everything else (model, reasoning effort, project trust, features, and\n * any MCP server reachable via PATH or a Linux-plausible absolute path).\n */\n\n/**\n * True when `cmd` is an absolute path under a location guaranteed absent in the\n * Linux box: the host home, or a macOS-only / host-package root. Bare program\n * names (PATH-resolved, e.g. `node`, `npx`, `uvx`) and Linux-plausible\n * absolutes (`/usr/...`, `/bin/...`) are kept — we never over-strip.\n */\nexport function isHostOnlyPath(cmd: unknown, hostHome: string): boolean {\n if (typeof cmd !== 'string' || cmd.length === 0) return false;\n if (!cmd.startsWith('/')) return false; // PATH-resolved bare name — may exist in box\n const hostOnlyRoots = [\n hostHome.endsWith('/') ? hostHome : `${hostHome}/`,\n '/Applications/',\n '/opt/homebrew/',\n '/Library/',\n '/System/',\n '/private/',\n '/Users/',\n ];\n return hostOnlyRoots.some((root) => cmd.startsWith(root));\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** The box workspace path — Codex must trust it so it doesn't pop the \"trust\n * this folder?\" prompt on first attach. Same value the docker + cloud paths\n * mount the project at. */\nexport const BOX_WORKSPACE = '/workspace';\n\n/** Minimal config.toml that pre-trusts `/workspace`, for a host with no\n * `~/.codex/config.toml` to sanitize (so the box still skips the trust prompt). */\nexport const MINIMAL_TRUSTED_CODEX_CONFIG = `[projects.\"${BOX_WORKSPACE}\"]\\ntrust_level = \"trusted\"\\n`;\n\nexport interface SanitizeCodexConfigResult {\n /** Sanitized TOML (re-serialized); equals the input semantically when `changed` is false. */\n text: string;\n /** True when at least one host-only entry was stripped. */\n changed: boolean;\n}\n\n/**\n * Parse → mutate → re-serialize the codex `config.toml`, dropping entries that\n * reference host-only paths. Throws on a TOML parse failure so callers can fall\n * back to copying the file verbatim. Reformatting (lost comments / reordered\n * keys) is acceptable: the box copy is derived and consumed only by in-box codex.\n *\n * Returns `changed: false` (so callers can keep the host's original copy\n * untouched) when nothing host-only was found.\n */\nexport function sanitizeCodexConfigForBox(\n tomlText: string,\n hostHome: string = homedir(),\n): SanitizeCodexConfigResult {\n const cfg = parse(tomlText) as Record<string, unknown>;\n let changed = false;\n\n // mcp_servers: drop servers whose `command` is a host-only path.\n if (isRecord(cfg['mcp_servers'])) {\n const servers = cfg['mcp_servers'];\n for (const [name, def] of Object.entries(servers)) {\n if (isRecord(def) && isHostOnlyPath(def['command'], hostHome)) {\n delete servers[name];\n changed = true;\n }\n }\n }\n\n // notify: an array whose first element is the program to run. Drop the key\n // when that program is a host-only path.\n const notify = cfg['notify'];\n if (Array.isArray(notify) && isHostOnlyPath(notify[0], hostHome)) {\n delete cfg['notify'];\n changed = true;\n }\n\n // marketplaces: drop local-source marketplaces under a host-only path, then\n // drop the plugins that reference them (`\"<plugin>@<marketplace>\"`).\n const droppedMarkets = new Set<string>();\n if (isRecord(cfg['marketplaces'])) {\n const markets = cfg['marketplaces'];\n for (const [name, def] of Object.entries(markets)) {\n if (\n isRecord(def) &&\n def['source_type'] === 'local' &&\n isHostOnlyPath(def['source'], hostHome)\n ) {\n delete markets[name];\n droppedMarkets.add(name);\n changed = true;\n }\n }\n }\n if (droppedMarkets.size > 0 && isRecord(cfg['plugins'])) {\n const plugins = cfg['plugins'];\n for (const key of Object.keys(plugins)) {\n const marketplace = key.split('@')[1];\n if (marketplace !== undefined && droppedMarkets.has(marketplace)) {\n delete plugins[key];\n changed = true;\n }\n }\n }\n\n // Pre-trust the box workspace so codex doesn't prompt \"trust this folder?\" on\n // first attach. The box mounts the project at /workspace; the host config only\n // trusts host-absolute project paths, never /workspace. (Codex's own\n // path-based `[projects.\"<path>\"].trust_level` is stable — unlike the\n // hash-based hook trust — so this is safe to persist.)\n if (!isRecord(cfg['projects'])) cfg['projects'] = {};\n const projects = cfg['projects'] as Record<string, unknown>;\n const wsEntry = isRecord(projects[BOX_WORKSPACE]) ? projects[BOX_WORKSPACE] : {};\n if (wsEntry['trust_level'] !== 'trusted') {\n wsEntry['trust_level'] = 'trusted';\n projects[BOX_WORKSPACE] = wsEntry;\n changed = true;\n }\n\n return { text: changed ? stringify(cfg) : tomlText, changed };\n}\n","/**\n * Cross-provider versioning primitives for `~/.agentbox/<provider>-prepared.json`.\n *\n * Each provider records what it has baked (docker image / hetzner snapshot /\n * daytona snapshot) under a per-provider JSON file with a shared `base.*`\n * substructure so the CLI can detect when the on-disk artifact is stale\n * relative to the current CLI's build context.\n *\n * The invalidation key is `base.contextSha256`: a deterministic SHA-256\n * over every file in the build context (Dockerfile + scripts + baked\n * config), keyed by the file's relative path. Two CLIs with the same\n * staged runtime tree produce the same hash; an edit to any baked asset\n * — even a one-byte tweak to `custom-system-CLAUDE.md` — flips it.\n *\n * Checkpoints embed the captured `contextSha256` so restoring an older\n * checkpoint can warn the user that the baked layers predate the current\n * base image.\n */\n\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, resolve as pathResolve } from 'node:path';\n\nimport type { ProviderKind } from '@agentbox/config';\n\n/**\n * Providers that bake a `~/.agentbox/<provider>-prepared.json` artifact. The\n * built-in set is the config `ProviderKind`; the `(string & {})` arm keeps\n * autocomplete for those while also admitting an external plugin's open-string\n * provider name (a plugin manages its own prepared-state — see docs/provider-plugins.md).\n */\nexport type PreparedProviderKind = ProviderKind | (string & {});\n\n/**\n * The cross-provider record. `TImage` is the provider's opaque image\n * identifier: a string tag for docker/daytona, a numeric image id for\n * hetzner. The `TExtra` slot lets a provider attach provider-specific\n * fields (e.g. hetzner's `description` and `projects[]`) without forking\n * the whole shape.\n */\nexport interface PreparedBaseSnapshot<TImage = string, TExtra = unknown> {\n /** Schema version. Bumped when the on-disk shape changes incompatibly. */\n schema: number;\n base?: {\n /** Provider-opaque image identifier (docker tag | hetzner imageId | daytona snapshot name). */\n imageRef: TImage;\n /** Deterministic SHA-256 of the build context — the invalidation key. */\n contextSha256: string;\n /** Informational: CLI version that produced this artifact. */\n cliVersion: string;\n /** Informational: git short SHA injected at CLI build time (or 'dev'). */\n cliCommit?: string;\n /** ISO timestamp of bake completion. */\n createdAt: string;\n };\n /** Provider-specific extras (e.g. hetzner's per-project snapshot tier). */\n extras?: TExtra;\n}\n\nexport function preparedStatePathFor(provider: PreparedProviderKind): string {\n // The name lands in a filename; a plugin's open-string name could otherwise\n // carry a path separator. Provider names are `[a-z0-9-]` by convention — reject\n // anything else rather than resolve outside ~/.agentbox.\n if (!/^[A-Za-z0-9._-]+$/.test(provider)) {\n throw new Error(`invalid provider name for prepared-state: ${JSON.stringify(provider)}`);\n }\n return pathResolve(homedir(), '.agentbox', `${provider}-prepared.json`);\n}\n\n/**\n * Read the prepared-state file for `provider`. Returns `null` when the file\n * is missing, malformed, or carries a schema this code doesn't recognise —\n * callers treat all three as \"rebuild needed\". Sync so it can run from\n * non-async setup paths (mirrors the hetzner helper it generalises).\n */\nexport function readPreparedStateRaw(provider: PreparedProviderKind): unknown {\n const path = preparedStatePathFor(provider);\n if (!existsSync(path)) return null;\n try {\n return JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n return null;\n }\n}\n\n/**\n * Atomic write: write to `<path>.tmp` then rename. `mode: 0o600` because\n * the file is informational but lives alongside `secrets.env` — same dir,\n * same permissions hygiene.\n */\nexport function writePreparedStateRaw(provider: PreparedProviderKind, state: unknown): void {\n const path = preparedStatePathFor(provider);\n mkdirSync(dirname(path), { recursive: true });\n const body = JSON.stringify(state, null, 2) + '\\n';\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, body, { mode: 0o600 });\n renameSync(tmp, path);\n}\n\nexport async function sha256OfFile(path: string): Promise<string> {\n const buf = await readFile(path);\n return createHash('sha256').update(buf).digest('hex');\n}\n\nexport interface ContextFile {\n /**\n * Logical relative path. Used as the canonical key for hash determinism\n * — two stagings with identical contents but different absolute paths\n * must hash the same.\n */\n rel: string;\n /** Absolute path the file is read from. */\n abs: string;\n}\n\n/**\n * Deterministic hash over a set of context files. Entries are sorted by\n * `rel` then hashed as `<rel>\\0<sha256(file)>\\n` lines into a final SHA-256.\n *\n * - Sort order = determinism (the caller can pass files in any order).\n * - NUL separator = no collision between a `rel` ending in hex and the\n * following digest.\n * - Trailing newline per record = stable framing.\n *\n * Missing files raise — silently skipping would let a partial dev rebuild\n * stamp a hash that doesn't represent what's actually in the image.\n */\nexport async function computeContextSha256(files: ContextFile[]): Promise<string> {\n const sorted = [...files].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));\n const outer = createHash('sha256');\n for (const f of sorted) {\n const inner = await sha256OfFile(f.abs);\n outer.update(`${f.rel}\\0${inner}\\n`);\n }\n return outer.digest('hex');\n}\n\n/** Short form for log lines — first 12 hex chars of a sha256. */\nexport function shortFingerprint(sha: string): string {\n return sha.slice(0, 12);\n}\n\n/**\n * Fold the Claude install method into a base context fingerprint so switching\n * `box.claudeInstall` native↔npm forces a re-bake. `native` returns the base\n * hash unchanged — existing native snapshots keep their fingerprint and never\n * spuriously rebuild; only `npm` derives a distinct hash.\n */\nexport function claudeInstallFingerprint(baseSha: string, mode: 'native' | 'npm'): string {\n if (mode === 'native') return baseSha;\n return createHash('sha256').update(`${baseSha}\\0claude-install=npm`).digest('hex');\n}\n\n/**\n * CLI version stamps set by `apps/cli/src/index.ts` at startup via env vars\n * (the values themselves come from tsup's build-time `define`). Providers\n * record them onto prepared-state files and checkpoint manifests so a stale\n * artifact carries a human-readable hint about which CLI built it.\n *\n * Fallbacks cover the unit-test and unbundled-dev paths (the CLI never\n * loaded, env unset). `unknown` is a sentinel — never a real version.\n */\nexport interface CliStamp {\n cliVersion: string;\n cliCommit: string;\n}\n\nexport function readCliStamp(): CliStamp {\n return {\n cliVersion: process.env.AGENTBOX_CLI_VERSION ?? 'unknown',\n cliCommit: process.env.AGENTBOX_CLI_COMMIT ?? 'unknown',\n };\n}\n\n/**\n * Canonical map of files that go into the Docker base image build context\n * — every file `Dockerfile.box` COPYs, plus the Dockerfile itself. Two\n * layouts resolve the same logical entries:\n *\n * - staged: `<contextDir>/<staged>` (production CLI runtime + dev with `apps/cli/runtime/docker`)\n * - dev: `<sandboxDockerRoot>/<dev>` (workspace dev, no staged tree)\n *\n * Shared across providers because:\n * - sandbox-docker uses it to fingerprint its locally-built image.\n * - sandbox-daytona uses it to fingerprint the snapshot it bakes from the\n * same Dockerfile.box + the daytona-specific CLAUDE.md overlay.\n *\n * If you add a COPY line to `Dockerfile.box`, add the file here AND in\n * `apps/cli/scripts/stage-runtime.mjs` — failure to do so means the image\n * won't get re-built when that file changes.\n */\nexport const DOCKER_CONTEXT_FILE_MAP: Record<string, { staged: string; dev: string }> = {\n 'Dockerfile.box': { staged: 'Dockerfile.box', dev: 'Dockerfile.box' },\n 'ctl/bin.cjs': {\n staged: 'packages/ctl/dist/bin.cjs',\n dev: '../ctl/dist/bin.cjs',\n },\n 'share/agentbox-setup/SKILL.md': {\n staged: 'apps/cli/share/agentbox-setup/SKILL.md',\n dev: '../../apps/cli/share/agentbox-setup/SKILL.md',\n },\n 'scripts/agentbox-vnc-start': {\n staged: 'packages/sandbox-docker/scripts/agentbox-vnc-start',\n dev: 'scripts/agentbox-vnc-start',\n },\n 'scripts/agentbox-dockerd-start': {\n staged: 'packages/sandbox-docker/scripts/agentbox-dockerd-start',\n dev: 'scripts/agentbox-dockerd-start',\n },\n 'scripts/agentbox-checkpoint-cleanup': {\n staged: 'packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup',\n dev: 'scripts/agentbox-checkpoint-cleanup',\n },\n 'scripts/agentbox-open': {\n staged: 'packages/sandbox-docker/scripts/agentbox-open',\n dev: 'scripts/agentbox-open',\n },\n 'scripts/custom-system-CLAUDE.md': {\n staged: 'packages/sandbox-docker/scripts/custom-system-CLAUDE.md',\n dev: 'scripts/custom-system-CLAUDE.md',\n },\n 'scripts/claude-managed-settings.json': {\n staged: 'packages/sandbox-docker/scripts/claude-managed-settings.json',\n dev: 'scripts/claude-managed-settings.json',\n },\n 'scripts/agentbox-codex-hooks.json': {\n staged: 'packages/sandbox-docker/scripts/agentbox-codex-hooks.json',\n dev: 'scripts/agentbox-codex-hooks.json',\n },\n};\n\n/**\n * Resolve every entry in `fileMap` to an absolute path. Tries `<contextDir>/<staged>`\n * first; falls back to `<devRoot>/<dev>`. Returns `null` if any required file\n * is missing — callers treat that as \"can't fingerprint\" and skip the\n * cache-hit shortcut. Pure (no I/O beyond `existsSync`), so safe for use\n * from the provider's prepare path.\n */\nexport function resolveContextFilesFrom(\n fileMap: Record<string, { staged: string; dev: string }>,\n opts: { contextDir: string; devRoot: string },\n): ContextFile[] | null {\n const out: ContextFile[] = [];\n for (const [rel, paths] of Object.entries(fileMap)) {\n const candidates = [\n pathResolve(opts.contextDir, paths.staged),\n pathResolve(opts.devRoot, paths.dev),\n ];\n const hit = candidates.find((p) => existsSync(p));\n if (!hit) return null;\n out.push({ rel, abs: hit });\n }\n return out;\n}\n","/**\n * Docker provider's `~/.agentbox/docker-prepared.json` reader/writer + the\n * build-context fingerprint that drives base-image invalidation.\n *\n * The fingerprint is a SHA-256 over every file `docker build` would COPY\n * into the image — Dockerfile + scripts + baked config files. Two CLIs\n * with identical staged runtime trees produce the same hash; a one-byte\n * edit to any baked asset flips it, which is the signal `ensureImage()`\n * uses to rebuild instead of reusing the cached image.\n */\n\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n computeContextSha256,\n DOCKER_CONTEXT_FILE_MAP,\n readCliStamp,\n readPreparedStateRaw,\n resolveContextFilesFrom,\n writePreparedStateRaw,\n type ContextFile,\n type PreparedBaseSnapshot,\n} from '@agentbox/sandbox-core';\nimport { BUILD_CONTEXT_DIR, DEFAULT_BOX_IMAGE, DOCKERFILE_PATH } from './image.js';\n\nconst SCHEMA = 1 as const;\n\nexport type PreparedDockerState = PreparedBaseSnapshot<string, never>;\n\n/**\n * Resolve every fingerprint input to an absolute path. The canonical file\n * list lives in `@agentbox/sandbox-core` (DOCKER_CONTEXT_FILE_MAP) so the\n * daytona provider can hash the same inputs without depending on this\n * package. Two layouts are tried in order, mirroring `resolveDockerBuild()`\n * in `image.ts`:\n * 1. Build context dir (staged runtime / env override).\n * 2. Sandbox-docker package root (dev fallback).\n *\n * Returns `null` when *any* required file is missing — callers treat that\n * as \"can't fingerprint\" and skip the cache-hit shortcut (always rebuild).\n */\nexport function resolveContextFiles(opts: { contextDir?: string } = {}): ContextFile[] | null {\n const ctx = opts.contextDir ?? BUILD_CONTEXT_DIR;\n const here = dirname(fileURLToPath(import.meta.url));\n // sandbox-docker's package root = parent of src/ or parent of dist/.\n const packageRoot = resolve(here, '..');\n return resolveContextFilesFrom(DOCKER_CONTEXT_FILE_MAP, {\n contextDir: ctx,\n devRoot: packageRoot,\n });\n}\n\nexport interface ResolvedFingerprint {\n contextSha256: string;\n /** Files that fed the hash (in canonical sorted order). */\n files: ContextFile[];\n}\n\nexport async function computeDockerContextFingerprint(opts: {\n contextDir?: string;\n} = {}): Promise<ResolvedFingerprint | null> {\n const files = resolveContextFiles(opts);\n if (!files) return null;\n return { contextSha256: await computeContextSha256(files), files };\n}\n\nexport function readPreparedDockerState(): PreparedDockerState | null {\n const raw = readPreparedStateRaw('docker');\n if (raw === null || typeof raw !== 'object') return null;\n const parsed = raw as Partial<PreparedDockerState>;\n if (parsed.schema !== SCHEMA) return null;\n return { schema: SCHEMA, base: parsed.base };\n}\n\nexport function writePreparedDockerState(opts: {\n imageRef?: string;\n contextSha256: string;\n}): void {\n const stamp = readCliStamp();\n const state: PreparedDockerState = {\n schema: SCHEMA,\n base: {\n imageRef: opts.imageRef ?? DEFAULT_BOX_IMAGE,\n contextSha256: opts.contextSha256,\n cliVersion: stamp.cliVersion,\n cliCommit: stamp.cliCommit,\n createdAt: new Date().toISOString(),\n },\n };\n writePreparedStateRaw('docker', state);\n}\n\n/** Convenience for `ensureImage` and `prepare` — true when the stamped fingerprint matches. */\nexport function preparedMatches(state: PreparedDockerState | null, current: string): boolean {\n return state?.base?.contextSha256 === current;\n}\n\n/** Re-export so callers don't reach into image.ts just for the Dockerfile path. */\nexport { DOCKERFILE_PATH };\n","import { execa } from 'execa';\nimport { existsSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, resolve } from 'node:path';\nimport { claudeInstallFingerprint } from '@agentbox/sandbox-core';\n\nexport const DEFAULT_BOX_IMAGE = 'agentbox/box:dev';\n\n/**\n * Resolve the effective `box.claudeInstall` for the current project. Docker\n * builds its image lazily at create time, so every `ensureImage` path must\n * agree on the mode or a native rebuild would clobber an npm-baked image (and\n * vice-versa). Lazy-imported to keep the module load cheap; falls back to\n * `native` if config can't be read.\n */\nasync function resolveClaudeInstallMode(): Promise<'native' | 'npm'> {\n try {\n const { loadEffectiveConfig } = await import('@agentbox/config');\n const cfg = await loadEffectiveConfig(process.cwd());\n return cfg.effective.box.claudeInstall;\n } catch {\n return 'native';\n }\n}\n\n/**\n * Public registry repo the box image is published to (see\n * `.github/workflows/box-image.yml`). The CLI pulls a fingerprint-tagged\n * image from here on first use instead of building locally — a multi-minute\n * build collapses to a `docker pull`. An empty registry (config override)\n * disables pulling and always builds.\n */\nexport const BOX_IMAGE_REGISTRY = 'ghcr.io/madarco/agentbox/box';\n\n/**\n * The pull target for a given build-context fingerprint. The tag *is* the\n * content identity: a local staged context that matches a published build\n * has the same sha, so a pull hit can be retagged to `agentbox/box:dev` and\n * stamped into docker-prepared.json without risk of a stale image (a locally\n * edited context has a different sha, its tag 404s, and we build instead).\n */\nexport function registryRefForSha(sha: string, registry: string = BOX_IMAGE_REGISTRY): string {\n return `${registry}:sha-${sha.slice(0, 16)}`;\n}\n\nconst here = dirname(fileURLToPath(import.meta.url));\n\n// The Dockerfile's COPY lines reference monorepo-relative paths\n// (packages/ctl/dist/bin.cjs, apps/cli/share/..., packages/sandbox-docker/scripts/*),\n// so the build context must be a dir containing that tree.\n//\n// Resolution order:\n// 0. AGENTBOX_DOCKER_CONTEXT env override (dir holding Dockerfile.box).\n// 1. Staged context shipped with the bundled `agent-box` package: this\n// module is bundled into the CLI at <root>/dist, the stage step mirrors\n// the COPY tree at <root>/runtime/docker (sibling of dist/, uniform in\n// dev and when installed).\n// 2. Legacy monorepo: Dockerfile.box at the sandbox-docker package root,\n// build context = monorepo root.\nfunction resolveDockerBuild(): { dockerfile: string; context: string } {\n const override = process.env.AGENTBOX_DOCKER_CONTEXT;\n if (override && existsSync(resolve(override, 'Dockerfile.box'))) {\n return { dockerfile: resolve(override, 'Dockerfile.box'), context: override };\n }\n const staged = resolve(here, '..', 'runtime', 'docker');\n if (existsSync(resolve(staged, 'Dockerfile.box'))) {\n return { dockerfile: resolve(staged, 'Dockerfile.box'), context: staged };\n }\n // Legacy: src/ (or the unbundled package dist/) is one level under the\n // package root; the monorepo root is two more up.\n const packageRoot = resolve(here, '..');\n return {\n dockerfile: resolve(packageRoot, 'Dockerfile.box'),\n context: resolve(packageRoot, '..', '..'),\n };\n}\n\nconst { dockerfile: DOCKERFILE_PATH_RESOLVED, context: BUILD_CONTEXT_DIR_RESOLVED } =\n resolveDockerBuild();\nexport const DOCKERFILE_PATH = DOCKERFILE_PATH_RESOLVED;\nexport const BUILD_CONTEXT_DIR = BUILD_CONTEXT_DIR_RESOLVED;\n\nexport async function imageExists(ref: string): Promise<boolean> {\n const result = await execa('docker', ['image', 'inspect', ref], { reject: false });\n return result.exitCode === 0;\n}\n\n/**\n * Attempt `docker pull <target>`. Returns true on success, false on any\n * failure (missing tag, offline, auth) — callers fall back to a local build.\n * Never throws. Single attempt: a missing tag is the expected \"build locally\"\n * signal, not a transient error worth retrying.\n */\nexport async function pullImage(\n target: string,\n opts: { onProgress?: (line: string) => void } = {},\n): Promise<boolean> {\n const subprocess = execa('docker', ['pull', target], {\n stderr: 'pipe',\n stdout: 'pipe',\n reject: false,\n });\n if (opts.onProgress) {\n const forward = (chunk: Buffer | string): void => {\n const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (line.length > 0) opts.onProgress?.(line);\n }\n };\n subprocess.stdout?.on('data', forward);\n subprocess.stderr?.on('data', forward);\n }\n const result = await subprocess;\n return result.exitCode === 0;\n}\n\nexport async function tagImage(source: string, target: string): Promise<void> {\n await execa('docker', ['tag', source, target]);\n}\n\nexport interface ImageInfo {\n /** Image ref (e.g. `agentbox/box:dev`). */\n ref: string;\n /** True when the engine has the image locally. */\n exists: boolean;\n /** Image size in bytes, when known. */\n sizeBytes?: number;\n /** ISO-8601 creation time, when known. */\n createdAt?: string;\n}\n\n/**\n * Read-only inspect of a Docker image. Used by `agentbox prepare` (no-args\n * status mode) to surface base-image state. Never throws — returns\n * `{ exists: false }` on any error so the status command works even when\n * the docker daemon is unreachable.\n */\nexport async function imageInfo(ref: string = DEFAULT_BOX_IMAGE): Promise<ImageInfo> {\n const result = await execa(\n 'docker',\n ['image', 'inspect', '--format', '{{.Size}}|{{.Created}}', ref],\n { reject: false },\n );\n if (result.exitCode !== 0) return { ref, exists: false };\n const [sizeStr, createdAt] = result.stdout.trim().split('|');\n const sizeBytes = sizeStr ? Number.parseInt(sizeStr, 10) : NaN;\n return {\n ref,\n exists: true,\n sizeBytes: Number.isFinite(sizeBytes) ? sizeBytes : undefined,\n createdAt: createdAt && createdAt.length > 0 ? createdAt : undefined,\n };\n}\n\nexport interface BuildImageOptions {\n ref?: string;\n dockerfile?: string;\n contextDir?: string;\n /** `--build-arg K=V` pairs forwarded to `docker build` (e.g. AGENTBOX_CLAUDE_INSTALL). */\n buildArgs?: Record<string, string>;\n onProgress?: (line: string) => void;\n}\n\nexport async function buildImage(opts: BuildImageOptions = {}): Promise<string> {\n const ref = opts.ref ?? DEFAULT_BOX_IMAGE;\n const dockerfile = opts.dockerfile ?? DOCKERFILE_PATH;\n const contextDir = opts.contextDir ?? BUILD_CONTEXT_DIR;\n\n // Dogfood path: when building from inside an agentbox (docker-in-docker),\n // the default bridge network can't bind-mount /proc/<pid>/ns/net for the\n // build container, breaking any RUN that needs network (e.g. apt, curl).\n // Falling back to host networking sidesteps the missing capability.\n const args = ['build', '-t', ref, '-f', dockerfile];\n for (const [k, v] of Object.entries(opts.buildArgs ?? {})) {\n args.push('--build-arg', `${k}=${v}`);\n }\n args.push(contextDir);\n if (process.env.AGENTBOX === '1') {\n args.splice(1, 0, '--network=host');\n }\n\n const subprocess = execa('docker', args, {\n stderr: 'pipe',\n stdout: 'pipe',\n });\n\n if (opts.onProgress) {\n const forward = (chunk: Buffer | string): void => {\n const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (line.length > 0) opts.onProgress?.(line);\n }\n };\n subprocess.stdout?.on('data', forward);\n subprocess.stderr?.on('data', forward);\n }\n\n await subprocess;\n return ref;\n}\n\nexport interface PullOrBuildOptions {\n onProgress?: (line: string) => void;\n /** Dockerfile path. Defaults to `Dockerfile.box` next to this package. */\n dockerfile?: string;\n /** Build context directory. Defaults to the staged runtime / monorepo root. */\n contextDir?: string;\n /** Try the registry before building. Defaults to true. */\n allowPull?: boolean;\n /** Registry repo to pull from. Defaults to `BOX_IMAGE_REGISTRY`; empty disables pulling. */\n registry?: string;\n /** `--build-arg K=V` pairs forwarded to the local `docker build` (ignored on a registry pull). */\n buildArgs?: Record<string, string>;\n}\n\n/**\n * Make `ref` present locally, preferring a registry pull over a local build.\n *\n * When `fingerprint` is non-null and pulling is allowed, pull the\n * fingerprint-tagged image and retag it to `ref`; on a miss (or when pulling\n * is disabled / unfingerprintable) build from the staged context. Either way,\n * a known fingerprint is stamped into docker-prepared.json so the next\n * `ensureImage()` treats this as a cache hit.\n */\nexport async function pullOrBuild(\n ref: string,\n fingerprint: { contextSha256: string } | null,\n opts: PullOrBuildOptions = {},\n): Promise<{ source: 'pulled' | 'built' }> {\n const { writePreparedDockerState } = await import('./prepared-state.js');\n const registry = opts.registry ?? BOX_IMAGE_REGISTRY;\n const allowPull = opts.allowPull !== false;\n\n if (allowPull && registry && fingerprint) {\n const target = registryRefForSha(fingerprint.contextSha256, registry);\n opts.onProgress?.(`[image] pulling ${target}`);\n if (await pullImage(target, { onProgress: opts.onProgress })) {\n await tagImage(target, ref);\n writePreparedDockerState({ imageRef: ref, contextSha256: fingerprint.contextSha256 });\n opts.onProgress?.(`[image] pulled ${target} -> ${ref}`);\n return { source: 'pulled' };\n }\n opts.onProgress?.(`[image] registry miss, building ${ref} locally`);\n }\n\n await buildImage({\n ref,\n dockerfile: opts.dockerfile,\n contextDir: opts.contextDir,\n buildArgs: opts.buildArgs,\n onProgress: opts.onProgress,\n });\n if (fingerprint) {\n writePreparedDockerState({ imageRef: ref, contextSha256: fingerprint.contextSha256 });\n }\n return { source: 'built' };\n}\n\nexport interface EnsureImageOptions {\n onProgress?: (line: string) => void;\n /** Dockerfile path. Defaults to `Dockerfile.box` next to this package. */\n dockerfile?: string;\n /** Build context directory. Defaults to the monorepo root. */\n contextDir?: string;\n /** Try the registry before building. Defaults to true. */\n allowPull?: boolean;\n /** Registry repo to pull from. Defaults to `BOX_IMAGE_REGISTRY`; empty disables pulling. */\n registry?: string;\n /**\n * How Claude Code is installed into the image. Folded into the build-context\n * fingerprint so a mode switch rebuilds (and an npm image isn't clobbered by\n * a native rebuild). Defaults to the resolved `box.claudeInstall`.\n */\n claudeInstall?: 'native' | 'npm';\n}\n\nexport async function ensureImage(\n ref: string = DEFAULT_BOX_IMAGE,\n opts: EnsureImageOptions = {},\n): Promise<{ ref: string; built: boolean; reason?: string }> {\n // Lazy import: prepared-state imports back into image.ts for the default\n // DOCKERFILE_PATH/BUILD_CONTEXT_DIR constants, so loading it at top-level\n // would create a circular ESM init order.\n const { computeDockerContextFingerprint, readPreparedDockerState, preparedMatches } =\n await import('./prepared-state.js');\n\n const claudeInstall = opts.claudeInstall ?? (await resolveClaudeInstallMode());\n const rawFingerprint = await computeDockerContextFingerprint({\n contextDir: opts.contextDir,\n });\n // Fold the install mode into the sha so native↔npm are distinct cache\n // identities (`native` leaves the hash unchanged).\n const fingerprint = rawFingerprint\n ? {\n ...rawFingerprint,\n contextSha256: claudeInstallFingerprint(rawFingerprint.contextSha256, claudeInstall),\n }\n : null;\n const prepared = readPreparedDockerState();\n const exists = await imageExists(ref);\n\n let reason: string | undefined;\n if (!exists) {\n reason = `image ${ref} not present`;\n } else if (!fingerprint) {\n // Couldn't enumerate the context (partial dev rebuild?). Don't rebuild\n // unconditionally — that would surprise users mid-iteration. Trust the\n // image-exists check and leave the prepared file untouched.\n return { ref, built: false, reason: 'image present (fingerprint skipped)' };\n } else if (!prepared) {\n reason = 'no docker-prepared.json on disk';\n } else if (!preparedMatches(prepared, fingerprint.contextSha256)) {\n reason =\n `build context changed (was ${prepared.base?.contextSha256?.slice(0, 12) ?? '<none>'}, ` +\n `now ${fingerprint.contextSha256.slice(0, 12)})`;\n }\n\n if (!reason) {\n return { ref, built: false, reason: 'image up to date' };\n }\n\n opts.onProgress?.(`[image] ${ref}: ${reason}`);\n const npm = claudeInstall === 'npm';\n const { source } = await pullOrBuild(ref, fingerprint, {\n onProgress: opts.onProgress,\n dockerfile: opts.dockerfile,\n contextDir: opts.contextDir,\n // The published GHCR image is native-only, so npm mode must build locally.\n allowPull: npm ? false : opts.allowPull,\n registry: opts.registry,\n buildArgs: npm ? { AGENTBOX_CLAUDE_INSTALL: 'npm' } : undefined,\n });\n return { ref, built: source === 'built', reason };\n}\n\n/**\n * Read-only freshness classification of the docker base image, for surfaces\n * (hub API, tray) that want to announce an upcoming bake without triggering\n * it. `unknown` means \"couldn't fingerprint\" and MUST stay inert — the\n * matching `ensureImage` path trusts the existing image and does not rebuild.\n */\nexport type DockerBaseFreshness =\n | { state: 'fresh' }\n | { state: 'unknown' }\n | { state: 'unprepared' }\n | { state: 'stale'; reason: string };\n\n/**\n * Pure decision core shared by `evaluateDockerBaseFreshness`. Mirrors\n * `ensureImage`'s rebuild predicate exactly — if the two ever disagree, the\n * freshness surfaces would announce a bake that create then skips (or miss\n * one it performs). `stampedSha` is `docker-prepared.json`'s fingerprint,\n * null when the stamp is missing/invalid.\n */\nexport function classifyDockerBaseFreshness(input: {\n imagePresent: boolean;\n fingerprint: string | null;\n stampedSha: string | null;\n}): DockerBaseFreshness {\n if (!input.imagePresent) return { state: 'unprepared' };\n if (!input.fingerprint) return { state: 'unknown' };\n if (!input.stampedSha) return { state: 'stale', reason: 'no docker-prepared.json on disk' };\n if (input.stampedSha !== input.fingerprint) {\n return {\n state: 'stale',\n reason:\n `build context changed (was ${input.stampedSha.slice(0, 12)}, ` +\n `now ${input.fingerprint.slice(0, 12)})`,\n };\n }\n return { state: 'fresh' };\n}\n\n/**\n * Cheap live check: would `ensureImage` bake on the next create? The only\n * docker work is one `docker image inspect`; the rest hashes the ~15 build\n * context files. Never builds, pulls, or writes the prepared stamp.\n */\nexport async function evaluateDockerBaseFreshness(\n opts: { ref?: string; claudeInstall?: 'native' | 'npm'; contextDir?: string } = {},\n): Promise<DockerBaseFreshness> {\n // Lazy import for the same circular-init reason as in ensureImage above.\n const { computeDockerContextFingerprint, readPreparedDockerState } =\n await import('./prepared-state.js');\n const ref = opts.ref ?? DEFAULT_BOX_IMAGE;\n const imagePresent = await imageExists(ref);\n if (!imagePresent) return { state: 'unprepared' };\n const claudeInstall = opts.claudeInstall ?? (await resolveClaudeInstallMode());\n const raw = await computeDockerContextFingerprint({ contextDir: opts.contextDir });\n return classifyDockerBaseFreshness({\n imagePresent,\n fingerprint: raw ? claudeInstallFingerprint(raw.contextSha256, claudeInstall) : null,\n stampedSha: readPreparedDockerState()?.base?.contextSha256 ?? null,\n });\n}\n\n"],"mappings":";;;AIAA,SAAS,mBAAmB;AKY5B,SAAS,gBAAgB;AACzB,SAAS,UAAU,SAAS,cAAAA,aAAY,WAAW,WAAAC,UAAS,WAAW;ATNvE,IAAM,qBAAoC;EACxC,MAAM;;;;EAIN,UAAU,gBAAgB,UAAU;AAClC,QAAI,CAAC,eAAgB,QAAO,CAAC,GAAG,QAAQ;AACxC,WAAO,CAAC,gBAAgB,GAAG,QAAQ;EACrC;AACF;AAKA,IAAM,gBAA+B;EACnC,MAAM;EACN,UAAU,gBAAgB,UAAU;AAClC,QAAI,CAAC,eAAgB,QAAO,CAAC,GAAG,QAAQ;AACxC,WAAO,CAAC,gBAAgB,GAAG,QAAQ;EACrC;AACF;AAIA,IAAM,mBAAkC;EACtC,MAAM;EACN,UAAU,gBAAgB,UAAU;AAClC,QAAI,CAAC,eAAgB,QAAO,CAAC,GAAG,QAAQ;AACxC,WAAO,CAAC,gBAAgB,GAAG,QAAQ;EACrC;AACF;AAEO,SAAS,qBAAqB,MAAgC;AACnE,MAAI,SAAS,cAAe,QAAO;AACnC,MAAI,SAAS,QAAS,QAAO;AAC7B,MAAI,SAAS,WAAY,QAAO;AAChC,QAAM,IAAI,MAAM,uBAAuB,OAAO,IAAI,CAAC,EAAE;AACvD;AE/BO,IAAM,mBAAmB;EAC9B;EACA;EACA;EACA;EACA;;;;;;EAMA;AACF;AAIA,IAAM,kBAAkB,IAAI,IAAY,gBAAgB;AAYj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AAS,CAAC,aAAa;IACvB,aAAa;IACb,cAAc;IACd,aAAa;MACX;QACE,aAAa,CAAC,SAAS;QACvB,QAAQ;;;;;;QAMR,SAAS;UACP;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACF;MACF;IACF;IACA,YAAY;MACV,YAAY;MACZ,YAAY,GAAG,cAAc;MAC7B,YAAYI,MAAK,WAAW,yBAAyB;MACrD,gBAAgB;MAChB,cAAc;MACd,WAAW;IACb;IACA,kBAAkB;MAChB;MACA;MACA;MACA;IACF;IACA,WAAW,OAAO,CAAC;IACnB,MAAM,EAAE,QAAQ,MAAM,UAAU,QAAQ,gBAAgB,UAAU;EACpE;EACA;IACE,IAAI;IACJ,SAAS,CAAC;IACV,aAAa;IACb,cAAc;IACd,aAAa;MACX;QACE,aAAa,CAAC,QAAQ;QACtB,QAAQ;;;;;;QAMR,SAAS;UACP;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACF;MACF;IACF;IACA,YAAY;MACV,YAAY;MACZ,YAAY,GAAG,aAAa;MAC5B,YAAYA,MAAK,WAAW,wBAAwB;MACpD,gBAAgB;MAChB,cAAc;MACd,WAAW;IACb;IACA,kBAAkB,CAAC,gBAAgB;IACnC,WAAW,OAAO,CAAC;IACnB,MAAM,EAAE,QAAQ,MAAM,UAAU,QAAQ,gBAAgB,UAAU;EACpE;EACA;IACE,IAAI;IACJ,SAAS,CAAC;IACV,aAAa;IACb,cAAc;;;;IAId,aAAa;MACX;QACE,aAAa,CAAC,UAAU,SAAS,UAAU;QAC3C,QAAQ;;;;QAIR,SAAS;UACP;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;QACF;MACF;MACA,EAAE,aAAa,CAAC,WAAW,UAAU,GAAG,QAAQ,kBAAkB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Y;MAC3B,eAAe,KAAK;MACpB,YAAY,MAAM;MAClB,WAAW,MAAM;MACjB,YAAW,oBAAI,KAAK,GAAE,YAAY;IACpC;EACF;AACA,wBAAsB,UAAU,KAAK;AACvC;AAGO,SAAS,gBAAgB,OAAmC,SAA0B;AAC3F,SAAO,OAAO,MAAM,kBAAkB;AACxC;","names":["isAbsolute","resolve","resolve","dirname","stat","join","homedir","mkdir","readFile","execa","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","dirname","resolve","mkdir","open","readFile","rename","rm","stat","writeFile","join","delay","basename","join","homedir","mkdtemp","rm","tmpdir","execa","readdir","stat","realpath","mkdir","readFile","writeFile","dirname","createHash","basename","copyFile","relative","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","resolve","join","homedir","EMPTY","LOCK_STALE_MS","LOCK_ACQUIRE_TIMEOUT_MS","LOCK_RETRY_MS","mkdir","dirname","open","stat","rm","delay","normalize","existsSync","readFileSync","readFile","EMPTY","mkdir","dirname","writeFile","rename","join","basename","join","homedir","execa","mkdtemp","join","tmpdir","rm","stat","readdir","realpath","pathExists","readFile","mkdir","dirname","writeFile","createHash","basename","BOX_WORKSPACE","relative","copyFile","existsSync","readFileSync","mkdirSync","writeFileSync","renameSync","createHash","existsSync","dirname","resolve","fileURLToPath","execa","existsSync","dirname","resolve","dirname","existsSync","resolve","execa","writePreparedDockerState","computeDockerContextFingerprint","readPreparedDockerState","preparedMatches","here","fileURLToPath"]}
1
+ {"version":3,"sources":["../../../packages/core/src/agent.ts","../../../packages/core/src/box-record.ts","../../../packages/core/src/replace.ts","../../../packages/core/src/errors.ts","../../../packages/core/src/identity.ts","../../../packages/core/src/sync/agent-kind.ts","../../../packages/core/src/sync/provider-sync.ts","../../../packages/core/src/sync/topology.ts","../../../packages/core/src/sync/files.ts","../../../packages/core/src/sync/containment.ts","../../../packages/core/src/sync/git-refs.ts","../../../packages/sandbox-core/src/state.ts","../../../packages/sandbox-core/src/git-detect.ts","../../../packages/sandbox-core/src/host-open.ts","../../../packages/sandbox-core/src/ssh-config.ts","../../../packages/sandbox-core/src/claude-app-config.ts","../../../packages/sandbox-core/src/cloud-ssh.ts","../../../packages/sandbox-core/src/ssh-key.ts","../../../packages/sandbox-core/src/box-git.ts","../../../packages/sandbox-core/src/doctor.ts","../../../packages/sandbox-core/src/secrets.ts","../../../packages/sandbox-core/src/plugin-registry.ts","../../../packages/sandbox-core/src/carry-render.ts","../../../packages/sandbox-core/src/sync/recording-transport.ts","../../../packages/sandbox-core/src/sync/registry.ts","../../../packages/sandbox-core/src/sync/context.ts","../../../packages/sandbox-core/src/sync/concerns/env.ts","../../../packages/sandbox-core/src/sync/concerns/files.ts","../../../packages/sandbox-core/src/sync/agents/claude/paths.ts","../../../packages/sandbox-core/src/sync/host-links.ts","../../../packages/sandbox-core/src/sync/concerns/skills.ts","../../../packages/sandbox-core/src/sync/concerns/credentials.ts","../../../packages/sandbox-core/src/sync/concerns/git.ts","../../../packages/sandbox-core/src/sync/concerns/dynamic.ts","../../../packages/sandbox-core/src/sync/host-stage.ts","../../../packages/sandbox-core/src/sync/claude-hooks-filter.ts","../../../packages/sandbox-core/src/sync/codex-config.ts","../../../packages/sandbox-core/src/prepared-state.ts","../../../packages/sandbox-docker/src/prepared-state.ts","../../../packages/sandbox-docker/src/image.ts"],"sourcesContent":["import type { AgentKind } from './types.js';\n\nexport interface AgentLauncher {\n readonly kind: AgentKind;\n buildArgs(initialMessage: string, userArgs: string[]): string[];\n}\n\nconst claudeCodeLauncher: AgentLauncher = {\n kind: 'claude-code',\n // claude treats its first positional argument as the seed user turn in\n // interactive mode (`claude \"<message>\"`), so we slot the initial message\n // ahead of any user-passed flags.\n buildArgs(initialMessage, userArgs) {\n if (!initialMessage) return [...userArgs];\n return [initialMessage, ...userArgs];\n },\n};\n\n// codex accepts a leading positional as the seed prompt — `codex \"<message>\"`\n// drops the user into the TUI with that turn pre-submitted. Same shape as\n// claude, so the launcher is structurally identical.\nconst codexLauncher: AgentLauncher = {\n kind: 'codex',\n buildArgs(initialMessage, userArgs) {\n if (!initialMessage) return [...userArgs];\n return [initialMessage, ...userArgs];\n },\n};\n\n// opencode also accepts a leading positional as the seed prompt — `opencode\n// \"<message>\"` enters the TUI with that turn pre-submitted. Mirrors claude/codex.\nconst opencodeLauncher: AgentLauncher = {\n kind: 'opencode',\n buildArgs(initialMessage, userArgs) {\n if (!initialMessage) return [...userArgs];\n return [initialMessage, ...userArgs];\n },\n};\n\nexport function resolveAgentLauncher(kind: AgentKind): AgentLauncher {\n if (kind === 'claude-code') return claudeCodeLauncher;\n if (kind === 'codex') return codexLauncher;\n if (kind === 'opencode') return opencodeLauncher;\n throw new Error(`unknown agent kind: ${String(kind)}`);\n}\n","/**\n * The per-box state record persisted to `~/.agentbox/state.json`. Shared by\n * every provider: a box may be a local Docker container or a remote cloud\n * sandbox. The `provider` discriminator says which; provider-specific fields\n * live flat (Docker, for historical reasons) or under `cloud` (cloud backends).\n */\n\nimport type { BoxRuntimeState } from './provider.js';\nimport type { SyncTopology } from './sync/types.js';\n\n/** Sandbox backend a box runs on. Open-ended so future providers need no core change. */\nexport type ProviderName = 'docker' | 'daytona' | 'hetzner' | (string & {});\n\n/**\n * Docker-backend-specific fields nested under `BoxRecord.docker` once 7.1\n * lands fully. Today every Docker box also keeps the flat copies of these\n * fields on `BoxRecord` directly for back-compat (state.json migration is\n * the rest of 7.1) — write sites populate both shapes; read sites still\n * use the flat fields. New code should target this interface so the\n * eventual flat-field removal is a search-and-replace, not a redesign.\n */\nexport interface DockerBoxFields {\n /** Docker container name (`agentbox-<id|name>`). */\n container: string;\n /** Base image / checkpoint image tag the container was started from. */\n image: string;\n /** Per-box scratch dir with the `cp -c` APFS clone (when --host-snapshot is on). */\n snapshotDir?: string | null;\n /** Host-side path to the agentbox-ctl unix socket bind-mounted into the container. */\n socketPath?: string;\n /** Docker volume mounted at /home/vscode/.claude inside the box. */\n claudeConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.codex inside the box. */\n codexConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.agents inside the box (Agent Skills). */\n agentsConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.local/share/opencode. */\n opencodeConfigVolume?: string;\n /** Per-box volume holding `.vscode-server`. */\n vscodeServerVolume?: string;\n /** Per-box volume holding `.cursor-server`. */\n cursorServerVolume?: string;\n /** Host port mapped to the noVNC web server. */\n vncHostPort?: number;\n /** Host port mapped to container :80. */\n webHostPort?: number;\n /** Portless route name registered for this box's web port. */\n portlessAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box. */\n portlessUrl?: string;\n /** Portless route name registered for this box's noVNC port (`vnc-<box-name>`). */\n portlessVncAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box's VNC. */\n portlessVncUrl?: string;\n /** Volume mounted at /var/lib/docker for the in-box dockerd. */\n dockerVolume?: string;\n /** True when this box's `dockerVolume` is the shared cache. */\n dockerCacheShared?: boolean;\n /** Checkpoint image tag this box was started from. */\n checkpointImage?: string;\n}\n\n/**\n * Cloud-backend-specific fields for a box. Populated only when\n * `BoxRecord.provider` is a cloud provider; `undefined` for Docker boxes.\n */\nexport interface CloudBoxFields {\n /** Cloud backend name, e.g. 'daytona'. Mirrors `BoxRecord.provider`. */\n backend: string;\n /** Provider-native sandbox id (the handle the backend SDK resolves). */\n sandboxId: string;\n /** Resolved base image / snapshot ref the sandbox was provisioned from. */\n image?: string;\n /**\n * In-box port the web service is exposed on (the supervisor's WebProxy\n * listen port). Cloud boxes bind a non-privileged port; Docker boxes use 80.\n */\n webPort?: number;\n /**\n * Token-authed preview URLs keyed by in-box port. Resolved at create and\n * refreshed on every start (preview tokens can rotate across stop/start).\n */\n previewUrls?: Record<number, string>;\n /**\n * Preview URL of the in-sandbox relay's `/bridge/*` surface — the channel the\n * host CloudBoxPoller drains. Refreshed on start alongside `previewUrls`.\n */\n relayPreviewUrl?: string;\n /**\n * Daytona-style preview-proxy token for `relayPreviewUrl` (sent as\n * `x-daytona-preview-token` header). Persisted so a relay restart can\n * rehydrate the poller without re-resolving from the SDK.\n */\n relayPreviewToken?: string;\n /**\n * Bearer secret authenticating the host poller to the in-sandbox relay's\n * `/bridge/*` routes. Distinct from `BoxRecord.relayToken` (the per-box token\n * the in-box agent sees) so a compromised agent cannot impersonate the host.\n */\n bridgeToken?: string;\n /**\n * User-facing checkpoint name this box was provisioned from (e.g. `setup`),\n * when `agentbox create --checkpoint <name>` resolved to a cloud snapshot.\n * Surfaces in `agentbox status --inspect` so the user can tell which\n * checkpoint a box is currently running.\n */\n snapshotRef?: string;\n /**\n * Last lifecycle state agentbox itself drove this box to (running on\n * create/start/resume, paused on pause/stop/vercel-checkpoint). `listBoxes`\n * shows this for cloud boxes so `agentbox list` stays instant — no SDK probe.\n * It reflects the last *host-initiated* op, not the authoritative live state\n * (a platform-side stop won't update it); `agentbox list --live` probes for\n * the real state. Absent on pre-feature records → treated as `running`.\n */\n lastState?: BoxRuntimeState;\n /**\n * Effective per-session timeout (ms) the sandbox was created with, when the\n * backend models one (vercel `Sandbox.create({ timeout })`). Recorded so the\n * host keepalive loop can seed its tracked death-time accurately (the\n * effective value can be project/workspace-overridden, not the global\n * default). Absent on backends without a session timeout / pre-feature records.\n */\n sessionTimeoutMs?: number;\n /**\n * True when this box's `/workspace` was seeded from the host checkout (the\n * laptop `create` path), i.e. it has a real fork base shared with the host.\n * Left unset for `inBoxClone` / plane boxes (they clone in-box from a leased\n * URL with no host fork base). Gates the session-start live-box resync — only\n * host-seeded boxes can merge the host's current state back in (Phase 7.5).\n */\n hostSeeded?: boolean;\n /**\n * The box's per-box branch (`agentbox/<name>`, or `--use-branch <b>`). The\n * merge target branch for the live-box resync; re-derived layout aside, this\n * is the one piece resync can't recover from the box alone.\n */\n workspaceBranch?: string;\n /**\n * Last branch the HOST sanctioned for this cloud box (defaults to\n * `workspaceBranch`, updated by host `agentbox git checkout`/`branch`/`pull\n * <branch>`). The cloud push gate auto-approves a push only to a scratch\n * branch OR this value — the cloud analogue of the docker registry's\n * `BoxWorktree.sanctionedBranch`. Absent → treated as `workspaceBranch`.\n */\n sanctionedBranch?: string;\n /**\n * The box's resolved sync federation shape (`resolveSyncTopology`). `'cloud'`\n * for a classic host-synced box, `'control-plane'` when its live relay is a\n * hosted control plane (the box forwards `/rpc` to the plane and leases push\n * tokens directly). Persisted so the value is stable across resumes.\n */\n topology?: SyncTopology;\n /**\n * The hosted control-plane base URL this box points at, when\n * `topology === 'control-plane'`. Persisted (not re-derived from config) so a\n * resume re-kick on a host whose config has changed/lacks the URL still\n * re-threads the box's forwarder upstream + `AGENTBOX_GIT_LEASE` correctly.\n */\n controlPlaneUrl?: string;\n /**\n * Git push routing (`git.pushMode`): `'auto' | 'relay' | 'lease'`. Persisted\n * (not re-derived from config) so a resume re-kick re-threads `AGENTBOX_GIT_LEASE`\n * correctly even if the host config changed. Mirrors config's `GitPushMode`.\n */\n gitPushMode?: 'auto' | 'relay' | 'lease';\n}\n\n/**\n * Last resolved SSH connection target for a box — host/user, the per-box\n * identity file (identity-authed providers: docker localhost sshd, Hetzner),\n * and an optional port (docker publishes its sshd on an ephemeral loopback\n * port; cloud providers use the default 22). Persisted on `BoxRecord.ssh`\n * whenever we're already online (create/start/code/open/shell) so\n * `~/.agentbox/ssh/config` can be regenerated purely from state — the\n * regenerate never hits a provider API or wakes a paused box. The host IP /\n * loopback port can change across stop/start, so it is refreshed on start/resume.\n * Absent for providers with no SSH.\n */\nexport interface SshTargetRecord {\n host: string;\n user: string;\n identityFile?: string;\n port?: number;\n}\n\nexport interface GitWorktreeRecord {\n kind: 'root' | 'nested';\n /** Host path to the main repo whose `.git/` is the source of the worktree. */\n hostMainRepo: string;\n /**\n * Agent-visible container path of the worktree (`/workspace` for root,\n * `/workspace/<sub>` for nested).\n */\n containerPath: string;\n /**\n * Per-box unique path where git registered the worktree. Docker boxes\n * register against the bind-mounted host `.git/`; cloud boxes clone into the\n * sandbox so this is a sandbox-local path. `destroyBox` uses it to deregister\n * a Docker worktree on the host.\n */\n gitWorktreePath: string;\n /** Branch the worktree was created on, e.g. `agentbox/<box-name>`. */\n branch: string;\n /**\n * The last branch the HOST put this box on — its create-time `branch`,\n * updated by host-driven `agentbox git checkout`/`branch`/`pull <branch>`.\n * Distinct from `branch` (which stays the immutable scratch identity used by\n * host-only land, checkout guards, and upstream-sync skip): the relay\n * auto-approves a push only to a scratch branch OR this sanctioned branch,\n * so an in-box agent self-switching to `main` and pushing still prompts.\n * Absent on records written before this field existed → treated as `branch`.\n */\n sanctionedBranch?: string;\n /** Workspace-relative path the repo was found at (empty string for root). */\n relPathFromWorkspace: string;\n}\n\nexport interface BoxRecord {\n id: string;\n name: string;\n /**\n * Cosmetic user-chosen label, set via `agentbox status <box> --set-name`.\n * Purely for display and lookup — unlike `name` it does NOT drive the\n * container, git branch, or Portless URL. Absent means \"fall back to name\".\n * See docs/state.md.\n */\n displayName?: string;\n /**\n * Sandbox backend the box runs on. Absent on records written before the\n * multi-provider split — `readState` migrates those to `'docker'` on read.\n */\n provider?: ProviderName;\n /**\n * Unique runtime identifier. For docker records: the container name\n * (`agentbox-<id|name>`) — what `docker exec` resolves. For cloud\n * records: the backend sandbox id, prefixed with `cloud:` so a grep\n * for \"agentbox-cloud-*\" finds nothing (post 7.2) — the cloud\n * sandbox is not a docker container and shouldn't look like one.\n * Docker-internal code should only ever reach this via\n * `requireDockerProvider(box, ...)` first.\n */\n container: string;\n /**\n * The image the box was started from. Docker: base image or checkpoint\n * image tag. Cloud: the resolved sandbox image / snapshot ref (mirrors\n * `box.cloud.image`).\n */\n image: string;\n workspacePath: string;\n /**\n * Optional per-box scratch dir holding a `cp -c` APFS clone of the host\n * workspace, made at create time when `--host-snapshot` is on. Docker only.\n */\n snapshotDir?: string | null;\n /**\n * Host-side path to the agentbox-ctl unix socket bind-mounted into the\n * container at /run/agentbox/ctl.sock. Docker only.\n */\n socketPath?: string;\n /** Docker volume mounted at /home/vscode/.claude inside the box. Docker only. */\n claudeConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.codex inside the box. Docker only. */\n codexConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.agents inside the box (Agent Skills). Docker only. */\n agentsConfigVolume?: string;\n /** Docker volume mounted at /home/vscode/.local/share/opencode. Docker only. */\n opencodeConfigVolume?: string;\n /** Per-box volume holding `.vscode-server`. Docker only. */\n vscodeServerVolume?: string;\n /** Per-box volume holding `.cursor-server`. Docker only. */\n cursorServerVolume?: string;\n /**\n * Bearer token the in-box supervisor uses to authenticate with the relay.\n * Generated at create time and forwarded as AGENTBOX_RELAY_TOKEN.\n */\n relayToken?: string;\n /** Per-box git worktrees. Empty/absent when the host workspace is not a git checkout. */\n gitWorktrees?: GitWorktreeRecord[];\n /** True when the box was created with --with-playwright. */\n withPlaywright?: boolean;\n /** True when the box was created with --with-env. */\n withEnv?: boolean;\n /**\n * Resolved `box.autoApproveHostActions` at create time. Forwarded to the\n * host relay so host-action confirms (git push, cp, gh writes, checkpoint)\n * auto-resolve to `y` for this box — with an audit event per bypass.\n * Persisted so a `relay` rehydrate re-registers with the same policy.\n */\n autoApproveHostActions?: boolean;\n /**\n * Resolved `box.autoApproveSafeHostActions` at create time (default true).\n * Forwarded to the relay so the SAFE subset of host actions (open PR, PR\n * comments, sanctioned-branch push, contained non-secret file copy, CI\n * rerun, checkpoint, integration writes) auto-resolves without a prompt.\n * Absent is treated as enabled (default on) by the relay. Persisted so a\n * `relay` rehydrate re-registers with the same policy.\n */\n autoApproveSafeHostActions?: boolean;\n /**\n * Carry summary recorded at create time: which host paths were copied into\n * the box from `agentbox.yaml`'s `carry:` block. Audit trail for inspect\n * (the actual file content is not retained — only the src/dest pairs and\n * sizes). Absent when no carry: block was applied.\n */\n carry?: {\n count: number;\n /**\n * `hash` is a content hash of the host source at copy time, used by the\n * on-start resync to re-copy only entries whose host source changed.\n * Absent on records written before resync existed (treated as \"changed\").\n */\n entries: Array<{ src: string; dest: string; bytes: number; hash?: string }>;\n };\n /** VNC stack (Xvnc + websockify + noVNC) is enabled for this box. */\n vncEnabled?: boolean;\n /** Container-side noVNC web port. */\n vncContainerPort?: number;\n /** Host port mapped to the noVNC web server (Docker), or preview port (cloud). */\n vncHostPort?: number;\n /** Per-box password baked into Xvnc's PasswordFile and the auto-connect URL. */\n vncPassword?: string;\n /** Container port reserved for the web service `expose:` forward. */\n webContainerPort?: number;\n /** Host port mapped to container :80 (Docker). */\n webHostPort?: number;\n /** In-box localhost sshd is enabled for this box (Docker). */\n sshEnabled?: boolean;\n /** Container-side sshd port (22). Docker. */\n sshContainerPort?: number;\n /** Ephemeral loopback host port mapped to the container's sshd (Docker). */\n sshHostPort?: number;\n /**\n * Last resolved SSH connection target. Regenerated into `~/.agentbox/ssh/config`\n * by `syncAgentboxSshConfig`. Docker: `127.0.0.1` + the per-box key + the\n * ephemeral `sshHostPort`; cloud (Hetzner): the VPS IP + per-box key.\n */\n ssh?: SshTargetRecord;\n /** Portless route name registered for this box's web port. Docker only. */\n portlessAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box. Docker only. */\n portlessUrl?: string;\n /** Portless route name registered for this box's noVNC port (`vnc-<box-name>`). */\n portlessVncAlias?: string;\n /** Full user-facing URL the Portless proxy serves for this box's VNC. */\n portlessVncUrl?: string;\n /** Volume mounted at /var/lib/docker for the in-box dockerd. Docker only. */\n dockerVolume?: string;\n /** True when this box's `dockerVolume` is the shared cache. Docker only. */\n dockerCacheShared?: boolean;\n /** Absolute host path of the project this box belongs to. */\n projectRoot?: string;\n /** Monotonic 1-based index within `projectRoot`. Never recycled. */\n projectIndex?: number;\n /** The checkpoint image tag this box was started from. Docker only. */\n checkpointImage?: string;\n /** Lineage of the checkpoint this box was started from. */\n checkpointSource?: {\n ref: string;\n type: 'layered' | 'flattened';\n /** Checkpoint refs composing the chain, base-most last. */\n chain: string[];\n };\n /** Resource ceilings actually applied at create. */\n resourceLimits?: {\n memoryBytes?: number;\n cpus?: number;\n pidsLimit?: number;\n disk?: string;\n };\n /**\n * Docker-backend-specific fields. Populated alongside the flat fields\n * during the 7.1 transition; once readers migrate, the flat fields go\n * away. New code SHOULD prefer `box.docker?.<field>` and fall back to\n * the flat field via the `dockerField()` helper in `@agentbox/core`.\n */\n docker?: DockerBoxFields;\n /** Cloud-backend-specific fields. Present only for cloud providers. */\n cloud?: CloudBoxFields;\n /**\n * The agent last launched in this box (`agentbox claude` / `codex` /\n * `opencode`). Recorded on every launch (foreground + queued). Durable, unlike\n * the in-box session pointers which are cleared on the running->stopped tmux\n * edge — so it's the signal `agentbox recover` uses to know which agent to\n * relaunch/attach, and the only such signal for an adopted box with no live\n * session.\n */\n lastAgent?: 'claude' | 'codex' | 'opencode';\n createdAt: string; // ISO-8601\n}\n\n/**\n * Read a Docker-specific field with fallback to the legacy flat slot.\n * Prefer this over `box.field` directly while the 7.1 migration is in\n * flight — once the flat fields are removed, this collapses to\n * `box.docker?.[key]` and the migration is mechanical.\n */\nexport function dockerField<K extends keyof DockerBoxFields>(\n box: BoxRecord,\n key: K,\n): DockerBoxFields[K] | undefined {\n if (box.docker && box.docker[key] !== undefined) return box.docker[key];\n // Fall back to the flat copy. Container / image are required at the\n // BoxRecord top level so they always exist as flat fields today.\n return (box as unknown as Record<string, unknown>)[key as string] as\n | DockerBoxFields[K]\n | undefined;\n}\n\nexport interface StateFile {\n version: 1;\n boxes: BoxRecord[];\n}\n\nexport type FindBoxResult =\n | { kind: 'ok'; box: BoxRecord }\n | { kind: 'none' }\n | { kind: 'ambiguous'; matches: BoxRecord[] };\n","/**\n * Provider-neutral text-replacement engine. Pure (no fs / no yaml) so it can be\n * shared by the host carry path (`renderCarryEntries`) and the in-box\n * `agentbox-ctl render` CLI without a dependency cycle. The yaml/fs loaders that\n * read a `replacements:` block live in `@agentbox/ctl` (which has those deps).\n */\n\n/**\n * The fixed set of `{{NAME}}` placeholders that `replaceEnvs` / `--env`\n * substitution recognizes. Deliberately a whitelist (not \"any env var\") so a\n * rendered file is predictable: a stray `{{FOO}}` is left untouched rather than\n * silently clobbered, and secrets/tokens are never substitutable.\n */\nexport const PLACEHOLDER_KEYS = [\n 'AGENTBOX_BOX_NAME',\n 'AGENTBOX_BOX_ID',\n 'AGENTBOX_BOX_KIND',\n 'AGENTBOX_HOST_WORKSPACE',\n 'AGENTBOX_PROJECT_ROOT',\n // Convenience: the host this box is reachable at. Derived from\n // AGENTBOX_BOX_NAME as `<box-name>.localhost` when not set explicitly (the\n // portless host for docker/hetzner). Public-URL cloud providers\n // (vercel/daytona/e2b) set it explicitly at boot to the real preview host\n // (e.g. `<sub>.vercel.run`), which then wins over the derived fallback.\n 'AGENTBOX_BOX_HOST',\n] as const;\n\nexport type PlaceholderKey = (typeof PLACEHOLDER_KEYS)[number];\n\nconst PLACEHOLDER_SET = new Set<string>(PLACEHOLDER_KEYS);\n\n/** A single regex/literal substitution. `to` may itself contain placeholders. */\nexport interface ReplaceRule {\n from: string;\n to: string;\n /** Treat `from` as a JS regex (with `flags`); otherwise a literal string. */\n regex?: boolean;\n /** Regex flags (default `g`). Ignored unless `regex` is true. */\n flags?: string;\n}\n\nexport class ReplaceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ReplaceError';\n }\n}\n\nconst PLACEHOLDER_RE = /\\{\\{\\s*([A-Z0-9_]+)\\s*\\}\\}/g;\n\n/**\n * Replace `{{NAME}}` placeholders whose NAME is in {@link PLACEHOLDER_KEYS}\n * with the matching value from `context`. Unknown names (not whitelisted) are\n * left as-is. Whitelisted names with no value in `context` are also left as-is\n * (and reported via `onWarn`).\n */\nexport function substitutePlaceholders(\n text: string,\n context: Record<string, string>,\n onWarn?: (msg: string) => void,\n): string {\n return text.replace(PLACEHOLDER_RE, (match, name: string) => {\n if (!PLACEHOLDER_SET.has(name)) return match;\n const value = context[name];\n if (value === undefined) {\n onWarn?.(`placeholder {{${name}}} has no value in this context — left untouched`);\n return match;\n }\n return value;\n });\n}\n\nexport interface ApplyReplacementsOptions {\n /** When true, substitute `{{NAME}}` whitelist placeholders across the file. */\n env?: boolean;\n /** Ordered custom rules applied after (or instead of) placeholder env subst. */\n rules?: ReplaceRule[];\n /** Placeholder values (used by both `env` subst and rule `to` strings). */\n context: Record<string, string>;\n onWarn?: (msg: string) => void;\n}\n\n/**\n * Apply env-placeholder substitution and/or custom rules to file content.\n * Rules run in declaration order; each rule's `to` string is itself run through\n * placeholder substitution so `to: '.{{AGENTBOX_BOX_NAME}}.localhost'` works\n * regardless of `env`.\n */\nexport function applyReplacements(content: string, opts: ApplyReplacementsOptions): string {\n let out = content;\n if (opts.env) {\n out = substitutePlaceholders(out, opts.context, opts.onWarn);\n }\n for (const rule of opts.rules ?? []) {\n const to = substitutePlaceholders(rule.to, opts.context, opts.onWarn);\n if (rule.regex) {\n let re: RegExp;\n try {\n re = new RegExp(rule.from, rule.flags ?? 'g');\n } catch (err) {\n throw new ReplaceError(\n `invalid regex \"${rule.from}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n out = out.replace(re, to);\n } else {\n // Literal: split/join so `$`/special chars in either side stay literal.\n out = out.split(rule.from).join(to);\n }\n }\n return out;\n}\n\n/**\n * Fill in `AGENTBOX_BOX_HOST` (the published portless host, `<box-name>.localhost`)\n * from `AGENTBOX_BOX_NAME` when it isn't already set. Single source of truth for\n * the host-derivation rule, shared by every placeholder-context builder. Mutates\n * and returns `ctx`.\n */\nexport function deriveBoxHost(ctx: Record<string, string>): Record<string, string> {\n if (ctx.AGENTBOX_BOX_HOST === undefined && ctx.AGENTBOX_BOX_NAME !== undefined) {\n ctx.AGENTBOX_BOX_HOST = `${ctx.AGENTBOX_BOX_NAME}.localhost`;\n }\n return ctx;\n}\n\n/** Build the whitelist placeholder context from a process environment. */\nexport function placeholderContextFromEnv(\n env: NodeJS.ProcessEnv = process.env,\n): Record<string, string> {\n const ctx: Record<string, string> = {};\n for (const key of PLACEHOLDER_KEYS) {\n const v = env[key];\n if (typeof v === 'string' && v.length > 0) ctx[key] = v;\n }\n return deriveBoxHost(ctx);\n}\n\n// --- rule parsing (shared by config top-level `replacements:` and the CLI) ---\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nconst RULE_KEYS = new Set(['from', 'to', 'regex', 'flags']);\n\n/** Parse one rule mapping (from `replacements:` blocks or carry `replace:`). */\nexport function parseReplaceRule(raw: unknown, where: string): ReplaceRule {\n if (!isPlainObject(raw)) {\n throw new ReplaceError(`${where} must be a mapping with at least { from, to }`);\n }\n for (const key of Object.keys(raw)) {\n if (!RULE_KEYS.has(key)) throw new ReplaceError(`${where} has unknown key \"${key}\"`);\n }\n if (typeof raw.from !== 'string' || raw.from.length === 0) {\n throw new ReplaceError(`${where}.from must be a non-empty string`);\n }\n if (typeof raw.to !== 'string') {\n throw new ReplaceError(`${where}.to must be a string`);\n }\n const rule: ReplaceRule = { from: raw.from, to: raw.to };\n if (raw.regex !== undefined && raw.regex !== null) {\n if (typeof raw.regex !== 'boolean') throw new ReplaceError(`${where}.regex must be a boolean`);\n rule.regex = raw.regex;\n }\n if (raw.flags !== undefined && raw.flags !== null) {\n if (typeof raw.flags !== 'string') throw new ReplaceError(`${where}.flags must be a string`);\n rule.flags = raw.flags;\n }\n if (rule.regex) {\n try {\n new RegExp(rule.from, rule.flags ?? 'g');\n } catch (err) {\n throw new ReplaceError(\n `${where}.from is not a valid regex: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n return rule;\n}\n\n/** Parse a list of rules (carry `replace:` or a `replacements:` named set). */\nexport function parseReplaceRules(raw: unknown, where: string): ReplaceRule[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) throw new ReplaceError(`${where} must be a list of rules`);\n return raw.map((r, i) => parseReplaceRule(r, `${where}[${String(i)}]`));\n}\n\n/** Parse the top-level `replacements:` block: name → rule list. */\nexport function parseReplacements(raw: unknown): Record<string, ReplaceRule[]> {\n if (raw === undefined || raw === null) return {};\n if (!isPlainObject(raw)) {\n throw new ReplaceError('replacements must be a mapping of name → rule list');\n }\n const out: Record<string, ReplaceRule[]> = {};\n for (const [name, rules] of Object.entries(raw)) {\n if (!/^[A-Za-z0-9_-]+$/.test(name)) {\n throw new ReplaceError(`replacements.${name}: name must match [A-Za-z0-9_-]+`);\n }\n out[name] = parseReplaceRules(rules, `replacements.${name}`);\n }\n return out;\n}\n\n/**\n * Resolve a list of named rule-set references against a `replacements:` map,\n * concatenating their rules in reference order. Throws on an unknown name.\n */\nexport function resolveRuleRefs(\n refs: string[],\n replacements: Record<string, ReplaceRule[]>,\n where: string,\n): ReplaceRule[] {\n const out: ReplaceRule[] = [];\n for (const name of refs) {\n const set = replacements[name];\n if (set === undefined) {\n const known = Object.keys(replacements);\n throw new ReplaceError(\n `${where}: unknown replacements rule-set \"${name}\"` +\n (known.length > 0 ? ` (known: ${known.join(', ')})` : ' (none declared)'),\n );\n }\n out.push(...set);\n }\n return out;\n}\n\n/** Parse a CLI `--rule 'from=>to'` argument into a rule. `regex` opt-in. */\nexport function parseRuleArg(arg: string, regex: boolean): ReplaceRule {\n const idx = arg.indexOf('=>');\n if (idx === -1) {\n throw new ReplaceError(`--rule \"${arg}\" must be of the form 'from=>to'`);\n }\n const from = arg.slice(0, idx);\n const to = arg.slice(idx + 2);\n if (from.length === 0) throw new ReplaceError(`--rule \"${arg}\" has an empty 'from'`);\n return parseReplaceRule({ from, to, ...(regex ? { regex: true } : {}) }, `--rule \"${arg}\"`);\n}\n","/**\n * Provider-neutral box-resolution errors. Thrown by the box-ref resolver and\n * caught by the CLI's lifecycle error handler. They carry the query (and, for\n * the ambiguous case, the candidate records) so the CLI can render a useful\n * hint.\n */\n\nimport type { BoxRecord } from './box-record.js';\n\n/**\n * Marker class for expected, actionable failures that the CLI should render\n * to the user as a clean message (no stack trace) — e.g. \"you skipped a\n * required `agentbox prepare` step\". The top-level CLI catch in\n * `apps/cli/src/index.ts` detects this via `instanceof` and falls back to the\n * `name` field so bundling / dual-publish boundaries can't lose the marker.\n */\nexport class UserFacingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'UserFacingError';\n }\n}\n\nexport class BoxNotFoundError extends Error {\n constructor(public readonly query: string) {\n super(`no agentbox matches \"${query}\"`);\n this.name = 'BoxNotFoundError';\n }\n}\n\nexport class AmbiguousBoxError extends Error {\n constructor(\n public readonly query: string,\n public readonly matches: BoxRecord[],\n ) {\n const ids = matches.map((m) => m.id).join(', ');\n super(`\"${query}\" matches multiple boxes: ${ids}`);\n this.name = 'AmbiguousBoxError';\n }\n}\n","import { randomBytes } from 'node:crypto';\n\n/**\n * Stable identity helpers shared across providers. Currently just the per-box\n * id mint; checkpoint ids etc. can join later under their own prefix.\n */\n\n/**\n * Type tag prefixed to every minted box id so the kind is readable at a glance\n * and id namespaces can grow without colliding (reserve `c` for checkpoints,\n * etc.). The leading non-digit is load-bearing: it guarantees a box id is never\n * an all-decimal string, which would otherwise collide with the per-project\n * numeric index in `resolveBoxRef` (`agentbox open 4`) and make all-digit ids\n * unresolvable.\n */\nexport const BOX_ID_PREFIX = 'b';\n\nexport function generateBoxId(): string {\n return `${BOX_ID_PREFIX}${randomBytes(4).toString('hex')}`;\n}\n","/**\n * The single adapter reconciling the two spellings of the Claude agent across\n * the codebase:\n * - `'claude'` — canonical INTERNAL name (sync layer, docker volumes,\n * `BoxRecord.lastAgent`, the CLI `claude` subcommand).\n * - `'claude-code'` — the FROZEN wire/registry name (relay `QueueAgentKind`,\n * persisted queue jobs, the `AgentLauncher` registry).\n *\n * Everything downstream of a boundary uses the canonical `SyncAgentKind`;\n * `toQueueKind` / `toSyncKind` translate only at the boundary. We NEVER rewrite\n * persisted wire/record values — back-compat is read-time normalization\n * (`normalizeLastAgent`), so existing box records and in-flight queue jobs keep\n * working untouched.\n */\n\n/** Canonical internal agent id. */\nexport type SyncAgentKind = 'claude' | 'codex' | 'opencode';\n\n/** The frozen wire/queue spelling (relay `QueueAgentKind`, persisted jobs). */\nexport type QueueAgentKind = 'claude-code' | 'codex' | 'opencode';\n\nexport const SYNC_AGENT_KINDS: readonly SyncAgentKind[] = ['claude', 'codex', 'opencode'];\n\n/** True for a known canonical id. */\nexport function isSyncAgentKind(v: unknown): v is SyncAgentKind {\n return v === 'claude' || v === 'codex' || v === 'opencode';\n}\n\n/**\n * Boundary → internal. Maps the wire spelling `'claude-code'` to `'claude'`;\n * `'codex'`/`'opencode'` pass through. Throws on anything else so a typo can't\n * silently seed the wrong agent.\n */\nexport function toSyncKind(k: string): SyncAgentKind {\n if (k === 'claude-code' || k === 'claude') return 'claude';\n if (k === 'codex') return 'codex';\n if (k === 'opencode') return 'opencode';\n throw new Error(`unknown agent kind: ${k}`);\n}\n\n/** Internal → boundary. Maps `'claude'` to the wire spelling `'claude-code'`. */\nexport function toQueueKind(k: SyncAgentKind): QueueAgentKind {\n return k === 'claude' ? 'claude-code' : k;\n}\n\n/**\n * Read-time back-compat for persisted `BoxRecord.lastAgent`. A record written by\n * any past/forked build that stored `'claude-code'` still resolves to\n * `'claude'`; unknown/absent values return undefined rather than throwing (a\n * stale record must never crash `list`/`recover`).\n */\nexport function normalizeLastAgent(raw: string | undefined | null): SyncAgentKind | undefined {\n if (!raw) return undefined;\n if (raw === 'claude-code' || raw === 'claude') return 'claude';\n if (raw === 'codex') return 'codex';\n if (raw === 'opencode') return 'opencode';\n return undefined;\n}\n","/**\n * `ProviderSync` — the co-located, auditable surface of every shared sync\n * activity a provider performs. One implementation per provider\n * (`makeDockerSync` / `makeCloudSync`), each method a thin delegation to the\n * provider-neutral concern in `@agentbox/sandbox-core`. The two goals this\n * serves — see `docs/sync-architecture.md` §\"Co-location: the ProviderSync\n * facade\":\n *\n * - **Per-provider audit** — one file (`docker-sync.ts` / `cloud-sync.ts`) is\n * the complete list of a provider's sync ops.\n * - **Per-concern cross-provider audit** — `dockerSync.resyncWorkspace` vs\n * `cloudSync.resyncWorkspace` are peer methods under one interface.\n *\n * The handle (docker container / cloud backend+handle) is closed at construction\n * time; every method takes the `SyncContext` plus its own operation args.\n *\n * Granularity is GROUPED: per-tool agent config (static config, skills, dynamic,\n * box-facts) bundles into `seedAgentConfig`; resync / credentials / extract /\n * git-identity / env / carry stay separate peer methods. Workspace *seed* (git\n * worktree create + docker `mount --bind`) is deliberately NOT here — it has no\n * cloud analog (cloud clones), so it stays a provider-specific step called\n * directly by each `create()`. Each facade file's header names that carve-out so\n * the file remains the full picture.\n */\n\nimport type { GitWorktreeRecord } from '../box-record.js';\nimport type { ResolvedCarryEntry, ResyncResult } from '../provider.js';\nimport type { SyncContext } from './context.js';\n\n/** Env var that flips every `ProviderSync` op into a print-only no-op. */\nexport const SYNC_DRYRUN_ENV = 'AGENTBOX_SYNC_DRYRUN';\n\n/**\n * Outcome of applying the approved `carry:` entries into a box. Mirrors the\n * docker `CopyCarryResult` shape (kept identical so `applyCarry` returns it\n * verbatim): the count copied, per-entry errors, and an audit summary for\n * `BoxRecord.carry` (`hash` is the host source content hash at copy time).\n */\nexport interface CarryApplyResult {\n copied: number;\n errors: string[];\n applied: Array<{ src: string; dest: string; bytes: number; hash?: string }>;\n}\n\nexport interface ProviderSync {\n /**\n * Merge the host's checked-out branch into each box worktree's per-box branch\n * and overlay the host's uncommitted/untracked changes, box-wins on conflict.\n * `worktrees` are the box's recorded worktrees (root + nested).\n */\n resyncWorkspace(ctx: SyncContext, worktrees: GitWorktreeRecord[]): Promise<ResyncResult>;\n /**\n * Seed the per-tool agent config (claude/codex/opencode): static config +\n * skills + dynamic (workflows/memory) + box-facts. The method body lists the\n * sub-steps in order so the facade file stays the auditable full picture.\n */\n seedAgentConfig(ctx: SyncContext): Promise<void>;\n /** Seed the host's agent logins (claude/codex/opencode) into the box. */\n seedCredentials(ctx: SyncContext): Promise<void>;\n /** Capture the box's agent logins back to the host backups. Returns updated agents. */\n extractCredentials(ctx: SyncContext): Promise<string[]>;\n /** Seed the host git identity (`~/.gitconfig`) into the box. Docker no-op (bind-mounted). */\n seedGitIdentity(ctx: SyncContext): Promise<void>;\n /** Copy gitignore-bypassing host env files matching `patterns` into /workspace. */\n seedEnvFiles(ctx: SyncContext, patterns: string[]): Promise<{ copied: number }>;\n /** Apply the approved `carry:` entries (host→box file copies) into the box. */\n applyCarry(ctx: SyncContext, entries: ResolvedCarryEntry[]): Promise<CarryApplyResult>;\n}\n\n/**\n * Wrap a `ProviderSync` so each op prints `[sync dry-run] <label>.<op>(…)` via\n * `ctx.onLog` and returns a benign default WITHOUT executing — the readable\n * audit of \"what the facade would do.\" `makeDockerSync`/`makeCloudSync` apply\n * this when {@link SYNC_DRYRUN_ENV} is set. The inner facade is never invoked, so\n * a dry run makes no host/box changes.\n */\nexport function dryRunProviderSync(label: string): ProviderSync {\n const note = (ctx: SyncContext, op: string, detail = ''): void =>\n ctx.onLog(`[sync dry-run] ${label}.${op}(${detail})`);\n return {\n resyncWorkspace(ctx, worktrees) {\n note(ctx, 'resyncWorkspace', `${String(worktrees.length)} worktree(s)`);\n return Promise.resolve({ repos: [], hadConflicts: false });\n },\n seedAgentConfig(ctx) {\n note(ctx, 'seedAgentConfig');\n return Promise.resolve();\n },\n seedCredentials(ctx) {\n note(ctx, 'seedCredentials');\n return Promise.resolve();\n },\n extractCredentials(ctx) {\n note(ctx, 'extractCredentials');\n return Promise.resolve([]);\n },\n seedGitIdentity(ctx) {\n note(ctx, 'seedGitIdentity');\n return Promise.resolve();\n },\n seedEnvFiles(ctx, patterns) {\n note(ctx, 'seedEnvFiles', `${String(patterns.length)} pattern(s)`);\n return Promise.resolve({ copied: 0 });\n },\n applyCarry(ctx, entries) {\n note(ctx, 'applyCarry', `${String(entries.length)} entry/entries`);\n return Promise.resolve({ copied: 0, errors: [], applied: [] });\n },\n };\n}\n","/**\n * Pure resolver for a box's {@link SyncTopology} — the \"resolved ONCE per box\n * (from the provider name + whether a control-plane URL is configured)\" step the\n * `SyncTopology` doc describes. No fs/exec — string logic only — so it's shared\n * by the provider (persists it on the record) and any host/box consumer.\n */\nimport type { SyncTopology } from './types.js';\n\n/**\n * Resolve a box's federation topology from its provider name and whether a\n * hosted control-plane URL is configured for it.\n *\n * - docker → always `'docker'` (bind-mounted `.git`, host relay loopback; never\n * a control-plane target).\n * - any cloud provider + a non-empty control-plane URL → `'control-plane'`\n * (the box's live relay is the plane; git push-back leases a token directly).\n * - any cloud provider without one → `'cloud'` (host-side sync via the backend).\n */\nexport function resolveSyncTopology(providerName: string, controlPlaneUrl?: string): SyncTopology {\n if (providerName === 'docker') return 'docker';\n return controlPlaneUrl && controlPlaneUrl.length > 0 ? 'control-plane' : 'cloud';\n}\n","/**\n * Pure download / file-transfer decisions, co-located here so *all* sync\n * decision logic is discoverable under `core/src/sync/` — even though the two\n * download handlers keep genuinely divergent transports (docker re-shells the\n * host CLI; cloud calls `pullCloudDirContents`, workspace-only). We do NOT\n * force-unify the transport; only these shared, pure decisions live here.\n *\n * No fs/exec beyond `node:path`/`node:os` string helpers.\n */\n\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, resolve } from 'node:path';\n\n/** The `download.<kind>` variants an in-box agent can request. */\nexport type DownloadKind = 'workspace' | 'env' | 'config' | 'claude';\n\n/**\n * Parse the `download.<kind>` RPC method into its kind, defaulting a missing\n * suffix to 'workspace'. Duplicated inline at the docker (`server.ts`) and\n * cloud (`host-actions.ts`) download entry points.\n */\nexport function parseDownloadKind(method: string): DownloadKind {\n return (method.split('.')[1] ?? 'workspace') as DownloadKind;\n}\n\n/**\n * Resolve a host path supplied by an in-box agent to an absolute host path.\n * Absolute paths pass through; a leading `~`/`~/` expands against the host\n * home; anything else is relative to the box's host `workspacePath` (NOT the\n * relay daemon's CWD). When `workspacePath` is unknown, relative paths fall\n * back to `path.resolve` (process CWD) — same as the old behaviour.\n */\nexport function resolveHostPath(workspacePath: string | undefined, hostPath: string): string {\n if (isAbsolute(hostPath)) return hostPath;\n if (hostPath === '~') return homedir();\n if (hostPath.startsWith('~/')) return join(homedir(), hostPath.slice(2));\n return workspacePath ? resolve(workspacePath, hostPath) : resolve(hostPath);\n}\n","/**\n * Host-side path-containment + secret-file guards for the relay's auto-approve\n * decisions. Unlike its pure sibling `files.ts`, this module DOES touch the\n * filesystem (`realpath`) — that's the whole point: following symlinks is what\n * catches an in-project symlink that actually points outside the box's project\n * folder. Lives in `@agentbox/core` so the relay (`@agentbox/relay`) and the\n * host CLI's carry resolver (`apps/cli`) share one containment definition.\n *\n * These are advisory *safety* checks for relaxing approval prompts, never the\n * only boundary: a not-contained / secret path just falls back to prompting.\n */\n\nimport { realpath } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, normalize, resolve, sep } from 'node:path';\n\n/** realpath `p`, falling back to a lexical resolve when it can't be canonicalized. */\nexport async function realpathSafe(p: string): Promise<string> {\n try {\n return await realpath(p);\n } catch {\n return resolve(p);\n }\n}\n\n/**\n * True when canonicalized `child` is `parent` or lives under it. Both are\n * resolved so the comparison happens in the same (already realpath'd) space —\n * callers pass values that have been through `realpathSafe`.\n */\nexport function isInside(child: string, parent: string): boolean {\n const c = resolve(child);\n const p = resolve(parent);\n if (c === p) return true;\n return c.startsWith(p + sep);\n}\n\n/**\n * realpath the deepest *existing* prefix of `p`, then re-append the\n * not-yet-existing tail. Lets a download/cp destination that doesn't exist yet\n * still be containment-checked (its existing parent is canonicalized, so a\n * symlinked parent pointing outside is caught), while a fully-existing source\n * is realpath'd end-to-end.\n */\nasync function realpathDeepestExisting(p: string): Promise<string> {\n let cur = resolve(p);\n const tail: string[] = [];\n // Bounded by the path depth; dirname() reaches the root fixpoint.\n for (;;) {\n try {\n const real = await realpath(cur);\n return tail.length > 0 ? resolve(real, ...tail.reverse()) : real;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return resolve(p);\n const parent = dirname(cur);\n if (parent === cur) return resolve(p); // nothing along the path exists\n tail.push(basename(cur));\n cur = parent;\n }\n }\n}\n\n/**\n * True when `hostPath` (an absolute host path) resolves to a location inside\n * the box's `workspacePath` (the host dir mirroring `/workspace`). Symlinks are\n * followed via realpath so an in-project link escaping the folder fails the\n * check. A literal `..` that survives normalization is rejected outright.\n * Returns `false` (→ caller prompts) when the workspace is unknown.\n */\nexport async function isContainedInWorkspace(\n hostPath: string,\n workspacePath: string | undefined,\n): Promise<boolean> {\n if (!workspacePath) return false;\n if (!isAbsolute(hostPath)) return false;\n // A surviving `..` segment means the literal path escapes upward.\n if (normalize(hostPath).split(sep).includes('..')) return false;\n const wsReal = await realpathSafe(workspacePath);\n const real = await realpathDeepestExisting(hostPath);\n return isInside(real, wsReal);\n}\n\n/** Sensitive directory names: any path segment equal to one of these is secret. */\nconst SECRET_DIR_SEGMENTS = new Set(['.ssh', '.aws', '.gnupg']);\n\n/** Exact basenames that are always secrets. */\nconst SECRET_BASENAMES = new Set(['credentials', '.npmrc', '.netrc', '.pgpass', '.htpasswd']);\n\n/** Basename patterns that mark a likely secret / private key. */\nconst SECRET_BASENAME_PATTERNS: readonly RegExp[] = [\n /^\\.env(\\..+)?$/, // .env, .env.local, .env.production\n /\\.(pem|key|pfx|p12|keystore|jks)$/i,\n /^id_(rsa|dsa|ecdsa|ed25519)$/, // private SSH keys (not the .pub)\n];\n\n/**\n * True when `hostPath` looks like a secret/credential file — used to keep a\n * host->box copy of such a file behind the approval prompt even when the path\n * is contained. Deliberately conservative (a false positive just re-adds a\n * prompt the user can approve): matches secret dirs, `.config/gh`, exact\n * credential basenames, and private-key patterns.\n */\nexport function looksLikeSecret(hostPath: string): boolean {\n const segs = normalize(hostPath).split(sep).filter(Boolean);\n for (const seg of segs) {\n if (SECRET_DIR_SEGMENTS.has(seg)) return true;\n }\n // `.config/gh` (gh CLI auth) — two adjacent segments.\n for (let i = 0; i + 1 < segs.length; i++) {\n if (segs[i] === '.config' && segs[i + 1] === 'gh') return true;\n }\n const base = basename(hostPath);\n if (SECRET_BASENAMES.has(base)) return true;\n return SECRET_BASENAME_PATTERNS.some((re) => re.test(base));\n}\n","/**\n * Pure git ref/branch decisions, shared by the relay host paths and the in-box\n * ctl. Lives in `@agentbox/core` (not `sandbox-core`) because `@agentbox/ctl`\n * depends only on core — same pattern as the pure engine in `../replace.ts`.\n *\n * No fs/exec: only string logic. The three git push-back paths (docker relay,\n * cloud relay, in-box lease push) keep their divergent *mechanisms* but read\n * these *decisions* from here so the branch/refspec/remote/upstream spellings\n * can't drift apart.\n */\n\n/** Prefix of the per-box scratch branch (`agentbox/<name>`). */\nexport const SCRATCH_BRANCH_PREFIX = 'agentbox/';\n\n/**\n * True for a per-box `agentbox/<name>` scratch branch. Undefined-safe so it\n * reproduces the existing `worktree?.branch.startsWith(...) ?? false` sites\n * exactly (`isScratchBranch(undefined) === false`).\n */\nexport function isScratchBranch(branch: string | undefined): boolean {\n return !!branch && branch.startsWith(SCRATCH_BRANCH_PREFIX);\n}\n\n/**\n * True when a push to `branch` is a *sanctioned* push that may bypass the\n * relay's confirm prompt: it's the box's own `agentbox/<name>` scratch branch\n * (always its job), or it exactly matches the branch the host last put the box\n * on (`sanctionedBranch`). An in-box agent that self-switches HEAD to some\n * other branch (e.g. `main`) fails both arms, so its push still prompts.\n * Undefined-safe; empty/`HEAD` never matches the sanctioned arm.\n */\nexport function isSanctionedPushBranch(\n branch: string | undefined,\n sanctionedBranch: string | undefined,\n): boolean {\n if (isScratchBranch(branch)) return true;\n return isResolvedBranch(branch ?? '') && !!sanctionedBranch && branch === sanctionedBranch;\n}\n\n/**\n * Resolve the push remote, defaulting to 'origin'.\n *\n * MUST be `??`, not `||`: only an *undefined* remote falls back to 'origin'.\n * A legitimately-empty wire remote must stay '' — `||` would coerce it and\n * silently change the push target.\n */\nexport function resolveRemote(remote?: string): string {\n return remote ?? 'origin';\n}\n\n/**\n * Host-only land destination branch: the requested `as` when non-empty, else\n * the source branch (server.ts `handleGitSaveToHost` ≡ host-actions.ts\n * `runGitRpc` host-only path).\n */\nexport function resolveLandDest(src: string, as?: string): string {\n return as && as.length > 0 ? as : src;\n}\n\n/**\n * Host-only land refspec for `git fetch . <refspec>` (docker) / `git fetch\n * <bundle> <refspec>` (cloud). Force prepends `+` for a non-fast-forward\n * overwrite of the destination branch.\n */\nexport function landRefspec(src: string, dest: string, force?: boolean): string {\n return `${force ? '+' : ''}${src}:refs/heads/${dest}`;\n}\n\n/** Upstream ref for `git branch --set-upstream-to=<remote>/<branch>`. */\nexport function upstreamRef(remote: string, branch: string): string {\n return `${remote}/${branch}`;\n}\n\n/**\n * Remote-tracking ref for the cloud in-box `git update-ref\n * refs/remotes/<remote>/<branch>` (docker shares .git/, so the ref updates\n * during the push and only the upstream config is missing). Kept beside\n * `upstreamRef` to document the two distinct ref shapes side-by-side.\n */\nexport function remoteTrackingRef(remote: string, branch: string): string {\n return `refs/remotes/${remote}/${branch}`;\n}\n\n/**\n * Detached-HEAD guard for a probed branch name (cloud `runGitRpc` resolves the\n * branch via `rev-parse --abbrev-ref HEAD`). NOTE: intentionally NOT used by\n * ctl's weaker `!branch` check — adopting it there would add a `=== 'HEAD'`\n * rejection on the control-plane lease push path (a behavior change).\n */\nexport function isResolvedBranch(s: string): boolean {\n return s.length > 0 && s !== 'HEAD';\n}\n\n/**\n * Filter a user-supplied extra-argv tail down to strings. The argv *prefixes*\n * differ per site (`git -C repo push …` vs `-C repo push …` vs `push …`) and\n * stay site-local; only this trailing arg-filter is shared.\n */\nexport function sanitizeGitArgs(args: unknown): string[] {\n return Array.isArray(args) ? args.filter((a): a is string => typeof a === 'string') : [];\n}\n\n/**\n * Wire params for the `git.push` / `git.fetch` RPCs. Canonical home for the\n * shape that the relay receives and the in-box ctl builds (previously declared\n * independently in `relay/src/types.ts` and `ctl/src/commands/git.ts`).\n */\nexport interface GitRpcParams {\n /** Container path identifying which worktree to run against. Defaults to /workspace. */\n path?: string;\n /** Remote name; defaults to 'origin'. */\n remote?: string;\n /** Extra argv tail appended after the standard args (e.g. ['--set-upstream', 'origin', 'branch']). */\n args?: string[];\n /**\n * git.push only: land the box's branch in the host's *local* repo instead of\n * pushing to the remote. Nothing is published online; the relay skips the\n * host-initiated-token / confirm-prompt gate (that gate guards remote pushes).\n */\n hostOnly?: boolean;\n /**\n * git.push --host-only only: destination branch name in the host repo.\n * Defaults to the box's current branch name when omitted.\n */\n as?: string;\n /** git.push --host-only only: allow a non-fast-forward overwrite of the destination branch. */\n force?: boolean;\n /**\n * One-time token minted by the host CLI via `/admin/host-initiated/mint`\n * before invoking this RPC through `agentbox-ctl`. The relay validates the\n * token against its in-memory store, scoped to `(boxId, method)`; on\n * match, the token is consumed and the confirm prompt is skipped. Boxes\n * cannot mint these (the admin endpoint is loopback-only), so a malicious\n * agent cannot forge \"host-initiated\" calls. Invalid/expired tokens fall\n * through to the normal prompt path.\n */\n hostInitiated?: string;\n}\n","import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport type {\n BoxRecord,\n DockerBoxFields,\n FindBoxResult,\n SshTargetRecord,\n StateFile,\n} from '@agentbox/core';\n\nexport const STATE_DIR = join(homedir(), '.agentbox');\nexport const STATE_FILE = join(STATE_DIR, 'state.json');\n\nconst EMPTY: StateFile = { version: 1, boxes: [] };\n\n// Cross-process lock tunables. The lock guards the read-modify-write of\n// `state.json` so concurrent `agentbox create`/`destroy` processes can't lose\n// each other's records or interleave a half-written file. Held only for the\n// duration of one read+write (sub-millisecond), so contention clears fast even\n// with a burst of parallel creates.\nconst LOCK_STALE_MS = 15_000; // a lock older than this is presumed abandoned\nconst LOCK_ACQUIRE_TIMEOUT_MS = 20_000;\nconst LOCK_RETRY_MS = 25;\n\n/**\n * Run `fn` while holding an exclusive cross-process lock on `${path}.lock`.\n *\n * Acquisition: create the lockfile with `wx` (O_EXCL) — atomic on local FSes.\n * On contention, retry with a short backoff until {@link LOCK_ACQUIRE_TIMEOUT_MS};\n * a lockfile older than {@link LOCK_STALE_MS} is treated as abandoned (crashed\n * holder) and forcibly broken. If the lock still can't be taken before the\n * timeout we proceed anyway — the write is atomic (temp+rename) so the worst\n * case degrades to a possible lost update, never a corrupt file. The lock is\n * always released in `finally`.\n */\nasync function withStateLock<T>(path: string, fn: () => Promise<T>): Promise<T> {\n const lockPath = `${path}.lock`;\n await mkdir(dirname(path), { recursive: true });\n const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS;\n let held = false;\n while (!held) {\n try {\n const fh = await open(lockPath, 'wx');\n await fh.writeFile(`${String(process.pid)}\\n`);\n await fh.close();\n held = true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;\n // Break a stale lock left by a crashed holder.\n try {\n const st = await stat(lockPath);\n if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {\n await rm(lockPath, { force: true });\n continue;\n }\n } catch {\n // lock vanished between open and stat — retry immediately\n continue;\n }\n if (Date.now() >= deadline) break; // give up waiting; proceed best-effort\n await delay(LOCK_RETRY_MS);\n }\n }\n try {\n return await fn();\n } finally {\n if (held) await rm(lockPath, { force: true }).catch(() => {});\n }\n}\n\n/**\n * Locked read-modify-write of the state file. `mutator` receives the current\n * state and returns the next one; the read and the (atomic) write happen under\n * the same lock so concurrent mutators serialize instead of clobbering.\n */\nexport async function mutateState(\n mutator: (state: StateFile) => StateFile,\n path: string = STATE_FILE,\n): Promise<void> {\n await withStateLock(path, async () => {\n const state = await readState(path);\n await writeState(mutator(state), path);\n });\n}\n\nexport async function readState(path: string = STATE_FILE): Promise<StateFile> {\n try {\n const raw = await readFile(path, 'utf8');\n const parsed = JSON.parse(raw) as StateFile;\n if (parsed.version !== 1 || !Array.isArray(parsed.boxes)) {\n throw new Error(`unrecognized state file shape at ${path}`);\n }\n // Migrate-on-read: records written before the multi-provider split carry no\n // `provider` field — they are all Docker boxes. Default it so every\n // consumer (provider registry, `findBox`) sees a discriminated record.\n // Also backfill `box.docker` from the flat fields for Docker records so\n // forward-looking readers (7.1) see the nested shape without waiting\n // for the box to be re-recorded.\n for (const b of parsed.boxes) {\n b.provider ??= 'docker';\n if ((b.provider ?? 'docker') === 'docker' && !b.docker) {\n b.docker = projectDockerFields(b);\n }\n // The SSH target moved from `box.cloud.ssh` to top-level `box.ssh`.\n // Backfill on read so an already-created box (e.g. a Hetzner box) keeps its\n // `~/.agentbox/ssh/config` alias — `syncAgentboxSshConfig` only reads\n // `box.ssh`, and it would otherwise vanish until the box is next started.\n const legacySsh = (b.cloud as { ssh?: SshTargetRecord } | undefined)?.ssh;\n if (!b.ssh && legacySsh) b.ssh = legacySsh;\n }\n return parsed;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { ...EMPTY };\n }\n throw err;\n }\n}\n\nexport async function writeState(state: StateFile, path: string = STATE_FILE): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n // Atomic: write a sibling temp file then rename over the target. rename(2) is\n // atomic on local filesystems, so a concurrent writer (or a reader) never\n // observes a half-written / interleaved JSON file. The pid+time suffix keeps\n // parallel writers from colliding on the temp path itself.\n const tmp = `${path}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, JSON.stringify(state, null, 2) + '\\n', 'utf8');\n await rename(tmp, path);\n}\n\nexport async function recordBox(box: BoxRecord, path: string = STATE_FILE): Promise<void> {\n // Forward-looking shape: every Docker write also mirrors the flat\n // docker-specific fields into `box.docker` so readers can move to the\n // nested form opportunistically (7.1). Cloud records skip the mirror —\n // the discriminator is `box.provider !== 'docker'`.\n const toWrite: BoxRecord =\n (box.provider ?? 'docker') === 'docker' && !box.docker\n ? { ...box, docker: projectDockerFields(box) }\n : box;\n await mutateState(\n (state) => ({\n version: 1,\n boxes: [...state.boxes.filter((b) => b.id !== toWrite.id), toWrite],\n }),\n path,\n );\n}\n\n/**\n * Record which agent was last launched in a box (`agentbox claude` / `codex` /\n * `opencode`). A locked read-modify-write so it can't clobber a concurrent\n * state change. No-op when the box isn't in state (a race with `destroy`).\n * `agentbox recover` reads `box.lastAgent` to decide which agent to relaunch.\n */\nexport async function recordLastAgent(\n boxId: string,\n kind: 'claude' | 'codex' | 'opencode',\n path: string = STATE_FILE,\n): Promise<void> {\n await mutateState(\n (state) => ({\n version: 1,\n boxes: state.boxes.map((b) => (b.id === boxId ? { ...b, lastAgent: kind } : b)),\n }),\n path,\n );\n}\n\n/**\n * Set (or clear) a box's cosmetic `displayName`. A locked read-modify-write so\n * it can't clobber a concurrent state change. Trims the input; an empty/blank\n * value clears the label (falls back to `name`). No-op when the box isn't in\n * state (a race with `destroy`). The label is display/lookup-only — it does not\n * touch the container, git branch, or URL. Reused by the CLI and the hub.\n */\nexport async function setBoxDisplayName(\n boxId: string,\n displayName: string | undefined,\n path: string = STATE_FILE,\n): Promise<void> {\n const trimmed = displayName?.trim();\n const next = trimmed ? trimmed : undefined;\n await mutateState(\n (state) => ({\n version: 1,\n boxes: state.boxes.map((b) => {\n if (b.id !== boxId) return b;\n if (next) return { ...b, displayName: next };\n const rest = { ...b };\n delete rest.displayName;\n return rest;\n }),\n }),\n path,\n );\n}\n\n/**\n * Persist a box's last resolved SSH target (`box.ssh`). A locked\n * read-modify-write so it can't clobber a concurrent state change. No-op when\n * the box isn't in state (a race with `destroy`). Works for any provider — the\n * docker localhost sshd (host `127.0.0.1` + ephemeral `port`) and cloud\n * providers (Hetzner VPS IP) both land here. `syncAgentboxSshConfig` reads it\n * back to regenerate `~/.agentbox/ssh/config` offline, without re-resolving the\n * target from the provider.\n */\nexport async function recordBoxSsh(\n boxId: string,\n ssh: { host: string; user: string; identityFile?: string; port?: number },\n path: string = STATE_FILE,\n): Promise<void> {\n await mutateState(\n (state) => ({\n version: 1,\n boxes: state.boxes.map((b) => (b.id === boxId ? { ...b, ssh } : b)),\n }),\n path,\n );\n}\n\n/**\n * Atomically allocate the next per-project index AND persist `record` claiming\n * it, under the state lock. Returns the reserved index (also stamped onto the\n * persisted record).\n *\n * Callers bake this index into on-disk paths (`<id>-<n>-<mnemonic>` box dir,\n * socket, snapshot), and host helpers re-derive those paths from the *recorded*\n * index — so the index must be settled before the paths are built. Allocating\n * with an unlocked `readState` and bumping a clash at record time would desync\n * the recorded index from the box's actual directory (status/ctl reads would\n * then miss it). Reserving up front, under the lock, guarantees the index a\n * create uses for its dirs is exactly the one in state.json, with no two\n * concurrent creates in the same project claiming the same number.\n */\nexport async function reserveProjectIndex(\n record: BoxRecord,\n projectRoot: string,\n path: string = STATE_FILE,\n): Promise<number> {\n let index = 1;\n await mutateState((state) => {\n index = allocateProjectIndex(state, projectRoot);\n const reserved: BoxRecord = { ...record, projectRoot, projectIndex: index };\n return {\n version: 1,\n boxes: [...state.boxes.filter((b) => b.id !== record.id), reserved],\n };\n }, path);\n return index;\n}\n\n/**\n * Build a `DockerBoxFields` payload from the flat Docker-specific fields\n * still living on `BoxRecord` for back-compat. Pure function, no\n * filesystem; safe for both `readState` migration and `recordBox` mirror.\n *\n * Once every reader uses `box.docker?.<field>` (the rest of 7.1), the\n * flat fields can be dropped and this projection becomes the canonical\n * shape. Until then, every write produces both shapes from the same\n * source so they can't drift.\n */\nfunction projectDockerFields(box: BoxRecord): DockerBoxFields {\n return {\n container: box.container,\n image: box.image,\n snapshotDir: box.snapshotDir ?? null,\n socketPath: box.socketPath,\n claudeConfigVolume: box.claudeConfigVolume,\n codexConfigVolume: box.codexConfigVolume,\n opencodeConfigVolume: box.opencodeConfigVolume,\n vscodeServerVolume: box.vscodeServerVolume,\n cursorServerVolume: box.cursorServerVolume,\n vncHostPort: box.vncHostPort,\n webHostPort: box.webHostPort,\n portlessAlias: box.portlessAlias,\n portlessUrl: box.portlessUrl,\n portlessVncAlias: box.portlessVncAlias,\n portlessVncUrl: box.portlessVncUrl,\n dockerVolume: box.dockerVolume,\n dockerCacheShared: box.dockerCacheShared,\n checkpointImage: box.checkpointImage,\n };\n}\n\nexport async function removeBoxRecord(id: string, path: string = STATE_FILE): Promise<boolean> {\n let removed = false;\n await mutateState((state) => {\n const next = state.boxes.filter((b) => b.id !== id);\n removed = next.length !== state.boxes.length;\n return { version: 1, boxes: next };\n }, path);\n return removed;\n}\n\n/**\n * Resolve a user-supplied identifier against the state file. Matching\n * precedence mirrors `docker`'s container reference resolution:\n *\n * 1. exact id\n * 2. unique id prefix\n * 3. exact name\n * 4. exact displayName (cosmetic label)\n * 5. exact container name\n *\n * Returns `'ambiguous'` if step 2 finds more than one match (steps 1, 3, 4\n * are exact-match so they cannot be ambiguous on their own).\n */\nexport function findBox(idOrName: string, state: StateFile): FindBoxResult {\n const q = idOrName.trim();\n if (q.length === 0) return { kind: 'none' };\n\n const exactId = state.boxes.find((b) => b.id === q);\n if (exactId) return { kind: 'ok', box: exactId };\n\n const prefixMatches = state.boxes.filter((b) => b.id.startsWith(q));\n if (prefixMatches.length === 1) return { kind: 'ok', box: prefixMatches[0]! };\n if (prefixMatches.length > 1) return { kind: 'ambiguous', matches: prefixMatches };\n\n const byName = state.boxes.find((b) => b.name === q);\n if (byName) return { kind: 'ok', box: byName };\n\n // A renamed box is addressable by its cosmetic `displayName`. Lowest-precedence\n // exact match (after id/name) so a label that happens to equal another box's\n // id/name never shadows it; first match wins on displayName collisions.\n const byDisplayName = state.boxes.find((b) => b.displayName === q);\n if (byDisplayName) return { kind: 'ok', box: byDisplayName };\n\n // For docker records `container` is the docker container name; for cloud\n // records it's `cloud:<sandboxId>` (post 7.2 — no more synthetic\n // agentbox-cloud-* prefix). Either form is a valid byContainer lookup\n // key for `findBox`.\n const byContainer = state.boxes.find((b) => b.container === q);\n if (byContainer) return { kind: 'ok', box: byContainer };\n\n return { kind: 'none' };\n}\n\n/**\n * Next monotonic 1-based index for the given project. Reads only `state.boxes`\n * — caller is responsible for persisting the assignment. Boxes without\n * `projectRoot` are ignored (legacy records); boxes in *other* projects are\n * also ignored. Indices are never recycled, so a destroyed #2 leaves a gap.\n */\nexport function allocateProjectIndex(state: StateFile, projectRoot: string): number {\n let max = 0;\n for (const b of state.boxes) {\n if (b.projectRoot !== projectRoot) continue;\n if (typeof b.projectIndex === 'number' && b.projectIndex > max) {\n max = b.projectIndex;\n }\n }\n return max + 1;\n}\n\n/**\n * Auto-pick when a command's `[box]` argument is omitted. Returns the unique\n * box for `projectRoot`, an `ambiguous` carrying all candidates so the CLI can\n * print a chooser, or `none`.\n */\nexport function autoPickProjectBox(state: StateFile, projectRoot: string): FindBoxResult {\n const matches = state.boxes.filter((b) => b.projectRoot === projectRoot);\n if (matches.length === 0) return { kind: 'none' };\n if (matches.length === 1) return { kind: 'ok', box: matches[0]! };\n return { kind: 'ambiguous', matches };\n}\n\n/**\n * Top-level resolver every CLI command goes through. Combines numeric-index\n * lookup with the legacy `findBox` matcher:\n *\n * - `ref === undefined` and `projectRoot` known → autoPickProjectBox.\n * - `ref` is a pure positive integer and `projectRoot` known → resolve as\n * project index. **Never** falls through to `findBox` on miss, so\n * `agentbox open 3` is reserved for the index and won't accidentally\n * match a hex id like `3abc…`.\n * - Otherwise → `findBox` (id → prefix → name → container).\n */\nexport function resolveBoxRef(\n ref: string | undefined,\n state: StateFile,\n projectRoot: string | undefined,\n): FindBoxResult {\n if (ref === undefined) {\n if (projectRoot === undefined) return { kind: 'none' };\n return autoPickProjectBox(state, projectRoot);\n }\n const trimmed = ref.trim();\n if (projectRoot !== undefined && /^[1-9][0-9]*$/.test(trimmed)) {\n const idx = Number.parseInt(trimmed, 10);\n const hit = state.boxes.find((b) => b.projectRoot === projectRoot && b.projectIndex === idx);\n return hit ? { kind: 'ok', box: hit } : { kind: 'none' };\n }\n return findBox(trimmed, state);\n}\n","import { execa } from 'execa';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport interface DetectedGitRepo {\n kind: 'root' | 'nested';\n /** Absolute host path of the repo working tree (== `<workspace>` for root). */\n hostMainRepo: string;\n /** Path relative to the workspace where the repo lives. Empty string for root. */\n relPathFromWorkspace: string;\n}\n\n/**\n * Look for `.git` directories at the workspace root and at every 1st-level\n * subdirectory. Worktree-form `.git` files (regular file containing\n * `gitdir: …`) are intentionally skipped — turning an existing worktree into\n * another worktree gets weird, and the user case for it is rare.\n *\n * Pure host-side detection: it only tells callers where the repos are. Docker\n * boxes create the worktree inside the container against the bind-mounted\n * `.git/`; cloud boxes clone from a bundle. Either way this is the host probe.\n */\nexport async function detectGitRepos(workspace: string): Promise<DetectedGitRepo[]> {\n const out: DetectedGitRepo[] = [];\n if (await isGitDir(join(workspace, '.git'))) {\n out.push({ kind: 'root', hostMainRepo: workspace, relPathFromWorkspace: '' });\n }\n let entries: Array<{ name: string; isDirectory: () => boolean }>;\n try {\n entries = await readdir(workspace, { withFileTypes: true });\n } catch {\n return out;\n }\n for (const e of entries) {\n if (!e.isDirectory() || e.name.startsWith('.')) continue;\n const sub = join(workspace, e.name);\n if (await isGitDir(join(sub, '.git'))) {\n out.push({ kind: 'nested', hostMainRepo: sub, relPathFromWorkspace: e.name });\n }\n }\n return out;\n}\n\nasync function isGitDir(path: string): Promise<boolean> {\n try {\n const s = await stat(path);\n return s.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Pick `<base>`, `<base>-2`, `<base>-3`, … until git reports no such branch\n * exists. Avoids collision when the user reruns `agentbox create -n same-name`\n * after destroying — the destroyed box's branch still lives in the host repo.\n */\nexport async function pickFreshBranch(hostMainRepo: string, base: string): Promise<string> {\n let candidate = base;\n let suffix = 2;\n while (await branchExists(hostMainRepo, candidate)) {\n candidate = `${base}-${String(suffix++)}`;\n if (suffix > 100) throw new GitWorktreeError(`could not find a free branch name near ${base}`);\n }\n return candidate;\n}\n\nasync function branchExists(hostMainRepo: string, name: string): Promise<boolean> {\n const result = await execa(\n 'git',\n ['-C', hostMainRepo, 'show-ref', '--verify', '--quiet', `refs/heads/${name}`],\n { reject: false },\n );\n return result.exitCode === 0;\n}\n\nexport class GitWorktreeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GitWorktreeError';\n }\n}\n","/**\n * The host command that opens a URL or file path in the OS default handler.\n *\n * macOS ships `open`; Linux uses `xdg-open` (from `xdg-utils`, present on any\n * desktop install). We deliberately return only the binary name and let each\n * call site keep its own spawn semantics (sync/async, stdio, detached) — the\n * single platform decision lives here so adding a host platform is a one-line\n * change. Callers already treat a non-zero exit / ENOENT as \"couldn't\n * auto-open\" and print the target, so an absent `xdg-open` degrades cleanly.\n */\nexport function hostOpenCommand(): string {\n return process.platform === 'linux' ? 'xdg-open' : 'open';\n}\n","import { promises as fs } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { pruneOrphanClaudeSshConfigs } from './claude-app-config.js';\nimport { readState } from './state.js';\n\n/**\n * Host-side SSH-config manager for cloud boxes. AgentBox owns a dedicated file\n * `~/.agentbox/ssh/config` holding one `Host <alias>` block per SSH-capable box,\n * and injects a single managed `Include ~/.agentbox/ssh/config` line into the\n * user's `~/.ssh/config` — so our churn stays out of their hand-maintained\n * config. The owned file is regenerated wholesale from `state.json`\n * (`syncAgentboxSshConfig`), which self-heals stale/destroyed boxes and reads\n * only persisted state (no provider calls, never wakes a paused box).\n *\n * Daytona's SSH gateway authenticates per-token (the User field carries an\n * ephemeral 60-min token from `sb.createSshAccess(60)`), so `agentbox code`\n * re-resolves + re-syncs on every invocation to keep the alias mapped to a live\n * token.\n */\n\nexport interface SshAliasOptions {\n /** Host alias the user (and VS Code Remote-SSH) refers to — the box name, e.g. `myname`. */\n alias: string;\n /** Daytona SSH gateway, typically `ssh.app.daytona.io`. */\n hostname: string;\n /** Ephemeral Daytona token (used as the SSH User). Rotates every call. */\n user: string;\n /**\n * Per-box private key path for providers that authenticate by identity\n * file (docker localhost sshd, Hetzner). Omit for token-in-User auth\n * (Daytona) — without this field VSCode's Remote-SSH would try ~/.ssh/id_*\n * defaults and fail with \"permission denied\" against a Hetzner VPS that only\n * trusts the per-box key under `~/.agentbox/boxes/<id>/ssh/id_ed25519`.\n */\n identityFile?: string;\n /**\n * Non-default SSH port. Docker publishes its in-box sshd on an ephemeral\n * `127.0.0.1:<port>`; omit for cloud providers reachable on 22.\n */\n port?: number;\n}\n\nfunction sshConfigPath(): string {\n return join(homedir(), '.ssh', 'config');\n}\n\n/** AgentBox-owned SSH config file `Include`d from `~/.ssh/config`. */\nexport function agentboxSshConfigPath(): string {\n return join(homedir(), '.agentbox', 'ssh', 'config');\n}\n\nfunction stateFilePath(): string {\n return join(homedir(), '.agentbox', 'state.json');\n}\n\nconst INCLUDE_BEGIN = '# BEGIN agentbox ssh include';\nconst INCLUDE_END = '# END agentbox ssh include';\n\nfunction beginMarker(alias: string): string {\n return `# BEGIN agentbox cloud box ${alias}`;\n}\n\nfunction endMarker(alias: string): string {\n return `# END agentbox cloud box ${alias}`;\n}\n\n/**\n * Stable `~/.ssh/config` Host alias for a box: the box name itself. Box names\n * are already kebab-safe, so `ssh <boxname>` works and external apps (Codex's\n * `codex://…?name=<alias>` deep link, Claude desktop) get a clean, memorable\n * host. Our BEGIN/END-marked managed block keeps this entry isolated from any\n * user-authored `Host <boxname>` so the two coexist.\n */\nexport function agentboxAliasFor(boxName: string): string {\n return boxName;\n}\n\nasync function readFileOrEmpty(path: string): Promise<string> {\n try {\n return await fs.readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return '';\n throw err;\n }\n}\n\nfunction buildBlock(opts: SshAliasOptions): string {\n // `UserKnownHostsFile /dev/null` + `LogLevel ERROR` is the Vagrant / dev-tool\n // convention: many sandboxes sit behind one DNS name, so pinning a host key\n // locally generates noise + false-positive HostKeyVerificationFailed errors.\n const lines: string[] = [\n beginMarker(opts.alias),\n `Host ${opts.alias}`,\n ` HostName ${opts.hostname}`,\n ` User ${opts.user}`,\n ];\n if (opts.port) {\n lines.push(` Port ${String(opts.port)}`);\n }\n if (opts.identityFile) {\n // `IdentitiesOnly yes` stops ssh-agent from offering unrelated keys\n // first — some sshd configs cap auth attempts and would lock us out\n // before the right key is tried.\n lines.push(` IdentityFile ${opts.identityFile}`);\n lines.push(` IdentitiesOnly yes`);\n }\n lines.push(\n ` StrictHostKeyChecking accept-new`,\n ` UserKnownHostsFile /dev/null`,\n ` LogLevel ERROR`,\n endMarker(opts.alias),\n '',\n );\n return lines.join('\\n');\n}\n\n/**\n * Old versions wrote per-box `# BEGIN agentbox cloud box <alias>` … `# END …`\n * blocks directly into `~/.ssh/config`. We now own `~/.agentbox/ssh/config`, so\n * strip any such inline leftovers whenever we touch `~/.ssh/config`. AgentBox is\n * unreleased → clean removal, no deprecation shim.\n */\nfunction stripLegacyInlineBlocks(contents: string): string {\n const pattern =\n /^# BEGIN agentbox cloud box .*\\n[\\s\\S]*?^# END agentbox cloud box .*\\n?/gm;\n return contents.replace(pattern, '');\n}\n\nfunction hasIncludeBlock(contents: string): boolean {\n return (\n contents.includes(INCLUDE_BEGIN) || contents.includes(`Include ${agentboxSshConfigPath()}`)\n );\n}\n\n/**\n * Ensure `~/.ssh/config` contains exactly one managed `Include\n * ~/.agentbox/ssh/config` block, prepended to the top. Prepend (not append)\n * because OpenSSH applies the first value it sees per keyword — putting the\n * Include first lets AgentBox's box entries win over any later user `Host *`\n * defaults. Also strips any legacy inline per-box blocks. Idempotent.\n */\nexport async function ensureSshInclude(): Promise<void> {\n const path = sshConfigPath();\n await fs.mkdir(join(homedir(), '.ssh'), { recursive: true, mode: 0o700 });\n const existing = stripLegacyInlineBlocks(await readFileOrEmpty(path));\n let next = existing;\n if (!hasIncludeBlock(existing)) {\n const block = `${INCLUDE_BEGIN}\\nInclude ${agentboxSshConfigPath()}\\n${INCLUDE_END}\\n`;\n next = existing.length === 0 ? block : `${block}\\n${existing}`;\n }\n await fs.writeFile(path, next, { mode: 0o600 });\n // Re-assert mode in case the file existed with broader perms.\n await fs.chmod(path, 0o600);\n}\n\n/**\n * Regenerate the AgentBox-owned `~/.agentbox/ssh/config` from `state.json`: one\n * `Host <name>` block per box that carries a resolved `box.ssh` target. Reads\n * only persisted state — no provider calls, never wakes a paused box — so a\n * destroyed box's block simply disappears on the next sync. Also ensures the\n * `Include` line in `~/.ssh/config`.\n */\nexport async function syncAgentboxSshConfig(statePath: string = stateFilePath()): Promise<void> {\n const state = await readState(statePath);\n const blocks: string[] = [];\n for (const box of state.boxes) {\n const ssh = box.ssh;\n if (!ssh) continue;\n blocks.push(\n buildBlock({\n alias: agentboxAliasFor(box.name),\n hostname: ssh.host,\n user: ssh.user,\n identityFile: ssh.identityFile,\n port: ssh.port,\n }),\n );\n }\n const header =\n '# Managed by agentbox — regenerated on box create/start/destroy.\\n' +\n '# Do not edit; changes are overwritten. Disable with `agentbox config set ssh.autoConfig false`.\\n\\n';\n const path = agentboxSshConfigPath();\n await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });\n await fs.writeFile(path, header + blocks.join('\\n'), { mode: 0o600 });\n await fs.chmod(path, 0o600);\n await ensureSshInclude();\n\n // Sweep Claude desktop's sshConfigs (written by `open --in claude`) of\n // entries whose box is gone — piggybacking on the sync means every destroy\n // path prunes (CLI, hub, dashboard), and any later sync self-heals one that\n // didn't. Aliases are keyed by box NAME (an entry survives a transiently\n // ssh-less record). Best-effort: a corrupt settings.json must never break\n // box lifecycle.\n try {\n pruneOrphanClaudeSshConfigs(new Set(state.boxes.map((b) => agentboxAliasFor(b.name))));\n } catch {\n /* best-effort */\n }\n}\n\n/**\n * True when `~/.ssh/config` has a user-authored `Host <alias>` stanza. With the\n * Include prepended, AgentBox's entry is read first so it wins — but a foreign\n * `Host <alias>` is still worth flagging to the user in case they expected their\n * own entry to take effect.\n */\nexport async function hasUnmanagedHostConflict(alias: string): Promise<boolean> {\n const contents = stripLegacyInlineBlocks(await readFileOrEmpty(sshConfigPath()));\n if (contents === '') return false;\n return contents.split('\\n').some((line) => {\n const m = /^\\s*Host\\s+(.+?)\\s*$/.exec(line);\n if (!m) return false;\n return m[1]!.split(/\\s+/).includes(alias);\n });\n}\n\nexport interface SshTarget {\n user: string;\n host: string;\n /** Path from `-i <path>` if the argv carries one (Hetzner). Undefined for\n * Daytona where auth is via token-in-User. */\n identityFile?: string;\n}\n\n/**\n * Pluck the SSH connect target (and identity file, if any) out of an argv\n * returned by a provider's `attachArgv` / `buildAttach`. The argv shape is\n * `ssh [-i <path>] [-o ...] <user>@<host> [command...]` — we walk from the\n * end to find the user@host token and scan forward for `-i`.\n */\nexport function parseSshTarget(argv: readonly string[]): SshTarget | undefined {\n let target: { user: string; host: string } | undefined;\n for (let i = argv.length - 1; i >= 0; i--) {\n const v = argv[i];\n if (!v || v.startsWith('-')) continue;\n const at = v.indexOf('@');\n if (at <= 0) continue;\n target = { user: v.slice(0, at), host: v.slice(at + 1) };\n break;\n }\n if (!target) return undefined;\n let identityFile: string | undefined;\n for (let i = 0; i < argv.length - 1; i++) {\n if (argv[i] === '-i') {\n identityFile = argv[i + 1];\n break;\n }\n }\n return { ...target, identityFile };\n}\n\n/**\n * Read back the `HostName` / `IdentityFile` from the managed block for `alias`\n * in `~/.agentbox/ssh/config`, if one exists. Used by `inspect` to surface the\n * SSH connection details without re-deriving them from a provider (which would\n * require bringing the box online). Returns undefined when no managed block is\n * present for the alias.\n */\nexport async function readAgentboxSshAlias(\n alias: string,\n): Promise<{ hostName?: string; identityFile?: string } | undefined> {\n const contents = await readFileOrEmpty(agentboxSshConfigPath());\n if (contents === '') return undefined;\n const begin = beginMarker(alias);\n const end = endMarker(alias);\n const escape = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const match = new RegExp(`^${escape(begin)}\\\\n([\\\\s\\\\S]*?)${escape(end)}`, 'm').exec(contents);\n if (!match) return undefined;\n const body = match[1] ?? '';\n const field = (name: string): string | undefined =>\n new RegExp(`^\\\\s*${name}\\\\s+(.+)$`, 'm').exec(body)?.[1]?.trim();\n return { hostName: field('HostName'), identityFile: field('IdentityFile') };\n}\n","/**\n * Writer for the Claude desktop app's own settings (`~/.claude/settings.json`)\n * — the app-local analogue of Codex's `codex://settings/connections/ssh/add`\n * deep link, which Claude.app doesn't have. The app reads SSH environments\n * from a `sshConfigs` array in its user settings (schema verified against\n * Claude.app v1.19367): `{ id, name, sshHost, sshPort?, sshIdentityFile?,\n * startDirectory? }`, where `sshHost` may be an alias from `~/.ssh/config` —\n * which is exactly what AgentBox maintains per box.\n *\n * This file is the user's REAL Claude Code settings: preserve every key we\n * don't own, and fail loud (never overwrite) when it exists but doesn't parse.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nexport interface ClaudeSshConfigEntry {\n /** Unique id; the app matches configs across settings sources by it. */\n id: string;\n /** Display name shown in the app's Environment dropdown. */\n name: string;\n /** \"user@host\", \"host\", or an alias from ~/.ssh/config. */\n sshHost: string;\n sshPort?: number;\n sshIdentityFile?: string;\n /** Default working directory on the remote (tilde-expanded by the app). */\n startDirectory?: string;\n}\n\nexport function claudeSettingsPath(): string {\n return join(homedir(), '.claude', 'settings.json');\n}\n\n/** The sshConfigs entry for a box: the alias carries port + identity file. */\nexport function claudeSshEntryFor(alias: string, boxName: string): ClaudeSshConfigEntry {\n return {\n id: `agentbox-${alias}`,\n name: `AgentBox: ${boxName}`,\n sshHost: alias,\n startDirectory: '/workspace',\n };\n}\n\ninterface ClaudeSettings {\n sshConfigs?: unknown[];\n [key: string]: unknown;\n}\n\nfunction readSettings(path: string): ClaudeSettings {\n if (!existsSync(path)) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, 'utf8'));\n } catch (err) {\n throw new Error(\n `${path} exists but is not valid JSON (${err instanceof Error ? err.message : String(err)}) — ` +\n `not touching it. Fix the file and retry.`,\n );\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${path} is not a JSON object — not touching it. Fix the file and retry.`);\n }\n return parsed as ClaudeSettings;\n}\n\nfunction writeSettings(path: string, settings: ClaudeSettings): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(settings, null, 2) + '\\n');\n}\n\nfunction entryId(e: unknown): string | undefined {\n if (e !== null && typeof e === 'object' && typeof (e as { id?: unknown }).id === 'string') {\n return (e as { id: string }).id;\n }\n return undefined;\n}\n\n/**\n * Insert or replace (by `id`) one entry in `sshConfigs`, preserving every\n * other entry and every other settings key. Throws on an unparseable file.\n */\nexport function upsertClaudeSshConfig(entry: ClaudeSshConfigEntry): void {\n const path = claudeSettingsPath();\n const settings = readSettings(path);\n const configs = Array.isArray(settings.sshConfigs) ? settings.sshConfigs : [];\n const idx = configs.findIndex((e) => entryId(e) === entry.id);\n if (idx >= 0) {\n configs[idx] = entry;\n } else {\n configs.push(entry);\n }\n settings.sshConfigs = configs;\n writeSettings(path, settings);\n}\n\n/**\n * Drop every AgentBox-owned (`agentbox-`-prefixed) entry whose alias no longer\n * matches a live box. Called (best-effort) from `syncAgentboxSshConfig`, which\n * every lifecycle path runs — CLI destroy, hub/dashboard destroys via\n * `provider.destroy`+sync, and any later create/start — so an entry left by a\n * path that skipped the sync is swept on the next one. Foreign entries (no\n * `agentbox-` prefix) are never touched.\n */\nexport function pruneOrphanClaudeSshConfigs(liveAliases: ReadonlySet<string>): number {\n return removeClaudeSshConfigs(\n (id) => id.startsWith('agentbox-') && !liveAliases.has(id.slice('agentbox-'.length)),\n );\n}\n\n/**\n * Drop every `sshConfigs` entry whose id matches `predicate`. No-op when the\n * file is missing, has no `sshConfigs`, or nothing matches — the file is only\n * rewritten on a change. Throws on an unparseable file (callers treat this as\n * best-effort).\n */\nexport function removeClaudeSshConfigs(predicate: (id: string) => boolean): number {\n const path = claudeSettingsPath();\n if (!existsSync(path)) return 0;\n const settings = readSettings(path);\n if (!Array.isArray(settings.sshConfigs)) return 0;\n const kept = settings.sshConfigs.filter((e) => {\n const id = entryId(e);\n return id === undefined || !predicate(id);\n });\n const removed = settings.sshConfigs.length - kept.length;\n if (removed === 0) return 0;\n settings.sshConfigs = kept;\n writeSettings(path, settings);\n return removed;\n}\n","import type { BoxRecord, Provider } from '@agentbox/core';\nimport { recordBoxSsh } from './state.js';\nimport { agentboxAliasFor, parseSshTarget, syncAgentboxSshConfig } from './ssh-config.js';\n\n/**\n * Resolve + persist a cloud box's SSH connection target and regenerate\n * `~/.agentbox/ssh/config`. Lives in sandbox-core (not the CLI) so BOTH the CLI\n * commands AND the hub can write the SSH config after create/start/resume — the\n * caller supplies the already-resolved `Provider` (the CLI via `providerForBox`,\n * the hub via its own provider seam), so this code takes no dependency on either\n * one's provider registry.\n */\n\nexport interface CloudSshAlias {\n /** Host alias written to `~/.ssh/config` (the box name). */\n alias: string;\n /** SSH host — VPS IP (Hetzner) or gateway domain (Daytona). */\n host: string;\n /** SSH user — `vscode` (Hetzner) or an ephemeral token (Daytona). */\n user: string;\n /**\n * Per-box private key path when the provider authenticates by identity file\n * (Hetzner). Undefined for token-in-User providers (Daytona) — callers that\n * need a persistent connection (external apps) should treat its absence as\n * \"not supported\".\n */\n identityFile?: string;\n}\n\nexport interface CloudSshOptions {\n /**\n * Bring the box online (resume/start) before resolving the target. Default\n * true. Callers that already brought the box online (e.g. `agentbox code`\n * after its own wait-ready) pass false to skip a redundant lifecycle pass.\n */\n bringOnline?: boolean;\n /** Optional progress logger for the bring-online path (CLI passes clack's `log.info`). */\n logInfo?: (msg: string) => void;\n}\n\n/**\n * Resolve a cloud box's SSH connection target WITHOUT touching `~/.ssh/config`.\n * Lets callers inspect the target (e.g. gate on a persistent `identityFile`)\n * before deciding to persist an alias.\n *\n * The SSH-support check runs FIRST, before any lifecycle action — so an\n * unsupported provider (e.g. Docker, which has no `buildAttach`) errors without\n * resuming/starting the box. `buildAttach(..., { noTmux: true })` yields the\n * plain `ssh ... <user>@<host>` argv; the identity path (if any) is parsed\n * straight out of it so we never hardcode a provider-specific key path.\n */\nexport async function resolveCloudSshTarget(\n box: BoxRecord,\n provider: Provider,\n opts: CloudSshOptions = {},\n): Promise<CloudSshAlias> {\n if (!provider.buildAttach) {\n throw new Error(`cloud provider '${provider.name}' does not support SSH attach`);\n }\n\n if (opts.bringOnline ?? true) {\n const state = await provider.probeState(box);\n if (state === 'paused') {\n opts.logInfo?.('box is paused; resuming');\n await provider.resume(box);\n } else if (state === 'stopped') {\n opts.logInfo?.('box is stopped; starting');\n await provider.start(box);\n } else if (state === 'missing') {\n throw new Error(`cloud sandbox for ${box.name} is missing; was it deleted?`);\n }\n }\n\n const spec = await provider.buildAttach(box, 'shell', { noTmux: true });\n const target = parseSshTarget(spec.argv);\n if (!target) {\n throw new Error(`could not parse <user>@<host> from cloud SSH argv: ${spec.argv.join(' ')}`);\n }\n const alias = agentboxAliasFor(box.name);\n return { alias, host: target.host, user: target.user, identityFile: target.identityFile };\n}\n\n/**\n * Bring a cloud box online, persist its resolved SSH target to `box.ssh`,\n * and regenerate `~/.agentbox/ssh/config` (+ the `~/.ssh/config` Include),\n * returning the connection target. Shared by `agentbox code` (VS Code\n * Remote-SSH), `agentbox open` (sshfs mount), and `agentbox shell --ssh-config`\n * (external app handoff) — all three need the same alias mapped to a live SSH\n * target. These are explicit user actions, so they write regardless of the\n * `ssh.autoConfig` toggle (which only governs the proactive create/start path).\n */\nexport async function ensureCloudSshAlias(\n box: BoxRecord,\n provider: Provider,\n opts: CloudSshOptions = {},\n): Promise<CloudSshAlias> {\n const conn = await resolveCloudSshTarget(box, provider, opts);\n await recordBoxSsh(box.id, {\n host: conn.host,\n user: conn.user,\n identityFile: conn.identityFile,\n });\n await syncAgentboxSshConfig();\n return conn;\n}\n\n/**\n * Proactive, default-on SSH-config write on create/start/resume — gated by the\n * `ssh.autoConfig` config key so a user who manages `~/.ssh/config` themselves\n * can opt out. Only persistent-identity providers qualify (Hetzner/DigitalOcean:\n * a per-box identity file that survives across sessions); Daytona's ephemeral\n * token and Docker/Vercel/E2B (no SSH) are skipped. Best-effort: a failure here\n * must never break the lifecycle command/action that triggered it — but it is no\n * longer swallowed silently, so `logWarn` surfaces the reason (CLI stderr, hub log).\n *\n * The box is assumed already online (create just finished, or start/resume\n * brought it up), so `bringOnline: false` avoids a redundant lifecycle pass.\n * Re-resolving on start is what refreshes a Hetzner box's changed public IP.\n */\nexport async function autoWriteSshConfig(\n box: BoxRecord,\n provider: Provider,\n enabled: boolean,\n logWarn?: (msg: string) => void,\n): Promise<void> {\n if (!enabled) return;\n try {\n const conn = await resolveCloudSshTarget(box, provider, { bringOnline: false });\n if (!conn.identityFile) return;\n await recordBoxSsh(box.id, {\n host: conn.host,\n user: conn.user,\n identityFile: conn.identityFile,\n });\n await syncAgentboxSshConfig();\n } catch (err) {\n // Best-effort: SSH-config auto-write must never break create/start. But\n // surface the reason rather than swallowing it (this masked the hub-create\n // gap for a whole release).\n logWarn?.(\n `ssh-config auto-write for ${box.name} failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n","/**\n * Per-box SSH key minting, shared by every provider that authenticates a box\n * over SSH by identity file: the docker localhost sshd and the Hetzner VPS both\n * mint a fresh ed25519 keypair per box and never let the private key leave the\n * host. The public key is installed into the box's `authorized_keys` (docker via\n * `docker exec`, Hetzner via cloud-init).\n */\n\nimport { mkdir, readFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { execa } from 'execa';\n\nexport interface MintedSshKey {\n /** Directory holding the key files. */\n dir: string;\n /** Absolute path to the private key. */\n privatePath: string;\n /** Absolute path to the public key. */\n publicPath: string;\n /** Public key contents (one OpenSSH-format line). */\n publicKey: string;\n}\n\n/**\n * Mint a fresh ed25519 keypair into `targetDir/id_ed25519` (+ `.pub`). The\n * directory is created if missing (0700). `comment` is embedded in the public\n * key so the key is identifiable in `authorized_keys` on a forensic look.\n *\n * Reuses the existing keypair when `targetDir/id_ed25519` is already present\n * (idempotent across `agentbox start`), reading its `.pub` back — callers on the\n * restart path can call this blindly without clobbering the key the box already\n * trusts.\n */\nexport async function mintSshKey(targetDir: string, comment: string): Promise<MintedSshKey> {\n const dir = resolve(targetDir);\n const priv = join(dir, 'id_ed25519');\n const pub = `${priv}.pub`;\n await mkdir(dir, { recursive: true, mode: 0o700 });\n\n const existing = await readFile(pub, 'utf8').catch(() => null);\n if (existing !== null) {\n return { dir, privatePath: priv, publicPath: pub, publicKey: existing.trim() };\n }\n\n // `ssh-keygen -N ''` for no passphrase; `-q` to suppress the random art.\n await execa('ssh-keygen', ['-t', 'ed25519', '-N', '', '-C', comment, '-f', priv, '-q'], {\n stdio: 'pipe',\n });\n\n const publicKey = (await readFile(pub, 'utf8')).trim();\n return { dir, privatePath: priv, publicPath: pub, publicKey };\n}\n","/**\n * Provider-agnostic box git + service-control helpers, shared by the host CLI\n * (`agentbox git …` / `agentbox services …`) and the hub backend so the argv and\n * RPC-param contracts never drift between the two frontends.\n *\n * Credentialed git RPCs (push / pull-fetch) carry a one-time host-initiated\n * token; minting is a relay concern, so the caller injects it via\n * `deps.hostInitiatedArgs`. Keeping the mint out of this module is deliberate:\n * `@agentbox/relay` depends on `@agentbox/sandbox-core`, so this package must not\n * reach back to relay/ctl (that would be a dependency cycle).\n *\n * The predicted `GitRpcParams` built here MUST match, byte-for-byte, what the\n * in-box `agentbox-ctl git` sends, or the relay's params-hash binding rejects\n * the minted token. This mirrors `buildParams` in `packages/ctl/src/commands/git.ts`.\n */\nimport type { BoxRecord, ExecResult, GitRpcParams, Provider } from '@agentbox/core';\nimport { isScratchBranch, SCRATCH_BRANCH_PREFIX } from '@agentbox/core';\n\n/** The box workspace is always mounted here; ctl mirrors `process.cwd()` into `params.path`. */\nexport const BOX_WORKSPACE = '/workspace';\n\n/**\n * Mint a `--host-initiated-token <tok>` argv fragment bound to a git RPC's\n * `(method, params)`. Returns `[]` when no token could be minted — the call\n * still proceeds through the relay's normal prompt path (and `agentbox/*`\n * scratch pushes auto-allow with no prompt regardless).\n */\nexport type HostInitiatedArgs = (method: string, params: GitRpcParams) => Promise<string[]>;\n\nexport interface BoxGitDeps {\n hostInitiatedArgs?: HostInitiatedArgs;\n}\n\nfunction run(provider: Provider, box: BoxRecord, argv: string[]): Promise<ExecResult> {\n return provider.exec(box, argv, { cwd: BOX_WORKSPACE });\n}\n\n/** Normalize a user-supplied name to an `agentbox/<name>` scratch branch (idempotent). */\nexport function scratchBranchName(name: string): string {\n const trimmed = name.trim();\n return isScratchBranch(trimmed) ? trimmed : `${SCRATCH_BRANCH_PREFIX}${trimmed}`;\n}\n\n/** `git checkout <branch>` — switch the box's worktree. No relay: local to the worktree. */\nexport function boxGitCheckout(\n provider: Provider,\n box: BoxRecord,\n branch: string,\n extraArgs: string[] = [],\n): Promise<ExecResult> {\n return run(provider, box, ['git', 'checkout', branch, ...extraArgs]);\n}\n\n/**\n * `git checkout -b agentbox/<name> [from]` — create AND switch onto a fresh\n * scratch branch (from HEAD by default, or the given base ref). Local to the\n * worktree; for docker the branch lands in the bind-mounted host `.git/`\n * immediately, for cloud it stays in-box until pushed to the host.\n */\nexport function boxGitNewBranch(\n provider: Provider,\n box: BoxRecord,\n name: string,\n from?: string,\n): Promise<ExecResult> {\n const argv = ['git', 'checkout', '-b', scratchBranchName(name)];\n if (from && from.trim()) argv.push(from.trim());\n return run(provider, box, argv);\n}\n\n/** Build the `{ path, remote?, args? }` ctl sends for a git.push / git.fetch RPC. */\nfunction gitRpcParams(remote: string | undefined, extraArgs: string[]): GitRpcParams {\n const params: GitRpcParams = { path: BOX_WORKSPACE };\n if (remote) params.remote = remote;\n if (extraArgs.length > 0) params.args = extraArgs;\n return params;\n}\n\n/** `agentbox-ctl git push` — push the box's branch to the remote via the host relay. */\nexport async function boxGitPush(\n provider: Provider,\n box: BoxRecord,\n opts: { remote?: string; force?: boolean; args?: string[] },\n deps: BoxGitDeps = {},\n): Promise<ExecResult> {\n // `--force` is a real remote-push flag; ctl normalizes it back onto the args\n // tail, so it must be part of the predicted params hash (force last, matching\n // the host CLI).\n const extraArgs = [...(opts.args ?? []), ...(opts.force ? ['--force'] : [])];\n const params = gitRpcParams(opts.remote, extraArgs);\n const tokenArgs = deps.hostInitiatedArgs ? await deps.hostInitiatedArgs('git.push', params) : [];\n const argv = ['agentbox-ctl', 'git', 'push', ...tokenArgs];\n if (opts.remote) argv.push('--remote', opts.remote);\n argv.push(...extraArgs);\n return run(provider, box, argv);\n}\n\n/**\n * `agentbox-ctl git pull` — fetch via the relay then merge in /workspace. Only\n * `git.fetch` crosses the relay (the merge is local, no creds), so the token is\n * scoped to `git.fetch`. `--ff-only` is consumed by ctl (not forwarded to the\n * relay) so it stays out of the predicted params hash.\n */\nexport async function boxGitPull(\n provider: Provider,\n box: BoxRecord,\n opts: { remote?: string; ffOnly?: boolean; args?: string[] },\n deps: BoxGitDeps = {},\n): Promise<ExecResult> {\n const extraArgs = opts.args ?? [];\n const params = gitRpcParams(opts.remote, extraArgs);\n const tokenArgs = deps.hostInitiatedArgs ? await deps.hostInitiatedArgs('git.fetch', params) : [];\n const argv = ['agentbox-ctl', 'git', 'pull', ...tokenArgs];\n if (opts.remote) argv.push('--remote', opts.remote);\n if (opts.ffOnly) argv.push('--ff-only');\n argv.push(...extraArgs);\n return run(provider, box, argv);\n}\n\n/**\n * `agentbox-ctl git push --host-only` — land the box's branch in the host's\n * *local* repo, publishing nothing. The relay skips its confirm/token gate\n * (that gate guards remote pushes), so no host-initiated token is needed.\n */\nexport function boxGitPushHost(\n provider: Provider,\n box: BoxRecord,\n opts: { as?: string; force?: boolean; args?: string[] } = {},\n): Promise<ExecResult> {\n const argv = ['agentbox-ctl', 'git', 'push', '--host-only'];\n if (opts.as) argv.push('--as', opts.as);\n if (opts.force) argv.push('--force');\n argv.push(...(opts.args ?? []));\n return run(provider, box, argv);\n}\n\n// ── service control (in-box supervisor) ──\n// The argv is single-sourced here; parsing the `--json` StatusReply stays in the\n// callers (they can import `@agentbox/ctl`; this module can't — cycle, see above).\n\n/** `agentbox-ctl status --json` — dump the live task/service/port snapshot. */\nexport function servicesStatusArgv(): string[] {\n return ['agentbox-ctl', 'status', '--json'];\n}\n\n/** Run the live status pull and return the raw exec result (caller parses stdout). */\nexport function boxServicesStatusRaw(provider: Provider, box: BoxRecord): Promise<ExecResult> {\n return run(provider, box, servicesStatusArgv());\n}\n\n/** `agentbox-ctl restart <name>` — restart one supervised service. */\nexport function restartServiceArgv(name: string): string[] {\n return ['agentbox-ctl', 'restart', name];\n}\n\n/** Restart a single supervised service by name. */\nexport function boxRestartService(provider: Provider, box: BoxRecord, name: string): Promise<ExecResult> {\n return run(provider, box, restartServiceArgv(name));\n}\n\n/**\n * Restart every named service in sequence (host-side loop — no in-box wire op,\n * so it works on already-baked boxes). Returns each service's exec result so the\n * caller can report partial failures. Sequential (not parallel) to keep the box\n * from thrashing when services depend on one another.\n */\nexport async function boxRestartServices(\n provider: Provider,\n box: BoxRecord,\n names: string[],\n): Promise<{ name: string; result: ExecResult }[]> {\n const out: { name: string; result: ExecResult }[] = [];\n for (const name of names) {\n out.push({ name, result: await boxRestartService(provider, box, name) });\n }\n return out;\n}\n","/**\n * Shared shape for a provider health-check row, produced by each provider's\n * `doctorChecks()` and consumed by `agentbox doctor` / the install wizard, plus\n * the `ProviderModule` contract the CLI loads each `@agentbox/sandbox-<name>`\n * through.\n *\n * Lives in sandbox-core (not apps/cli) so each provider package can own its own\n * probes and login/credential surface without depending on the CLI — a new\n * provider ships all of this in its own package and the CLI dispatches to it\n * generically via a lazy `import()`.\n */\n\nimport type { CloudBackend, Provider } from '@agentbox/core';\n\n/**\n * `info` is for rows that are intentionally inert (e.g. an integration the\n * user hasn't enabled). It surfaces as a distinct glyph but rolls up like\n * `ok` so it never pushes the overall doctor status to \"warn\".\n */\nexport type CheckStatus = 'ok' | 'info' | 'warn' | 'fail';\n\nexport interface CheckResult {\n label: string;\n status: CheckStatus;\n detail: string;\n hint?: string;\n}\n\n/** Normalized credential state used by the install wizard's re-auth prompt. */\nexport interface CredStatusSummary {\n configured: boolean;\n /** Optional detail shown in the \"already configured (…)\" line (e.g. auth kind). */\n label?: string;\n}\n\n/**\n * Outcome of a non-interactive `setCredentials` call (the headless path the hub\n * drives). `status` reflects the store *after* the attempt, so a caller can\n * report `configured` without a second read.\n */\nexport interface CredSetResult {\n ok: boolean;\n /** One-line failure reason when `ok` is false (e.g. a rejected token). */\n error?: string;\n status: CredStatusSummary;\n}\n\n/**\n * The uniform surface every `@agentbox/sandbox-<name>` package exposes as\n * `export const providerModule`. The CLI's provider loader resolves this via a\n * lazy `import()` and drives create / doctor / install / checkpoint through it,\n * so adding a provider needs no per-provider `switch` arm in the CLI.\n */\nexport interface ProviderModule {\n /** The `Provider` implementation (lifecycle, exec, attach, checkpoint…). */\n provider: Provider;\n /** Cloud backend (host-side executor). Absent for the local docker provider. */\n backend?: CloudBackend;\n /**\n * First-run credential gate. Called before `create`/`claude`/etc. hand out\n * the provider. Absent for docker (no login). `force` re-runs the flow.\n */\n ensureCredentials?: (opts?: { force?: boolean }) => Promise<void>;\n /** Normalized credential state for the install wizard. Absent for docker. */\n readCredStatus?: () => Promise<CredStatusSummary> | CredStatusSummary;\n /**\n * Non-interactive credential write (the headless path a hub/API driver uses,\n * bypassing the TTY-gated `ensureCredentials` prompts). Validates the given\n * fields against the cloud, then persists them to `~/.agentbox/secrets.env`.\n * The `fields` shape is provider-specific (e.g. `{ apiKey }`, `{ token }`,\n * `{ token, teamId?, projectId? }`). Absent for docker (no login). Never\n * returns the secret values.\n */\n setCredentials?: (fields: Record<string, string>) => Promise<CredSetResult>;\n /**\n * CURRENT build-context fingerprint of the provider's base image/snapshot,\n * for staleness nagging. Absent for docker (its base self-heals).\n */\n currentBaseFingerprintLive?: (\n claudeInstall?: 'native' | 'npm',\n ) => Promise<string | undefined>;\n /** Local, offline-safe health probes for `agentbox doctor`. */\n doctorChecks: () => Promise<CheckResult[]>;\n}\n\n/** First line of a multi-line string (for compact error summaries). */\nexport function firstLine(s: string): string {\n const i = s.indexOf('\\n');\n return i === -1 ? s : s.slice(0, i);\n}\n\n/** Compact one-line summary of an unknown thrown value. */\nexport function errSummary(err: unknown): string {\n return err instanceof Error ? firstLine(err.message) : String(err);\n}\n","/**\n * Shared writer for the managed cloud-credential store at\n * `~/.agentbox/secrets.env`. Every cloud provider (`daytona`, `hetzner`,\n * `vercel`, `e2b`) persists its API keys/tokens here so the per-provider\n * env-loaders pick them up for every command. The write logic was copy-pasted\n * across four `credentials.ts` files (`writeManaged` / `persistCredentials`);\n * this consolidates it.\n *\n * The file is a plain `KEY=value` env file (optionally `export KEY=value`),\n * mode 0600, written atomically (temp + rename, atomic on the same filesystem).\n */\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, resolve } from 'node:path';\n\n/** Canonical path of the managed secrets file: `~/.agentbox/secrets.env`. */\nexport function secretsEnvPath(): string {\n return resolve(homedir(), '.agentbox', 'secrets.env');\n}\n\n/**\n * Atomically rewrite a set of managed keys in `~/.agentbox/secrets.env`: strip\n * every prior value for a `managedKeys` entry (whether written as `KEY=` or\n * `export KEY=`), then append exactly the keys in `record`. Unrelated lines the\n * user dropped in the file are preserved untouched. Also mirrors the change into\n * `process.env` — every `managedKeys` entry is cleared first, then `record` is\n * applied — so the current process uses the new values immediately (and a stale\n * alternate auth method, e.g. an old JWT when switching to an API key, is gone).\n *\n * File is written mode 0600.\n */\nexport function writeManagedSecrets(\n managedKeys: readonly string[],\n record: Record<string, string>,\n): void {\n for (const k of managedKeys) delete process.env[k];\n for (const [k, v] of Object.entries(record)) process.env[k] = v;\n\n const path = secretsEnvPath();\n mkdirSync(dirname(path), { recursive: true });\n\n let existing = '';\n if (existsSync(path)) {\n try {\n existing = readFileSync(path, 'utf8');\n } catch {\n existing = '';\n }\n }\n\n const kept = existing\n .split(/\\r?\\n/)\n .filter((line) => {\n const stripped = line.startsWith('export ') ? line.slice('export '.length) : line;\n const eq = stripped.indexOf('=');\n if (eq <= 0) return true;\n const key = stripped.slice(0, eq).trim();\n return !managedKeys.includes(key);\n })\n .join('\\n')\n .replace(/\\s+$/u, '');\n\n const lines = Object.entries(record).map(([k, v]) => `${k}=${v}`);\n const body = (kept ? `${kept}\\n` : '') + lines.join('\\n') + '\\n';\n\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, body, { mode: 0o600 });\n try {\n chmodSync(tmp, 0o600);\n } catch {\n // chmod best-effort; writeFileSync mode already covers most filesystems.\n }\n renameSync(tmp, path);\n try {\n chmodSync(path, 0o600);\n } catch {\n // ignore — already attempted on the temp file\n }\n}\n\n/**\n * Mask a secret for display: keep the first and last 4 chars, hide the middle.\n * Short values are fully masked. Never returns the raw secret.\n */\nexport function maskSecret(value: string): string {\n if (value.length <= 8) return '*'.repeat(value.length);\n return `${value.slice(0, 4)}…${'*'.repeat(8)}${value.slice(-4)}`;\n}\n","/**\n * The external-provider plugin registry: `~/.agentbox/plugins.json`.\n *\n * A community provider ships as its own npm package (`agentbox-provider-<name>`)\n * built against `@madarco/agentbox-provider-sdk`. The user installs it themselves, then\n * `agentbox plugin add <pkg>` validates it and records it here; the CLI and the\n * host relay both read this file to resolve + lazily `import()` the package at\n * runtime (a true variable specifier — built-ins are bundle-inlined, external\n * providers are not).\n *\n * Concurrency + durability mirror `state.ts`: an O_EXCL lockfile guards the\n * read-modify-write, and writes are atomic (temp + rename). Reads have a sync\n * variant so the CLI's synchronous `isKnownProvider`/name-list checks can\n * consult it without going async.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\n\nexport const PLUGINS_FILE = join(homedir(), '.agentbox', 'plugins.json');\n\n/**\n * `SDK_API_VERSION` majors this CLI can load. A plugin built against an SDK\n * whose major is not listed is refused at `plugin add` and skipped at load\n * (with a warning) rather than crashing the CLI. Extend this array when the CLI\n * keeps back-compat with an older provider contract.\n */\n// v2: BoxRecord.cloud.ssh moved to top-level BoxRecord.ssh (+port, docker sshd\n// fields). v1 plugins still load — only ones reading box.cloud.ssh notice.\nexport const SUPPORTED_SDK_API_VERSIONS: readonly number[] = [1, 2];\n\nexport function isSupportedApiVersion(v: number): boolean {\n return SUPPORTED_SDK_API_VERSIONS.includes(v);\n}\n\n/** One registered external provider package. */\nexport interface PluginRecord {\n /** Package name as installed (e.g. `agentbox-provider-digitalocean`). */\n packageName: string;\n /** Absolute path to the package's resolved entry module, recorded at add time. */\n resolvedEntry: string;\n /** Package version at add time (informational). */\n version: string;\n /** Provider names this package contributes (from each `providerModule.provider.name`). */\n providers: string[];\n /** `SDK_API_VERSION` the package declared (compat gate). */\n apiVersion: number;\n /** ISO timestamp the package was added. */\n addedAt: string;\n}\n\nexport interface PluginsFile {\n version: 1;\n plugins: PluginRecord[];\n}\n\nconst EMPTY: PluginsFile = { version: 1, plugins: [] };\n\nconst LOCK_STALE_MS = 15_000;\nconst LOCK_ACQUIRE_TIMEOUT_MS = 20_000;\nconst LOCK_RETRY_MS = 25;\n\n/** Exclusive cross-process lock around `${path}.lock` (mirrors state.ts). */\nasync function withFileLock<T>(path: string, fn: () => Promise<T>): Promise<T> {\n const lockPath = `${path}.lock`;\n await mkdir(dirname(path), { recursive: true });\n const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS;\n let held = false;\n while (!held) {\n try {\n const fh = await open(lockPath, 'wx');\n await fh.writeFile(`${String(process.pid)}\\n`);\n await fh.close();\n held = true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;\n try {\n const st = await stat(lockPath);\n if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {\n await rm(lockPath, { force: true });\n continue;\n }\n } catch {\n continue;\n }\n if (Date.now() >= deadline) break;\n await delay(LOCK_RETRY_MS);\n }\n }\n try {\n return await fn();\n } finally {\n if (held) await rm(lockPath, { force: true }).catch(() => {});\n }\n}\n\nfunction normalize(raw: unknown): PluginsFile {\n const parsed = raw as PluginsFile;\n if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.plugins)) {\n // Unrecognized shape → treat as empty (a fresh registry), never throw:\n // a corrupt plugins.json must not brick every CLI command.\n return { ...EMPTY };\n }\n return parsed;\n}\n\n/** Synchronous read for the CLI's sync name-list / validation checks. Missing file → empty. */\nexport function readPluginRegistrySync(path: string = PLUGINS_FILE): PluginsFile {\n try {\n if (!existsSync(path)) return { ...EMPTY };\n return normalize(JSON.parse(readFileSync(path, 'utf8')));\n } catch {\n return { ...EMPTY };\n }\n}\n\nexport async function readPluginRegistry(path: string = PLUGINS_FILE): Promise<PluginsFile> {\n try {\n return normalize(JSON.parse(await readFile(path, 'utf8')));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { ...EMPTY };\n return { ...EMPTY };\n }\n}\n\n/**\n * Read for a read-modify-WRITE. Unlike the lenient readers (which degrade a\n * corrupt file to empty so the CLI never bricks), this REFUSES to proceed when\n * an existing file is unparseable/unrecognized — otherwise `addPluginRecord`\n * would overwrite a recoverable `plugins.json` and silently drop every other\n * registered plugin. A genuinely missing file (ENOENT) is still an empty start.\n */\nasync function readForWrite(path: string): Promise<PluginsFile> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { ...EMPTY };\n throw err;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new Error(\n `refusing to modify a corrupt plugin registry at ${path} (${(err as Error).message}) — fix or delete the file and retry.`,\n );\n }\n const p = parsed as PluginsFile;\n if (!p || p.version !== 1 || !Array.isArray(p.plugins)) {\n throw new Error(\n `refusing to modify an unrecognized plugin registry at ${path} — fix or delete the file and retry.`,\n );\n }\n return p;\n}\n\nasync function writeRegistry(file: PluginsFile, path: string = PLUGINS_FILE): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const tmp = `${path}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, JSON.stringify(file, null, 2) + '\\n', 'utf8');\n await rename(tmp, path);\n}\n\n/** Upsert a plugin by `packageName` (idempotent re-add updates the record). */\nexport async function addPluginRecord(\n record: PluginRecord,\n path: string = PLUGINS_FILE,\n): Promise<void> {\n await withFileLock(path, async () => {\n const file = await readForWrite(path);\n const next = file.plugins.filter((p) => p.packageName !== record.packageName);\n next.push(record);\n await writeRegistry({ version: 1, plugins: next }, path);\n });\n}\n\n/**\n * Remove a plugin by package name OR by a provider name it contributes.\n * Returns the removed record(s) count.\n */\nexport async function removePluginRecord(\n nameOrPackage: string,\n path: string = PLUGINS_FILE,\n): Promise<number> {\n let removed = 0;\n await withFileLock(path, async () => {\n const file = await readForWrite(path);\n const next = file.plugins.filter((p) => {\n const match = p.packageName === nameOrPackage || p.providers.includes(nameOrPackage);\n if (match) removed += 1;\n return !match;\n });\n await writeRegistry({ version: 1, plugins: next }, path);\n });\n return removed;\n}\n\n/** All provider names contributed by registered plugins (sync). */\nexport function pluginProviderNames(path: string = PLUGINS_FILE): string[] {\n return readPluginRegistrySync(path).plugins.flatMap((p) => p.providers);\n}\n\n/** The plugin record that contributes `providerName`, or null (sync). */\nexport function pluginForProvider(\n providerName: string,\n path: string = PLUGINS_FILE,\n): PluginRecord | null {\n return (\n readPluginRegistrySync(path).plugins.find((p) => p.providers.includes(providerName)) ?? null\n );\n}\n","import { mkdtemp, readFile, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, join } from 'node:path';\nimport { applyReplacements, deriveBoxHost, type ResolvedCarryEntry } from '@agentbox/core';\n\n/**\n * Box facts used to fill `{{AGENTBOX_*}}` placeholders in carried files. The\n * placeholder *names* match the in-box `agentbox-ctl render` whitelist; here the\n * values come from the create context (the box is named but not yet booted).\n */\nexport interface CarryBoxContext {\n name?: string;\n id?: string;\n kind?: string;\n /** Host workspace path (mirrors in-box AGENTBOX_HOST_WORKSPACE). */\n hostWorkspace?: string;\n projectRoot?: string;\n}\n\n/** Build the whitelist placeholder context (and derive AGENTBOX_BOX_HOST). */\nexport function carryPlaceholderContext(ctx: CarryBoxContext): Record<string, string> {\n const out: Record<string, string> = {};\n if (ctx.name) out.AGENTBOX_BOX_NAME = ctx.name;\n if (ctx.id) out.AGENTBOX_BOX_ID = ctx.id;\n if (ctx.kind) out.AGENTBOX_BOX_KIND = ctx.kind;\n if (ctx.hostWorkspace) out.AGENTBOX_HOST_WORKSPACE = ctx.hostWorkspace;\n if (ctx.projectRoot) out.AGENTBOX_PROJECT_ROOT = ctx.projectRoot;\n return deriveBoxHost(out);\n}\n\n/** Whether an entry opts into host-side rendering (file entries only). */\nfunction wantsRender(e: ResolvedCarryEntry): boolean {\n return e.kind === 'file' && (!!e.replaceEnvs || (e.replace?.length ?? 0) > 0);\n}\n\n/**\n * Render carry entries that opt into `replaceEnvs`/`replace`: read each file\n * host-side, apply the substitutions, write the result to a temp file, and\n * repoint `absSrc` at it so the existing per-provider tar/copy step transfers\n * the rendered content. Entries without replace options pass through unchanged.\n * Returns a new array (inputs are not mutated).\n */\nexport async function renderCarryEntries(\n entries: ResolvedCarryEntry[],\n ctx: CarryBoxContext,\n onLog?: (line: string) => void,\n): Promise<ResolvedCarryEntry[]> {\n if (!entries.some(wantsRender)) return entries;\n\n const context = carryPlaceholderContext(ctx);\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-carry-render-'));\n const out: ResolvedCarryEntry[] = [];\n for (const [i, entry] of entries.entries()) {\n if (!wantsRender(entry)) {\n out.push(entry);\n continue;\n }\n const content = await readFile(entry.absSrc, 'utf8');\n const rendered = applyReplacements(content, {\n env: entry.replaceEnvs,\n rules: entry.replace,\n context,\n onWarn: (msg) => onLog?.(`carry: ${entry.rawSrc}: ${msg}`),\n });\n const tmp = join(stage, `${String(i)}-${basename(entry.absSrc)}`);\n await writeFile(tmp, rendered, 'utf8');\n out.push({ ...entry, absSrc: tmp, bytes: Buffer.byteLength(rendered) });\n const what = [\n ...(entry.replaceEnvs ? ['env'] : []),\n ...(entry.replace?.length ? [`${String(entry.replace.length)} rule(s)`] : []),\n ].join('+');\n onLog?.(`carry: rendered ${entry.rawSrc} (${what})`);\n }\n return out;\n}\n","/**\n * `RecordingSyncTransport` — the parity net for the sync refactor. Every concern\n * module is a pure function of `(ctx, transport, …)`, so a concern's entire\n * observable effect IS its ordered sequence of transport calls. This fake\n * `SyncTransport` records that sequence deterministically — no host FS, no git,\n * no relay, no docker, no randomness — so a concern can be golden-snapshotted\n * and a refactor that changes what we emit fails the snapshot.\n *\n * Mirrors the `MockCloudBackend` (`@agentbox/sandbox-cloud`) pattern: a\n * reference double shipped in `src/` and driven by tests.\n */\n\nimport type {\n PushOptions,\n SyncExecOptions,\n SyncExecResult,\n SyncTransport,\n TransportCaps,\n VolumeHostSource,\n} from '@agentbox/core';\n\n/** One recorded transport call, in invocation order. */\nexport interface RecordedOp {\n op:\n | 'exec'\n | 'applyTarball'\n | 'pushTree'\n | 'pushFile'\n | 'pullTree'\n | 'pullFile'\n | 'readText'\n | 'ensureVolume'\n | 'seedVolumeFromHost';\n /** Normalized, snapshot-stable arguments for this call. */\n args: Record<string, unknown>;\n}\n\nexport interface RecordingTransportOptions {\n /** Override capability flags (default: docker-like). */\n caps?: Partial<TransportCaps>;\n /**\n * Whether the volume primitives are present. Default true (docker-like). Set\n * false to model an ephemeral cloud backend (no `ensureVolume` /\n * `seedVolumeFromHost`), so a concern that feature-detects them takes the\n * push-every-create branch.\n */\n withVolumes?: boolean;\n /** Canned `exec` result. Default `{ exitCode: 0, stdout: '', stderr: '' }`. */\n execResult?: (cmd: string[], opts?: SyncExecOptions) => SyncExecResult;\n /** Canned `readText` responses keyed by box path. Default: null (absent). */\n readText?: (boxPath: string) => string | null;\n}\n\nexport interface RecordingSyncTransport extends SyncTransport {\n /** Recorded calls in invocation order. */\n readonly ops: ReadonlyArray<RecordedOp>;\n /** Drop the recorded ops (between assertions in one test). */\n clear(): void;\n}\n\nconst DEFAULT_CAPS: TransportCaps = {\n persistentVolumes: true,\n helperContainer: true,\n ephemeralFs: false,\n};\n\nexport function makeRecordingTransport(\n opts: RecordingTransportOptions = {},\n): RecordingSyncTransport {\n const ops: RecordedOp[] = [];\n const caps: TransportCaps = { ...DEFAULT_CAPS, ...opts.caps };\n const withVolumes = opts.withVolumes ?? true;\n const push = (op: RecordedOp['op'], args: Record<string, unknown>) => ops.push({ op, args });\n\n const base: SyncTransport = {\n caps,\n async exec(cmd: string[], execOpts?: SyncExecOptions): Promise<SyncExecResult> {\n push('exec', { cmd, opts: execOpts });\n return opts.execResult?.(cmd, execOpts) ?? { exitCode: 0, stdout: '', stderr: '' };\n },\n async applyTarball(hostTarPath: string, boxDestDir: string, o?: PushOptions): Promise<void> {\n push('applyTarball', { hostTarPath, boxDestDir, opts: o });\n },\n async pushTree(hostSrcDir: string, boxDestDir: string, o?: PushOptions): Promise<void> {\n push('pushTree', { hostSrcDir, boxDestDir, opts: o });\n },\n async pushFile(hostSrcPath: string, boxDestPath: string, o?: PushOptions): Promise<void> {\n push('pushFile', { hostSrcPath, boxDestPath, opts: o });\n },\n async pullTree(boxSrcDir: string, hostDestDir: string, o?: { exclude?: string[] }): Promise<void> {\n push('pullTree', { boxSrcDir, hostDestDir, opts: o });\n },\n async pullFile(boxSrcPath: string, hostDestPath: string): Promise<void> {\n push('pullFile', { boxSrcPath, hostDestPath });\n },\n async readText(boxPath: string): Promise<string | null> {\n push('readText', { boxPath });\n return opts.readText?.(boxPath) ?? null;\n },\n };\n\n if (withVolumes) {\n base.ensureVolume = async (name: string): Promise<{ volumeId: string }> => {\n push('ensureVolume', { name });\n return { volumeId: `vol-${name}` };\n };\n base.seedVolumeFromHost = async (volume: string, sources: VolumeHostSource[]): Promise<void> => {\n push('seedVolumeFromHost', { volume, sources });\n };\n }\n\n return {\n ...base,\n get ops() {\n return ops;\n },\n clear(): void {\n ops.length = 0;\n },\n };\n}\n","/**\n * The per-tool sync registry. `AGENT_SYNC_SPECS` is the data-driven table the\n * driver and both providers iterate instead of hardcoding three per-tool blocks\n * (`sandbox-docker/create.ts:623-763`, `sandbox-cloud/cloud-provider.ts:705-819`).\n *\n * Values here are the single source of truth mirrored by the docker constants\n * (`SHARED_*_VOLUME`, `*_FORWARDED_ENV_KEYS`, `*_CREDENTIALS_BACKUP_FILE`) and\n * the cloud `AGENT_SPECS`; a cross-check test in `@agentbox/sandbox-cloud`\n * (which can see both packages) guards against drift until those constants are\n * re-exported from here.\n */\n\nimport { join } from 'node:path';\nimport { STATE_DIR } from '../state.js';\nimport type { AgentId, AgentSyncSpec } from './agents/types.js';\n\nconst CLAUDE_BOX_DIR = '/home/vscode/.claude';\nconst CODEX_BOX_DIR = '/home/vscode/.codex';\nconst OPENCODE_BOX_DIR = '/home/vscode/.local/share/opencode';\n\nexport const AGENT_SYNC_SPECS: readonly AgentSyncSpec[] = [\n {\n id: 'claude',\n aliases: ['claude-code'],\n sessionName: 'claude',\n dockerVolume: 'agentbox-claude-config',\n staticPaths: [\n {\n hostHomeRel: ['.claude'],\n boxDir: CLAUDE_BOX_DIR,\n // Static-stage excludes (single source of truth; consumed by\n // `host-stage.ts:stageClaudeStaticForUpload`). `node_modules` drops\n // host-platform binaries; `.credentials.json` ships separately; the\n // rest is per-machine runtime/history state the in-box claude\n // regenerates (`workflows` is seeded per-box at create time, not baked).\n exclude: [\n 'node_modules',\n '.credentials.json',\n 'projects',\n 'workflows',\n 'sessions',\n 'history.jsonl',\n 'file-history',\n 'shell-snapshots',\n 'backups',\n 'session-env',\n 'paste-cache',\n 'cache',\n 'telemetry',\n 'tasks',\n 'downloads',\n 'chrome',\n 'ide',\n 'debug',\n 'mcp-needs-auth-cache.json',\n 'stats-cache.json',\n ],\n },\n ],\n credential: {\n boxRelPath: '.credentials.json',\n boxAbsPath: `${CLAUDE_BOX_DIR}/.credentials.json`,\n hostBackup: join(STATE_DIR, 'claude-credentials.json'),\n cloudMountPath: '/home/vscode/.agentbox-creds/claude',\n cloudSubpath: 'claude/',\n realShape: 'claude-oauth',\n },\n forwardedEnvKeys: [\n 'ANTHROPIC_API_KEY',\n 'CLAUDE_CODE_OAUTH_TOKEN',\n 'CLAUDE_EFFORT',\n 'ANTHROPIC_MODEL',\n ],\n boxRunEnv: () => ({}),\n caps: { resume: true, teleport: 'full', activitySource: 'scraper' },\n },\n {\n id: 'codex',\n aliases: [],\n sessionName: 'codex',\n dockerVolume: 'agentbox-codex-config',\n staticPaths: [\n {\n hostHomeRel: ['.codex'],\n boxDir: CODEX_BOX_DIR,\n // Static-stage excludes (single source of truth; consumed by\n // `host-stage.ts:stageCodexStaticForUpload`). `auth.json` ships\n // separately; `state_*.sqlite*` is the resume-cwd index (rebuilt in-box);\n // `packages`/`plugins/.plugin-appserver`/`computer-use` are heavy\n // macOS-only artifacts; the rest is host-only session/log/cache state.\n exclude: [\n 'auth.json',\n 'sessions',\n 'log',\n 'history.jsonl',\n 'hooks.json',\n 'state_*.sqlite*',\n 'logs_*.sqlite*',\n 'external_agent_session_imports.json',\n 'sqlite',\n 'cache',\n 'vendor_imports',\n 'tmp',\n '.tmp',\n '.codex-global-state.json',\n '.codex-global-state.json.bak',\n '.personality_migration',\n 'shell_snapshots',\n 'session_index.jsonl',\n 'models_cache.json',\n 'installation_id',\n 'version.json',\n 'packages',\n 'plugins/.plugin-appserver',\n 'computer-use',\n 'archived_sessions',\n ],\n },\n ],\n credential: {\n boxRelPath: 'auth.json',\n boxAbsPath: `${CODEX_BOX_DIR}/auth.json`,\n hostBackup: join(STATE_DIR, 'codex-credentials.json'),\n cloudMountPath: '/home/vscode/.agentbox-creds/codex',\n cloudSubpath: 'codex/',\n realShape: 'nonempty-json',\n },\n forwardedEnvKeys: ['OPENAI_API_KEY'],\n boxRunEnv: () => ({}),\n caps: { resume: true, teleport: 'full', activitySource: 'scraper' },\n },\n {\n id: 'opencode',\n aliases: [],\n sessionName: 'opencode',\n dockerVolume: 'agentbox-opencode-config',\n // The three-XDG-dir layout as DATA: the generic seed loop reproduces\n // `ensureOpencodeVolume`'s three-source rsync (data + config→config +\n // state→.state/opencode newest-wins) with no tool-specific control flow.\n staticPaths: [\n {\n hostHomeRel: ['.local', 'share', 'opencode'],\n boxDir: OPENCODE_BOX_DIR,\n // Static-stage excludes for the data tree (single source of truth;\n // consumed by `host-stage.ts:stageOpencodeStaticForUpload`). `auth.json`\n // ships separately; the rest is host-only runtime state.\n exclude: [\n 'auth.json',\n 'storage',\n 'log',\n 'project',\n 'cache',\n 'bin',\n 'repos',\n 'snapshot',\n 'config',\n 'opencode.db',\n 'opencode.db-shm',\n 'opencode.db-wal',\n ],\n },\n { hostHomeRel: ['.config', 'opencode'], boxDir: OPENCODE_BOX_DIR, relocToSubpath: 'config' },\n {\n hostHomeRel: ['.local', 'state', 'opencode'],\n boxDir: OPENCODE_BOX_DIR,\n relocToSubpath: '.state/opencode',\n update: true,\n exclude: ['locks'],\n },\n ],\n credential: {\n boxRelPath: 'auth.json',\n boxAbsPath: `${OPENCODE_BOX_DIR}/auth.json`,\n hostBackup: join(STATE_DIR, 'opencode-credentials.json'),\n cloudMountPath: '/home/vscode/.agentbox-creds/opencode',\n cloudSubpath: 'opencode/',\n realShape: 'nonempty-json',\n },\n forwardedEnvKeys: [\n 'ANTHROPIC_API_KEY',\n 'OPENAI_API_KEY',\n 'OPENROUTER_API_KEY',\n 'GEMINI_API_KEY',\n 'GOOGLE_GENERATIVE_AI_API_KEY',\n 'GOOGLE_API_KEY',\n 'GROQ_API_KEY',\n ],\n boxRunEnv: () => ({\n OPENCODE_CONFIG_DIR: `${OPENCODE_BOX_DIR}/config`,\n XDG_STATE_HOME: `${OPENCODE_BOX_DIR}/.state`,\n }),\n caps: { resume: false, teleport: 'stub', activitySource: 'plugin' },\n },\n];\n\n/** Resolve a spec by canonical id or any alias (e.g. `'claude-code'` → the claude spec). */\nexport function resolveAgentSpec(name: string): AgentSyncSpec {\n const spec = AGENT_SYNC_SPECS.find((s) => s.id === name || s.aliases.includes(name));\n if (!spec) throw new Error(`no agent sync spec for '${name}'`);\n return spec;\n}\n\n/** The canonical ids, in registry order. */\nexport function agentIds(): AgentId[] {\n return AGENT_SYNC_SPECS.map((s) => s.id);\n}\n","/**\n * `SyncContext` — the runtime values a concern needs that aren't the transport\n * or its per-call plan. Assembled once by the provider (docker/cloud) at create\n * or session-start and threaded through every concern, so concern signatures\n * stay `(ctx, transport, plan?)`.\n *\n * The interface itself is a Tier-1 contract that lives in `@agentbox/core` (so\n * the `ProviderSync` facade there can also name it); it's re-exported here so\n * existing `@agentbox/sandbox-core` importers are unchanged. The builder\n * `makeSyncContext` stays here — it defaults `hostHome` to the OS home dir.\n */\n\nimport { homedir } from 'node:os';\nimport type { SyncContext } from '@agentbox/core';\n\nexport type { SyncContext } from '@agentbox/core';\n\nexport interface SyncContextInit {\n boxName: string;\n boxId: string;\n provider: 'docker' | 'cloud';\n hostWorkspace: string;\n projectRoot?: string;\n boxWorkspace?: string;\n hostHome?: string;\n onLog?: (line: string) => void;\n}\n\n/** Build a `SyncContext` with the conventional defaults filled in. */\nexport function makeSyncContext(init: SyncContextInit): SyncContext {\n return {\n boxName: init.boxName,\n boxId: init.boxId,\n provider: init.provider,\n hostWorkspace: init.hostWorkspace,\n projectRoot: init.projectRoot ?? init.hostWorkspace,\n boxWorkspace: init.boxWorkspace ?? '/workspace',\n hostHome: init.hostHome ?? homedir(),\n onLog: init.onLog ?? (() => {}),\n };\n}\n","/**\n * Concern: env/config files (`.env`, `secrets.toml`, `agentbox.yaml`, …) copied\n * host→box into `/workspace` at create, gitignore-bypassing.\n *\n * Unifies docker `copyHostEnvFilesToBox` (`sandbox-docker/host-export.ts`) and\n * cloud `uploadEnvFiles` (`sandbox-cloud/env-files.ts`): the host-side `find` +\n * `tar --null -T -` pack is identical across providers and lives here; the only\n * difference — how the tarball is extracted into the box — is the transport's\n * `applyTarball`. Both providers now delegate here, injecting their transport.\n *\n * Best-effort: a scan/pack failure or empty match set logs and returns the count\n * rather than throwing — a missing optional secret must not abort a healthy box.\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 { SyncTransport } from '@agentbox/core';\nimport type { SyncContext } from '../context.js';\n\n/**\n * Default env/config file basename globs. These are almost always gitignored,\n * so a normal gitignore-aware pull skips them; this list opts them back in.\n * `agentbox.yaml` is included so an in-box `/agentbox-setup`-generated file\n * lands on the host even before it's committed.\n */\nexport const DEFAULT_ENV_PATTERNS = [\n '.env',\n '.env.*',\n '.envrc',\n '.dev.vars',\n 'secrets.toml',\n 'local.settings.json',\n 'appsettings.*.json',\n 'agentbox.yaml',\n];\n\n/** Directories the env-file `find` prunes — heavy or never-relevant. */\nexport const ENV_PRUNE_DIRS = [\n 'node_modules',\n '.git',\n '.venv',\n 'venv',\n '__pycache__',\n 'dist',\n '.next',\n 'build',\n];\n\nfunction nameGroup(names: string[]): string[] {\n const out: string[] = [];\n names.forEach((n, i) => {\n if (i > 0) out.push('-o');\n out.push('-name', n);\n });\n return out;\n}\n\n/**\n * Host-side `find` argv enumerating env/config files by basename glob, pruning\n * `ENV_PRUNE_DIRS`. Rooted at `.` (run with cwd = the host workspace) with\n * `-print0` (BSD `find` on macOS has no `-printf`); `./relpath` entries feed\n * `tar -C <workspace> --null -T -` directly.\n */\nexport function buildHostEnvFindArgs(patterns: string[]): string[] {\n return [\n 'find',\n '.',\n '(',\n '-type',\n 'd',\n '(',\n ...nameGroup(ENV_PRUNE_DIRS),\n ')',\n '-prune',\n ')',\n '-o',\n '(',\n '-type',\n 'f',\n '(',\n ...nameGroup(patterns),\n ')',\n '-print0',\n ')',\n ];\n}\n\n/**\n * Raw `find` output relative to `workspaceDir` — `./relpath` entries, NUL-split,\n * NO `./` stripping. This is what feeds `tar -C <workspaceDir> --null -T -`\n * (which handles `./relpath` directly), so `pushEnvFiles` uses it verbatim to\n * stay byte-identical to the pre-refactor copy. Empty on a scan failure or empty\n * pattern set (best-effort).\n */\nasync function findEnvFilesForTar(workspaceDir: string, patterns: string[]): Promise<string[]> {\n if (patterns.length === 0) return [];\n const found = await execa('find', buildHostEnvFindArgs(patterns).slice(1), {\n cwd: workspaceDir,\n reject: false,\n });\n if (found.exitCode !== 0) return [];\n return String(found.stdout)\n .split('\\0')\n .filter((p) => p.length > 0);\n}\n\n/**\n * Run `buildHostEnvFindArgs` against `workspaceDir` and return the matched\n * relative paths with the leading `./` stripped — the display/preview form used\n * by the setup wizard's multiselect. Pure host-side helper (no box mutation).\n * Empty on a scan failure or empty pattern set (best-effort).\n */\nexport async function scanHostEnvFiles(workspaceDir: string, patterns: string[]): Promise<string[]> {\n const raw = await findEnvFilesForTar(workspaceDir, patterns);\n return raw.map((p) => p.replace(/^\\.\\//, '')).filter((p) => p.length > 0);\n}\n\nexport interface PushEnvFilesResult {\n /** Number of files written into the box. 0 when nothing matched. */\n copied: number;\n}\n\n/**\n * Copy the host's env/config files (selected by `patterns`) into the box's\n * `/workspace`, gitignore-bypassing. Files land owned by uid 1000 (`vscode`).\n */\nexport async function pushEnvFiles(\n ctx: SyncContext,\n transport: SyncTransport,\n patterns: string[],\n): Promise<PushEnvFilesResult> {\n const list = await findEnvFilesForTar(ctx.hostWorkspace, patterns);\n if (list.length === 0) return { copied: 0 };\n\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-envfiles-'));\n const localTar = join(stage, 'envfiles.tar');\n try {\n const packed = await execa(\n 'tar',\n ['-C', ctx.hostWorkspace, '--null', '-T', '-', '-cf', localTar],\n { input: list.join('\\0'), reject: false },\n );\n if (packed.exitCode !== 0) {\n ctx.onLog(`warning: env-file tar pack failed: ${String(packed.stderr).slice(0, 300)}`);\n return { copied: 0 };\n }\n try {\n await transport.applyTarball(localTar, ctx.boxWorkspace, { uid: 1000 });\n } catch (err) {\n ctx.onLog(\n `warning: env-file copy into box failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n return { copied: 0 };\n }\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n return { copied: list.length };\n}\n","/**\n * Concern: files (`carry:` block from `agentbox.yaml`) copied host→box to\n * declared destinations that may live anywhere in the box (not constrained to\n * /workspace).\n *\n * carry is the most provider-divergent concern, so this module deliberately\n * unifies only the *decision* logic — the pure `planCarryEntry` below — and\n * leaves each provider's *apply* mechanism byte-identical:\n * - docker `copyOneEntry` (`sandbox-docker/host-export.ts`): `streamTarPipe`\n * (stdin, no temp file) + separate `docker exec --user 0:0` calls.\n * - cloud `uploadOneEntry` (`sandbox-cloud/carry.ts`): a staged temp tar +\n * `uploadFile` + ONE combined bash command (splitting/nesting it reintroduces\n * a Vercel `$(...)`/`while` hang — see the note in that file).\n *\n * Both apply paths share the same up-front decisions (`~/`→`/home/vscode`\n * expansion, file-vs-dir, exclude, uid/mode defaults, rename-needed,\n * parent-chain-needed). Those live here so the two providers can't drift.\n */\n\nimport type { ResolvedCarryEntry } from '@agentbox/core';\n\n/** Hardcoded in-box home — boxes always run as the `vscode` user (uid 1000). */\nexport const BOX_HOME = '/home/vscode';\n\n/** dirname() that always uses '/' regardless of host OS (the box is linux). */\nexport function dirnameUnix(p: string): string {\n const i = p.lastIndexOf('/');\n if (i <= 0) return '/';\n return p.slice(0, i);\n}\n\n/** basename() that always uses '/' regardless of host OS (the box is linux). */\nexport function basenameUnix(p: string): string {\n const i = p.lastIndexOf('/');\n return i < 0 ? p : p.slice(i + 1);\n}\n\n/**\n * The shared, byte-for-byte carry decisions both providers apply. Everything\n * here is a pure function of the entry; nothing touches the host FS or the box.\n */\nexport interface CarryPlan {\n /** `absDest` with `~/` expanded to `/home/vscode` (host-side, never in-box). */\n boxDest: string;\n /** True for a `dir` entry, false for a `file` entry. */\n isDir: boolean;\n /**\n * Dir to `mkdir -p` before extracting: the dest itself for a dir, the dest's\n * parent for a file. Trailing slashes on the dest are stripped first.\n */\n parentDir: string;\n /** tar `--exclude` patterns (dir entries only; empty for files). */\n exclude: string[];\n /** chown target uid:uid inside the box. Default 1000 (`vscode`); 0 = root. */\n uid: number;\n /** Zero-padded octal `chmod -R` arg, or undefined when no mode is set. */\n mode?: string;\n /** Source basename inside the packed tar (file entries only; '' for dirs). */\n fileBase: string;\n /** Dest basename (file entries only; '' for dirs). */\n destBase: string;\n /** File dest basename differs from the source → `mv` after extract. */\n renameNeeded: boolean;\n /**\n * Dest is under `$HOME` with a non-`$HOME` immediate parent, so the\n * root-created parent chain must be chowned back to `uid`. System paths\n * (`/etc/*`, …) are left untouched.\n */\n parentChainNeeded: boolean;\n}\n\n/**\n * Compute the shared carry decisions for one entry. Returns `null` for a\n * `missing` (optional + absent-on-host) entry, which both providers skip.\n */\nexport function planCarryEntry(entry: ResolvedCarryEntry): CarryPlan | null {\n if (entry.kind === 'missing') return null;\n\n // ~/ expands to /home/vscode at this layer (host-side), NOT inside the box's\n // shell — so we never depend on the executing user's $HOME (which is /root\n // when the docker path runs `--user 0:0`).\n const boxDest = entry.absDest.startsWith('~/')\n ? `${BOX_HOME}/${entry.absDest.slice(2)}`\n : entry.absDest;\n const boxDestNoSlash = boxDest.endsWith('/') ? boxDest.slice(0, -1) : boxDest;\n\n const isDir = entry.kind === 'dir';\n const parentDir = isDir ? boxDestNoSlash : dirnameUnix(boxDestNoSlash);\n const exclude = isDir ? (entry.exclude ?? []) : [];\n // Default uid 1000 (in-box vscode); explicit `user: 0` lands root:root.\n const uid = entry.user ?? 1000;\n const mode = entry.mode !== undefined ? entry.mode.toString(8).padStart(4, '0') : undefined;\n\n const fileBase = isDir ? '' : basenameUnix(entry.absSrc);\n const destBase = isDir ? '' : basenameUnix(boxDest);\n const renameNeeded = !isDir && fileBase !== destBase;\n\n // `mkdir -p` runs as root, so any new dirs between $HOME and dirname(dest) are\n // root-owned. Only walk when the dest is under $HOME — system paths keep their\n // existing ownership.\n const parentChainNeeded =\n boxDest.startsWith(`${BOX_HOME}/`) && dirnameUnix(boxDest) !== BOX_HOME;\n\n return {\n boxDest,\n isDir,\n parentDir,\n exclude,\n uid,\n mode,\n fileBase,\n destBase,\n renameNeeded,\n parentChainNeeded,\n };\n}\n","/**\n * Claude-specific host/box path helpers, shared by every provider's sync layer.\n *\n * Moved here (from `@agentbox/sandbox-docker`'s `host-stage.ts`) so the cloud\n * dynamic-sync path can reuse them without importing the docker package — the\n * dependency leak the sync refactor closes. `host-stage.ts` re-exports these for\n * its existing importers, so nothing else moves.\n */\n\nimport { readdir, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Claude Code keys per-project state (memory, sessions, history) under\n * `~/.claude/projects/<encoded>/`, where `<encoded>` is the project's absolute\n * path with every non-alphanumeric char replaced by `-`. Inside every box the\n * workspace is `/workspace`, so its key is always `-workspace`. We duplicate\n * the rule here (rather than importing apps/cli's `encodeClaudeProjectsDir`)\n * because the sync layer must not depend on the CLI package.\n */\nexport function encodeClaudeProjectsKey(absPath: string): string {\n return absPath.replace(/[^a-zA-Z0-9]/g, '-');\n}\n\n/** In-box Claude project dir for `/workspace` (fixed for every box). */\nexport const BOX_CLAUDE_PROJECT_DIR = '/home/vscode/.claude/projects/-workspace';\n\n/**\n * Resolve the host's `~/.claude/projects/<encode(hostWorkspace)>/memory` dir,\n * or `null` when it's absent or empty (so callers no-op rather than seed an\n * empty tree). `hostHome` is overridable for tests.\n */\nexport async function resolveClaudeMemoryDir(\n hostWorkspace: string,\n hostHome: string = homedir(),\n): Promise<string | null> {\n if (hostWorkspace.length === 0) return null;\n const memDir = join(\n hostHome,\n '.claude',\n 'projects',\n encodeClaudeProjectsKey(hostWorkspace),\n 'memory',\n );\n if (!(await pathExists(memDir))) return null;\n try {\n const entries = await readdir(memDir);\n if (entries.length === 0) return null;\n } catch {\n return null;\n }\n return memDir;\n}\n","/**\n * Host-side symlink pre-scan shared by the skills/agents-volume seed and the\n * claude static stage. Pure filesystem inspection (no docker, no box), so it\n * lives in the sync layer and both providers reuse it. Moved here from\n * `@agentbox/sandbox-docker`'s `claude.ts`, which re-exports it for its existing\n * importers.\n */\n\nimport { readdir, realpath, stat } from 'node:fs/promises';\nimport { isAbsolute, join, relative } from 'node:path';\n\nfunction isUnder(parent: string, child: string): boolean {\n const rel = relative(parent, child);\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));\n}\n\n/**\n * Walk `root` and return rsync-style relative paths of every symlink the\n * in-container sync can't dereference, so we can `--exclude` them. Two cases\n * abort the whole sync under `--copy-unsafe-links` if left in:\n *\n * - Broken on the host (e.g. claude's `debug/latest` once an older debug file\n * is reaped).\n * - Valid on the host but pointing OUTSIDE the trees the helper container\n * mounts (`reachableRoots`: `~/.claude` itself and, when present, `~/.agents`\n * at `/.agents`). The referent then has \"no referent\" inside the box — e.g. a\n * dev's `~/.claude/skills/*` symlinked into an agentbox source checkout.\n *\n * A symlinked directory whose target IS reachable can still hide an unsyncable\n * link one level down: `~/.claude/skills/<name>` -> `~/.agents/skills/<name>`\n * (reachable) whose `SKILL.md` is an ABSOLUTE link into a repo checkout (not\n * mounted). rsync's `--copy-unsafe-links` dereferences the reachable dir link\n * and descends into it, then aborts on the nested absolute link. So when a\n * symlink resolves into a reachable tree we recurse into the resolved target,\n * reporting nested findings under the symlink's path as rsync transfers it\n * (the link name in `root`, not the resolved `~/.agents` path). An ancestry\n * guard (`onPath`) blocks symlink cycles without suppressing the same resolved\n * dir reached under a *different* virtual prefix — e.g. two skills symlinked to\n * one shared target must each report their nested unsyncable link, or rsync\n * still aborts on the prefix we skipped.\n */\nexport async function findUnsyncableSymlinks(\n root: string,\n reachableRoots: string[],\n): Promise<string[]> {\n // realpath the reachable roots so a symlinked ancestor (e.g. macOS\n // /var -> /private/var) doesn't make a containment check spuriously fail.\n const reachable = await Promise.all(\n reachableRoots.map(async (r) => {\n try {\n return await realpath(r);\n } catch {\n return r;\n }\n }),\n );\n const unsyncable: string[] = [];\n // Resolved dirs currently on the recursion path. Guards against symlink\n // cycles (a link pointing at an ancestor) while still allowing the same dir\n // to be re-walked under a different virtual prefix once this branch unwinds.\n const onPath = new Set<string>();\n // `realDir` is the filesystem directory to read; `virtualDir` is its path as\n // rsync sees it under `root` (they diverge once we follow a symlinked dir).\n async function walk(realDir: string, virtualDir: string): Promise<void> {\n if (onPath.has(realDir)) return;\n onPath.add(realDir);\n try {\n let entries;\n try {\n entries = await readdir(realDir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const ent of entries) {\n const realFull = join(realDir, ent.name);\n const virtualFull = virtualDir ? join(virtualDir, ent.name) : ent.name;\n if (ent.isSymbolicLink()) {\n let real: string;\n try {\n real = await realpath(realFull);\n } catch {\n unsyncable.push(virtualFull); // broken on the host\n continue;\n }\n if (!reachable.some((r) => isUnder(r, real))) {\n unsyncable.push(virtualFull); // target not mounted in the box\n continue;\n }\n // Reachable target: rsync will dereference + descend, so check inside\n // it too for nested unsyncable links, keyed to the symlink's path.\n const st = await stat(real).catch(() => null);\n if (st?.isDirectory()) await walk(real, virtualFull);\n } else if (ent.isDirectory()) {\n await walk(realFull, virtualFull);\n }\n }\n } finally {\n onPath.delete(realDir);\n }\n }\n await walk(root, '');\n return unsyncable;\n}\n","/**\n * Concern: skills — the shared `~/.agents` tree (`~/.agents/skills/<name>`, the\n * cross-agent Agent Skills location) seeded host→box so the in-box agents see\n * the same skill set the host does.\n *\n * On docker this is a persistent shared volume seeded from the host via the\n * transport's `seedVolumeFromHost` (a throwaway rsync helper container). Cloud\n * has no helper container (`caps.helperContainer === false`) — its static config\n * is baked into the prepare-time snapshot via `stageAgentsStaticForUpload` — so\n * cloud never calls this.\n *\n * The host is authoritative and the sync is additive (no `--delete`). Skills\n * routinely symlink files into checkouts, so the seed dereferences reachable\n * links (`copyUnsafeLinks`) and excludes the ones the box can't resolve (broken\n * on the host or pointing outside the mounted tree — see `findUnsyncableSymlinks`),\n * or rsync aborts with \"symlink has no referent\".\n */\n\nimport { stat } from 'node:fs/promises';\nimport type { SyncTransport } from '@agentbox/core';\nimport { findUnsyncableSymlinks } from '../host-links.js';\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface SeedAgentsVolumeArgs {\n /** Transport bound to the box's provider. Must expose `seedVolumeFromHost`. */\n transport: SyncTransport;\n /** The shared agents-config volume name (already ensured to exist). */\n volume: string;\n /** Host `~/.agents` dir. */\n hostAgents: string;\n /**\n * Sync host → volume when true AND the host `~/.agents` exists. When false or\n * absent, the volume is only made writable by the in-box `vscode` user.\n */\n syncFromHost: boolean;\n onLog?: (line: string) => void;\n}\n\nexport interface SeedAgentsVolumeResult {\n /** True when the rsync helper ran (syncFromHost was true AND host had `~/.agents`). */\n synced: boolean;\n}\n\n/**\n * Seed (or make writable) the shared `~/.agents` volume via the transport's\n * persistent-volume seam. The caller owns volume creation + `created`\n * detection; this owns the host→volume sync decision so both providers (only\n * docker today) share it.\n */\nexport async function seedAgentsVolume(args: SeedAgentsVolumeArgs): Promise<SeedAgentsVolumeResult> {\n const seed = args.transport.seedVolumeFromHost;\n if (!seed) throw new Error('seedAgentsVolume requires a transport with seedVolumeFromHost');\n\n const willSync = args.syncFromHost && (await pathExists(args.hostAgents));\n if (!willSync) {\n // No host ~/.agents to sync — an empty source set still makes the (possibly\n // freshly created, root-owned) volume root writable by the in-box vscode\n // user. Best-effort: a failed chown must not abort box creation (the sync\n // path below, by contrast, propagates — a botched skills sync is worth\n // surfacing).\n try {\n await seed.call(args.transport, args.volume, []);\n } catch (err) {\n args.onLog?.(\n `skills: volume writable-chown failed (ignored): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return { synced: false };\n }\n\n // `--copy-unsafe-links` dereferences a skill's symlinks pointing outside\n // ~/.agents into real files; the ones it can't resolve (broken / out-of-tree)\n // are excluded so the sync doesn't abort with \"symlink has no referent\".\n const excludes = (await findUnsyncableSymlinks(args.hostAgents, [args.hostAgents])).map(\n (rel) => `/${rel}`,\n );\n await seed.call(args.transport, args.volume, [\n { hostDir: args.hostAgents, destSubpath: '', exclude: excludes, copyUnsafeLinks: true },\n ]);\n if (excludes.length > 0) {\n args.onLog?.(`skills: excluded ${String(excludes.length)} unsyncable symlink(s) from ~/.agents`);\n }\n return { synced: true };\n}\n","/**\n * Concern: credentials — the per-agent login secrets (`~/.claude/.credentials.json`\n * for claude, `auth.json` for codex/opencode) that ride separately from static\n * config because they change per login and must never be baked into a shared\n * snapshot.\n *\n * What lives here is the provider-neutral core of the concern:\n * - the pure host-side guards (`isRealAgentCredential`, `hostClaudeBackupExpired`,\n * `hostBackupHasCredentials`) — the \"is this blob real / expired?\" decisions,\n * driven by the registry's `credential.realShape` so the per-agent switch has\n * one home;\n * - the box→host extract (`extractCredentials`) expressed against the\n * `SyncTransport.readText` seam, so cloud's `extractCloudAgentCredentials`\n * becomes a thin transport-injecting wrapper;\n * - the seed-once marker name (`SEED_MARKER`) shared by the cloud volume seed.\n *\n * What deliberately does NOT live here (yet): the *seed* mechanisms. Docker\n * seeds claude via a throwaway root helper container that bidirectionally syncs\n * the shared config volume with the host backup (`syncClaudeCredentials`,\n * `SYNC_SCRIPT`) — it predates any running box, so it has no `SyncTransport`\n * (box-bound) analog and no polymorphic caller; codex/opencode ride the whole-\n * dir volume rsync. Cloud seeds via `seedCredentialsOne` (marker/force gate +\n * `uploadFile` + a volume-vs-ephemeral extract split). Those stay in their\n * providers; their transport-seam collapse folds into the Phase 7 driver, the\n * same call carry's apply mechanism and skills' box→host pull already made.\n */\n\nimport { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport type { SyncTransport } from '@agentbox/core';\nimport { AGENT_SYNC_SPECS, resolveAgentSpec } from '../registry.js';\nimport type { AgentId } from '../agents/types.js';\n\n/** Agents whose credentials we extract from a box back to the host. Mirrors `AgentId`. */\nexport type CredentialAgentKind = AgentId;\n\n/**\n * Marker filename written inside a cloud agent's credentials subpath recording\n * when we last seeded it (a single ISO-8601 timestamp on disk). Absent marker =\n * first time on this volume → seed. Volume/idempotency-only: ephemeral cloud\n * backends can't persist it and push every create; docker uses a content check\n * (real-vs-empty) instead of a marker.\n */\nexport const SEED_MARKER = '.agentbox-seeded-at';\n\n/** Host backup of the claude OAuth blob — the registry is the single source of truth. */\nconst CLAUDE_HOST_BACKUP = resolveAgentSpec('claude').credential.hostBackup;\n\n/**\n * True iff `text` looks like a real (usable) credential for `agent`, not an\n * empty/placeholder file. Used so the box→host extract never clobbers a good\n * host backup with an empty box file. The per-agent shape comes from the\n * registry (`credential.realShape`): claude requires a non-empty\n * `claudeAiOauth.refreshToken`; codex/opencode auth files just have to parse as\n * a non-empty JSON object. Unknown agents fall back to the JSON-object check\n * (never throws — matches the pre-registry `if (agent === 'claude')` switch).\n */\nexport function isRealAgentCredential(agent: CredentialAgentKind, text: string): boolean {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return false;\n }\n if (typeof parsed !== 'object' || parsed === null) return false;\n const spec = AGENT_SYNC_SPECS.find((s) => s.id === agent);\n if (spec?.credential.realShape === 'claude-oauth') {\n const rt = (parsed as { claudeAiOauth?: { refreshToken?: unknown } }).claudeAiOauth?.refreshToken;\n return typeof rt === 'string' && rt.length > 0;\n }\n return Object.keys(parsed as Record<string, unknown>).length > 0;\n}\n\n/**\n * True iff the claude host backup holds an OAuth blob whose access token is\n * already expired (`claudeAiOauth.expiresAt`, ms epoch, < now). A missing\n * `expiresAt` (or unreadable file) → false: we only report a *known* expiry, so\n * callers don't nag when the box could still refresh the token itself. `now` is\n * injectable for tests. Claude is the only agent with a token-expiry gate (codex\n * / opencode auth files carry no comparable field).\n */\nexport async function hostClaudeBackupExpired(\n path: string = CLAUDE_HOST_BACKUP,\n now: number = Date.now(),\n): Promise<boolean> {\n try {\n const parsed = JSON.parse(await readFile(path, 'utf8')) as {\n claudeAiOauth?: { expiresAt?: unknown };\n };\n const exp = parsed?.claudeAiOauth?.expiresAt;\n return typeof exp === 'number' && Number.isFinite(exp) && exp < now;\n } catch {\n return false;\n }\n}\n\n/**\n * True iff the claude host backup file holds a real OAuth blob (a non-empty\n * `claudeAiOauth.refreshToken`). Used to decide whether to offer an interactive\n * sign-in before creating a box. Tolerant of a missing or garbage file — returns\n * false.\n */\nexport async function hostBackupHasCredentials(\n path: string = CLAUDE_HOST_BACKUP,\n): Promise<boolean> {\n try {\n const parsed = JSON.parse(await readFile(path, 'utf8')) as {\n claudeAiOauth?: { refreshToken?: unknown };\n };\n const rt = parsed?.claudeAiOauth?.refreshToken;\n return typeof rt === 'string' && rt.length > 0;\n } catch {\n return false;\n }\n}\n\nexport interface ExtractCredentialsOptions {\n onLog?: (line: string) => void;\n /** Override host backup paths per agent (tests). Defaults to the registry `hostBackup`. */\n backups?: Partial<Record<AgentId, string>>;\n}\n\n/**\n * Extract each agent's login credential from a running box back to the host\n * backups under `~/.agentbox/`, so the next box (seeded from those backups)\n * inherits the login. The provider-neutral core of docker's\n * `syncClaudeCredentials` extract direction and cloud's\n * `extractCloudAgentCredentials`, expressed against `transport.readText`.\n *\n * Reads the canonical in-box path (`credential.boxAbsPath`) via\n * `transport.readText`; only writes the host backup (mode 0600) when the content\n * passes `isRealAgentCredential`, so an empty / not-logged-in box never clobbers\n * a good backup. Best-effort per agent (never throws). Returns the agents whose\n * backup was updated.\n */\nexport async function extractCredentials(\n transport: SyncTransport,\n opts: ExtractCredentialsOptions = {},\n): Promise<AgentId[]> {\n const log = opts.onLog ?? (() => {});\n const extracted: AgentId[] = [];\n for (const spec of AGENT_SYNC_SPECS) {\n const hostBackup = opts.backups?.[spec.id] ?? spec.credential.hostBackup;\n try {\n // `readText` is `cat <path> 2>/dev/null` with noRetry → null on a missing\n // file; tolerate that silently. `!text` also covers an empty stdout.\n const text = await transport.readText(spec.credential.boxAbsPath);\n if (!text || !isRealAgentCredential(spec.id, text)) continue;\n await mkdir(dirname(hostBackup), { recursive: true });\n await writeFile(hostBackup, text, { mode: 0o600 });\n await chmod(hostBackup, 0o600).catch(() => {});\n extracted.push(spec.id);\n log(`extracted ${spec.id} login from box to ${hostBackup}`);\n } catch (err) {\n log(\n `WARN: ${spec.id} credential extract failed (${err instanceof Error ? err.message : String(err)}) — skipping`,\n );\n }\n }\n return extracted;\n}\n","/**\n * Concern: git / workspace — seed the box's per-box worktree(s) from the host at\n * create, and resync them with the host's current state on session restart\n * (box-wins on every conflict). This is the concrete `box-wins-content-hash`\n * conflict policy the reconciler contract (`@agentbox/core` `sync/reconciler.ts`)\n * anticipates as its first consumer.\n *\n * This file holds the provider-neutral *resync* half: the pure untracked-overlay\n * classifier + the `resyncWorkspace` orchestration, driven entirely through the\n * `WorkspaceResyncPorts` seam so it's a pure function of its I/O (golden-tested\n * against a scripted fake). The docker/cloud providers supply the ports. Docker\n * is the only implementation today; a cloud one closes the \"Phase 2\" gap (a\n * cloud box gets no workspace resync yet). Workspace *seed* (worktree add +\n * bind-mount replay) stays docker-specific — it has no cloud analog (cloud\n * clones) — and is not moved.\n */\n\nimport { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type {\n RepoResyncResult,\n ResyncWorktree,\n WorkspaceResyncPorts,\n} from '@agentbox/core';\n\n/**\n * Sentinel token the box-side probe emits for a path that exists but is NOT a\n * plain file (a dir or symlink) — always a conflict so we never clobber it.\n */\nexport const NON_REGULAR_TOKEN = '-';\n\n/**\n * Classify a host untracked file against what the box already has at that path.\n * `boxToken` is the box-side probe result: `undefined` when the path is absent\n * in the box (safe to copy), {@link NON_REGULAR_TOKEN} when it exists but isn't\n * a plain file, otherwise the sha256 of the box file's contents. `hostHash` is\n * the sha256 of the host file. A byte-identical file is a no-op (neither copied\n * nor reported); anything else that already exists is a conflict the box keeps\n * (box wins — the host change is shadowed, no marker left).\n */\nexport function classifyUntrackedOverlay(\n boxToken: string | undefined,\n hostHash: string,\n): 'copy' | 'identical' | 'conflict' {\n if (boxToken === undefined) return 'copy';\n if (boxToken === NON_REGULAR_TOKEN) return 'conflict';\n return boxToken === hostHash ? 'identical' : 'conflict';\n}\n\n/** Split a `-z` (NUL-delimited) git output into non-empty entries. */\nfunction splitNul(s: string): string[] {\n return s.split('\\0').filter((p) => p.length > 0);\n}\n\n/** Conflicted (unmerged) paths in the box worktree, if any. */\nasync function unmergedPaths(ports: WorkspaceResyncPorts, ct: string): Promise<string[]> {\n const r = await ports.boxGit(ct, ['diff', '--name-only', '--diff-filter=U', '-z']);\n return r.exitCode === 0 ? splitNul(r.stdout) : [];\n}\n\n/**\n * Resync each box worktree with the host's current state: merge the host's\n * checked-out branch into the box's per-box branch, then overlay the host's\n * uncommitted (stash) + untracked changes. The box wins every conflict — the\n * host change is skipped (no markers left) and the affected paths are returned\n * so the caller can warn the agent.\n *\n * Provider-neutral: all I/O goes through {@link WorkspaceResyncPorts}. On docker\n * the host `.git/` is bind-mounted so the host branch ref is already present in\n * the box and the merge needs no fetch (the same property create-time carry-over\n * relies on). Best-effort throughout — a step that fails is logged and skipped\n * rather than aborting the box start.\n */\nexport async function resyncWorkspace(\n worktrees: ResyncWorktree[],\n ports: WorkspaceResyncPorts,\n onLog?: (line: string) => void,\n): Promise<RepoResyncResult[]> {\n const log = onLog ?? (() => {});\n const results: RepoResyncResult[] = [];\n\n for (const w of worktrees) {\n const ct = w.containerPath;\n const hostMain = w.hostMainRepo;\n const boxBranch = w.branch;\n const res: RepoResyncResult = { containerPath: ct, mergeConflicts: [], overlaySkipped: [] };\n\n // --- host state (host-side git; no side effects on the worktree) ---\n const hostRef = await ports.resolveHostRef(hostMain);\n if (!hostRef) {\n log(`resync: ${ct}: could not resolve host ref; skipping`);\n results.push(res);\n continue;\n }\n const hostStashSha = await ports.createHostStash(hostMain);\n const hostUntracked = await ports.listHostUntracked(hostMain);\n\n // --- merge host commits into the box branch (skip when merging self) ---\n if (hostRef !== boxBranch) {\n // Stash the box's own uncommitted tracked changes so the merge can run;\n // restored on top afterward (box keeps them). Untracked box files stay.\n const status = await ports.boxGit(ct, ['status', '--porcelain']);\n const boxDirty = status.stdout\n .split('\\n')\n .some((line) => line.length > 0 && !line.startsWith('??'));\n let boxStashed = false;\n if (boxDirty) {\n const push = await ports.boxGit(ct, ['stash', 'push', '-m', 'agentbox-resync']);\n boxStashed = push.exitCode === 0;\n }\n\n const newCommits = await ports.boxGit(ct, ['rev-list', '--count', `${boxBranch}..${hostRef}`]);\n const n = newCommits.exitCode === 0 ? newCommits.stdout.trim() : '?';\n const merge = await ports.boxGit(ct, ['merge', '--no-commit', hostRef]);\n const mergeInProgress =\n (await ports.boxGit(ct, ['rev-parse', '-q', '--verify', 'MERGE_HEAD'])).exitCode === 0;\n const conflicts = await unmergedPaths(ports, ct);\n if (conflicts.length > 0) {\n await ports.boxGit(ct, ['checkout', '--ours', '--', ...conflicts]);\n await ports.boxGit(ct, ['add', '--', ...conflicts]);\n res.mergeConflicts.push(...conflicts);\n }\n if (mergeInProgress) {\n await ports.boxGit(ct, [\n '-c',\n 'user.name=agentbox',\n '-c',\n 'user.email=agentbox@users.noreply.github.com',\n 'commit',\n '--no-edit',\n ]);\n log(\n `resync: ${ct}: merged ${n} new host commit(s) from ${hostRef}` +\n (conflicts.length > 0 ? ` (${String(conflicts.length)} conflict(s) kept box version)` : ''),\n );\n } else if (merge.exitCode === 0) {\n log(`resync: ${ct}: ${n === '0' ? 'already up to date' : `fast-forwarded to ${hostRef}`}`);\n } else {\n // Hard failure (e.g. an untracked box file would be overwritten). Leave\n // the box untouched.\n await ports.boxGit(ct, ['merge', '--abort']);\n log(`resync: ${ct}: merge skipped (${(merge.stderr || merge.stdout).trim().split('\\n')[0]})`);\n }\n\n if (boxStashed) {\n const pop = await ports.boxGit(ct, ['stash', 'pop']);\n if (pop.exitCode !== 0) {\n // Box's uncommitted edits clash with the merged host change. Keep the\n // box's version (stash side = --theirs), drop the dangling stash.\n const popConflicts = await unmergedPaths(ports, ct);\n for (const p of popConflicts) {\n await ports.boxGit(ct, ['checkout', '--theirs', '--', p]);\n await ports.boxGit(ct, ['reset', '-q', '--', p]);\n }\n await ports.boxGit(ct, ['stash', 'drop']);\n }\n }\n }\n\n // --- overlay host uncommitted (stash) on top, box wins on conflict ---\n if (hostStashSha) {\n const apply = await ports.boxGit(ct, ['stash', 'apply', hostStashSha]);\n if (apply.exitCode !== 0) {\n const conflicts = await unmergedPaths(ports, ct);\n for (const p of conflicts) {\n // ours = box working tree, theirs = host stash → keep box, unstage.\n await ports.boxGit(ct, ['checkout', '--ours', '--', p]);\n await ports.boxGit(ct, ['reset', '-q', '--', p]);\n }\n if (conflicts.length > 0) res.overlaySkipped.push(...conflicts);\n }\n }\n\n // --- overlay host untracked files; box wins only when it actually differs ---\n if (hostUntracked.length > 0) {\n // Probe the box for each host path. A path absent in the box is copied; a\n // path present and byte-identical is a no-op (NOT a conflict — this is the\n // common case right after create-time seeding copied these same untracked\n // files in); a path present but differing (or a non-regular file we won't\n // clobber) is the box's version we keep and report.\n const boxTokens = await ports.probeUntrackedTokens(ct, hostUntracked);\n const toCopy: string[] = [];\n let identical = 0;\n for (const p of hostUntracked) {\n const boxToken = boxTokens.get(p);\n let hostHash = '';\n if (boxToken !== undefined && boxToken !== NON_REGULAR_TOKEN) {\n try {\n hostHash = await ports.hashHostFile(hostMain, p);\n } catch {\n // Host file vanished/unreadable since `ls-files` — can't copy it and\n // the box already has its own version; keep the box's, don't report.\n identical++;\n continue;\n }\n }\n const verdict = classifyUntrackedOverlay(boxToken, hostHash);\n if (verdict === 'copy') toCopy.push(p);\n else if (verdict === 'conflict') res.overlaySkipped.push(p);\n else identical++;\n }\n if (identical > 0) {\n log(`resync: ${ct}: ${String(identical)} untracked host file(s) already identical in box (no-op)`);\n }\n if (toCopy.length > 0) {\n const tar = await ports.packHostFiles(hostMain, toCopy);\n if (tar) {\n await ports.applyTarToBox(ct, tar);\n log(`resync: ${ct}: copied ${String(toCopy.length)} untracked host file(s)`);\n }\n }\n }\n\n results.push(res);\n }\n\n return results;\n}\n\n/**\n * The host-side half of {@link WorkspaceResyncPorts} — read-only git probes on\n * the host's own repo (checked-out ref, an uncommitted-changes stash sha, the\n * gitignore-respecting untracked list, a file content hash, and a tar pack of\n * chosen files). Host git is provider-neutral: it's the host's real repo whether\n * the box is docker or cloud, so both providers reuse these verbatim while\n * supplying their own box-side ports (`boxGit`/`probeUntrackedTokens`/\n * `applyTarToBox`). Each method reproduces the pre-refactor docker\n * `resyncWorkspaceFromHost` command byte-for-byte.\n *\n * The cloud live-box resync (Phase 7.5) reuses `listHostUntracked`/`hashHostFile`/\n * `packHostFiles` unchanged and overrides `resolveHostRef`/`createHostStash`\n * (its host ref/stash are pre-fetched into the box, not merged from a bind mount).\n */\nexport function makeHostGitPorts(): Pick<\n WorkspaceResyncPorts,\n 'resolveHostRef' | 'createHostStash' | 'listHostUntracked' | 'hashHostFile' | 'packHostFiles'\n> {\n return {\n async resolveHostRef(hostMain) {\n const hostBranchProbe = await execa(\n 'git',\n ['-C', hostMain, 'symbolic-ref', '--short', '-q', 'HEAD'],\n { reject: false },\n );\n const hostRef =\n hostBranchProbe.exitCode === 0 && hostBranchProbe.stdout.trim()\n ? hostBranchProbe.stdout.trim()\n : (await execa('git', ['-C', hostMain, 'rev-parse', 'HEAD'], { reject: false })).stdout.trim();\n return hostRef || null;\n },\n async createHostStash(hostMain) {\n const stash = await execa('git', ['-C', hostMain, 'stash', 'create'], { reject: false });\n return stash.exitCode === 0 ? stash.stdout.trim() || null : null;\n },\n async listHostUntracked(hostMain) {\n const untracked = await execa(\n 'git',\n ['-C', hostMain, 'ls-files', '--others', '--exclude-standard', '-z'],\n { reject: false },\n );\n return untracked.exitCode === 0 ? splitNul(untracked.stdout) : [];\n },\n async hashHostFile(hostMain, relPath) {\n return createHash('sha256').update(await readFile(join(hostMain, relPath))).digest('hex');\n },\n async packHostFiles(hostMain, relPaths) {\n const tarOut = await execa('tar', ['-C', hostMain, '--null', '-T', '-', '-cf', '-'], {\n input: relPaths.join('\\0'),\n encoding: 'buffer',\n reject: false,\n });\n return tarOut.exitCode === 0 ? (tarOut.stdout as Buffer) : null;\n },\n };\n}\n","/**\n * Concern: dynamic Claude config — the global `~/.claude/workflows/` scripts and\n * the current project's `memory/` tree. Unlike the static config\n * (plugins/skills/settings) that the cloud path bakes into the prepare-time\n * snapshot, these change between runs and must be refreshed per-box at create —\n * like credentials.\n *\n * These pieces are provider-neutral and pure where possible, so both the docker\n * volume sync and the cloud `seedDynamicConfig` reuse them:\n *\n * - `buildHostSyncManifest` hashes every file in each set on the host.\n * - `computeSyncDelta` diffs that against the manifest the box already\n * carries (captured by any checkpoint/snapshot), yielding the minimal set\n * of files to upload + delete and the manifest to write back.\n * - `stageDynamicSyncTarball` packs only the changed files into one tarball\n * whose members are laid out by set name, so the box `cp -a`s each set into\n * place without tar touching shared parent-dir perms.\n *\n * The box stores its manifest at {@link BOX_DYNAMIC_SYNC_MANIFEST}. Because it\n * lives on the box filesystem it rides along in every checkpoint, so a\n * checkpoint boot naturally syncs only what changed on the host since.\n *\n * Moved here (from `@agentbox/sandbox-docker`'s `dynamic-sync.ts`) so the cloud\n * path reuses it without importing the docker package. `sandbox-docker`\n * re-exports these for its existing importers.\n */\n\nimport { createHash } from 'node:crypto';\nimport { copyFile, mkdir, mkdtemp, readdir, readFile, rm, stat } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { execa } from 'execa';\nimport {\n BOX_CLAUDE_PROJECT_DIR,\n resolveClaudeMemoryDir,\n} from '../agents/claude/paths.js';\n\n/** In-box destination for the global workflow scripts. */\nexport const BOX_WORKFLOWS_DIR = '/home/vscode/.claude/workflows';\n\n/** In-box path of the per-box dynamic-sync manifest (rides along in checkpoints). */\nexport const BOX_DYNAMIC_SYNC_MANIFEST = '/home/vscode/.agentbox/dynamic-sync.json';\n\n/** In-box destination for the current project's rekeyed memory. */\nexport const BOX_MEMORY_DIR = `${BOX_CLAUDE_PROJECT_DIR}/memory`;\n\nexport type DynamicSyncSetName = 'workflows' | 'memory';\n\n/** A set's box destination dir + per-file content hashes (relpath -> sha256 hex). */\nexport interface DynamicSyncSet {\n dst: string;\n files: Record<string, string>;\n}\n\n/** Persisted shape written to {@link BOX_DYNAMIC_SYNC_MANIFEST}. */\nexport interface DynamicSyncManifest {\n version: 1;\n syncedAt?: string;\n sets: Record<DynamicSyncSetName, DynamicSyncSet>;\n}\n\n/** Host-side set: like {@link DynamicSyncSet} plus the source dir to read bytes from. */\ninterface HostSyncSet extends DynamicSyncSet {\n /** Absolute host source dir, or null when this set has nothing on the host. */\n hostDir: string | null;\n}\n\nexport interface HostSyncManifest {\n sets: Record<DynamicSyncSetName, HostSyncSet>;\n}\n\nexport interface DynamicSyncUpload {\n set: DynamicSyncSetName;\n /** Path relative to the set's dir. */\n rel: string;\n /** Absolute host source file. */\n absSrc: string;\n /** Absolute box destination file (`dst/rel`). */\n dst: string;\n}\n\nexport interface DynamicSyncDeletion {\n set: DynamicSyncSetName;\n rel: string;\n /** Absolute box file to remove. */\n dst: string;\n}\n\nexport interface DynamicSyncDelta {\n uploads: DynamicSyncUpload[];\n deletions: DynamicSyncDeletion[];\n /** Manifest to persist into the box after applying the delta (host state). */\n nextManifest: DynamicSyncManifest;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Recursively collect regular-file relpaths under `root` (posix-separated). */\nasync function walkFiles(root: string, prefix = ''): Promise<string[]> {\n let entries;\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch {\n return [];\n }\n const out: string[] = [];\n for (const ent of entries) {\n const rel = prefix ? `${prefix}/${ent.name}` : ent.name;\n const full = join(root, ent.name);\n if (ent.isDirectory()) {\n out.push(...(await walkFiles(full, rel)));\n } else if (ent.isFile()) {\n out.push(rel);\n } else if (ent.isSymbolicLink()) {\n // Follow only symlinks that resolve to a regular file (e.g. a workflow\n // symlinked from a checkout); ignore dangling/dir links.\n try {\n const s = await stat(full);\n if (s.isFile()) out.push(rel);\n } catch {\n /* skip dangling */\n }\n }\n }\n return out;\n}\n\nasync function hashFile(absPath: string): Promise<string> {\n const buf = await readFile(absPath);\n return createHash('sha256').update(buf).digest('hex');\n}\n\nasync function buildHostSet(\n name: DynamicSyncSetName,\n hostDir: string | null,\n boxDst: string,\n): Promise<HostSyncSet> {\n if (hostDir === null) return { dst: boxDst, files: {}, hostDir: null };\n const rels = await walkFiles(hostDir);\n const files: Record<string, string> = {};\n for (const rel of rels) {\n files[rel] = await hashFile(join(hostDir, rel));\n }\n return { dst: boxDst, files, hostDir };\n}\n\n/**\n * Hash the host's workflow + memory sets. `workspacePath` is the host-absolute\n * project path (used to locate the project's memory dir); `hostHome` is\n * overridable for tests. Sets with nothing on the host get an empty `files` map\n * and `hostDir: null` so the diff can still emit deletions for them.\n */\nexport async function buildHostSyncManifest(\n workspacePath: string,\n hostHome: string = homedir(),\n): Promise<HostSyncManifest> {\n const workflowsDir = join(hostHome, '.claude', 'workflows');\n const workflowsHost = (await pathExists(workflowsDir)) ? workflowsDir : null;\n const memoryHost = await resolveClaudeMemoryDir(workspacePath, hostHome);\n const [workflows, memory] = await Promise.all([\n buildHostSet('workflows', workflowsHost, BOX_WORKFLOWS_DIR),\n buildHostSet('memory', memoryHost, BOX_MEMORY_DIR),\n ]);\n return { sets: { workflows, memory } };\n}\n\nconst SET_NAMES: DynamicSyncSetName[] = ['workflows', 'memory'];\n\n/**\n * Diff the host manifest against the manifest the box already carries. A file\n * is uploaded when its hash differs (new or changed); a file in the box\n * manifest absent on the host is deleted. Pure — no IO, no clock.\n */\nexport function computeSyncDelta(\n host: HostSyncManifest,\n box: DynamicSyncManifest | null,\n): DynamicSyncDelta {\n const uploads: DynamicSyncUpload[] = [];\n const deletions: DynamicSyncDeletion[] = [];\n const nextSets = {} as Record<DynamicSyncSetName, DynamicSyncSet>;\n\n for (const name of SET_NAMES) {\n const hostSet = host.sets[name];\n const boxFiles = box?.sets?.[name]?.files ?? {};\n for (const [rel, hash] of Object.entries(hostSet.files)) {\n if (boxFiles[rel] !== hash) {\n uploads.push({\n set: name,\n rel,\n absSrc: join(hostSet.hostDir as string, rel),\n dst: `${hostSet.dst}/${rel}`,\n });\n }\n }\n for (const rel of Object.keys(boxFiles)) {\n if (!(rel in hostSet.files)) {\n deletions.push({ set: name, rel, dst: `${hostSet.dst}/${rel}` });\n }\n }\n nextSets[name] = { dst: hostSet.dst, files: hostSet.files };\n }\n\n return { uploads, deletions, nextManifest: { version: 1, sets: nextSets } };\n}\n\nexport interface StagedTarball {\n /** Absolute path to the .tar.gz, or null when there was nothing to upload. */\n tarballPath: string | null;\n /** Remove the staging dir + tarball. Idempotent. */\n cleanup(): Promise<void>;\n}\n\n/**\n * Pack the upload files into one gzip tarball laid out by set name\n * (`workflows/<rel>`, `memory/<rel>`). The box extracts into a staging dir and\n * `cp -a`s each set into its destination, so tar never touches the perms of\n * shared parent dirs (`/`, `/home`). Returns `{ tarballPath: null }` when\n * `uploads` is empty.\n */\nexport async function stageDynamicSyncTarball(\n uploads: DynamicSyncUpload[],\n): Promise<StagedTarball> {\n if (uploads.length === 0) {\n return { tarballPath: null, cleanup: async () => {} };\n }\n const stageDir = await mkdtemp(join(tmpdir(), 'agentbox-dynsync-stage-'));\n let tarballPath: string | null = null;\n try {\n for (const up of uploads) {\n const target = join(stageDir, up.set, up.rel);\n await mkdir(dirname(target), { recursive: true });\n await copyFile(up.absSrc, target);\n }\n tarballPath = join(tmpdir(), `agentbox-dynsync-${basename(stageDir)}.tar.gz`);\n // COPYFILE_DISABLE=1: stop macOS bsdtar from emitting AppleDouble sidecars.\n await execa('tar', ['-czf', tarballPath, '-C', stageDir, '.'], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n const tp = tarballPath;\n return {\n tarballPath: tp,\n cleanup: async () => {\n await rm(stageDir, { recursive: true, force: true });\n await rm(tp, { force: true });\n },\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n","/**\n * Stage the host's agent-config trees (`~/.claude`, `~/.codex`,\n * `~/.config/opencode` + `~/.local/share/opencode`) into filtered tarballs any\n * provider can ship into a remote sandbox.\n *\n * Per agent we produce **two** tarballs:\n *\n * - **static**: plugins, skills, settings, marketplaces, prompts, config —\n * stuff that's stable across re-auths. The cloud path bakes this into the\n * published Daytona snapshot once (`agentbox daytona publish-snapshot`),\n * so it ships into the sandbox FS at snapshot capture time, never the\n * S3-backed FUSE volume.\n *\n * - **credentials**: the renewable OAuth/auth files only (a handful of KB).\n * The cloud path uploads these into a per-org `agentbox-credentials`\n * volume on every create (cheap) and `agentbox daytona resync` refreshes\n * them after a re-auth — without touching the snapshot.\n *\n * Each `stage*ForUpload(opts)` returns a `StageResult`:\n * - `tarballPath`: absolute path to a `.tar.gz`, or `null` when the host has\n * nothing relevant to stage (no `~/.claude` etc., or no credentials file).\n * - `cleanup()`: removes the staging dir + the tarball; ALWAYS call after\n * the upload completes, even on error.\n * - `warnings`: non-fatal user-facing messages (the codex Keychain landmine\n * surfaces here).\n *\n * Requires `rsync` and `tar` on the host. macOS + every common Linux distro\n * ship both.\n */\n\nimport { copyFile, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { basename, join, relative } from 'node:path';\nimport { execa } from 'execa';\nimport {\n addProjectAlias,\n filterHostHooks,\n setInstallMethodNative,\n trustWorkspace,\n} from './claude-hooks-filter.js';\nimport { resolveAgentSpec } from './registry.js';\nimport { sanitizeCodexConfigForBox } from './codex-config.js';\n\n/**\n * Portable host backup of the claude OAuth creds — the single source of truth is\n * the registry (`credential.hostBackup`), which resolves to\n * `~/.agentbox/claude-credentials.json`. The docker provider's\n * `syncClaudeCredentials` mirrors the macOS Keychain into this same path.\n */\nconst CREDENTIALS_BACKUP_FILE = resolveAgentSpec('claude').credential.hostBackup;\n\nexport interface StageResult {\n /** Absolute path to the .tar.gz, or null when there was nothing to stage. */\n tarballPath: string | null;\n /** Remove the staging dir + tarball. Idempotent. */\n cleanup(): Promise<void>;\n /** Non-fatal messages (e.g. codex Keychain landmine). */\n warnings: string[];\n}\n\n/** Workspace path inside every cloud sandbox — matches the Docker model. */\nconst CLOUD_WORKSPACE = '/workspace';\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function findBrokenSymlinks(root: string): Promise<string[]> {\n const broken: string[] = [];\n async function walk(dir: string): Promise<void> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const ent of entries) {\n const full = join(dir, ent.name);\n if (ent.isSymbolicLink()) {\n try {\n await stat(full);\n } catch {\n broken.push(relative(root, full));\n }\n } else if (ent.isDirectory()) {\n await walk(full);\n }\n }\n }\n await walk(root);\n return broken;\n}\n\nasync function mkStageDir(prefix: string): Promise<string> {\n return mkdtemp(join(tmpdir(), `agentbox-${prefix}-stage-`));\n}\n\nfunction emptyResult(warnings: string[] = []): StageResult {\n return { tarballPath: null, cleanup: async () => {}, warnings };\n}\n\nasync function tarballFromDir(stageDir: string, agent: string): Promise<string> {\n const tarballPath = join(tmpdir(), `agentbox-${agent}-${basename(stageDir)}.tar.gz`);\n // COPYFILE_DISABLE=1: macOS's bsdtar (the system `tar`) walks extended attrs\n // and emits AppleDouble `._<name>` sidecars for any file with xattrs, which\n // then pollute the volume inside the cloud sandbox (claude reads ~/.claude\n // top-level and chokes on those bogus entries). The env knob makes Apple's\n // copyfile() helpers a no-op, so tar produces a clean POSIX archive.\n await execa('tar', ['-czf', tarballPath, '-C', stageDir, '.'], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n return tarballPath;\n}\n\nfunction makeCleanup(paths: string[]): () => Promise<void> {\n return async () => {\n for (const p of paths) {\n await rm(p, { recursive: true, force: true });\n }\n };\n}\n\n/**\n * Stage one file into a tarball whose only entry is that file at the tarball\n * root. Used for the credentials-only variants.\n */\nasync function stageSingleFileTarball(\n agent: string,\n sourcePath: string,\n tarballEntryName: string,\n): Promise<StageResult> {\n const stageDir = await mkStageDir(agent);\n let tarballPath: string | null = null;\n try {\n await copyFile(sourcePath, join(stageDir, tarballEntryName));\n tarballPath = await tarballFromDir(stageDir, agent);\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n// ---------- claude ----------\n\nexport interface StageClaudeOptions {\n /** Defaults to `homedir()`. Override for tests. */\n hostHome?: string;\n /**\n * The host-absolute workspace path being mounted as `/workspace` in the\n * box. When set, host-keyed `projects[<hostWorkspace>]` in `_claude.json`\n * gets duplicated to `projects['/workspace']` so MCP servers, history,\n * and trust state line up with the host's view of this project.\n */\n hostWorkspace?: string;\n}\n\n// Static-stage rsync excludes are registry data (single source of truth,\n// drift-guarded by the registry test). Bare patterns, mapped to `--exclude=`\n// at the rsync call; per-run broken-symlink excludes are appended there.\nconst CLAUDE_STATIC_EXCLUDES = resolveAgentSpec('claude').staticPaths[0]?.exclude ?? [];\n\n/**\n * Build the in-box `_claude.json` from the host's `~/.claude.json` (or a\n * sensible default when the host has no Claude config). Shared between the\n * full static tarball (prepare-time bake) and the json-only overlay\n * (create-time refresh).\n *\n * The defaults set `hasCompletedOnboarding: true` — a user who has installed\n * AgentBox has accepted Claude Code's onboarding implicitly, and the box's\n * Claude must not block on the theme picker. When the host *does* have a\n * `~/.claude.json`, the existing `hasCompletedOnboarding` / `theme` pass\n * through unchanged (the filter chain only touches hooks/install/projects/\n * trust).\n */\nasync function buildBoxClaudeJsonFromHost(opts: {\n hostHome: string;\n hostWorkspace?: string;\n}): Promise<unknown> {\n const { hostHome, hostWorkspace } = opts;\n const hostClaudeJson = join(hostHome, '.claude.json');\n let working: unknown;\n if (await pathExists(hostClaudeJson)) {\n try {\n working = JSON.parse(await readFile(hostClaudeJson, 'utf8'));\n } catch {\n working = null;\n }\n }\n if (working === undefined || working === null) {\n working = {\n installMethod: 'native',\n autoUpdates: false,\n autoUpdatesProtectedForNative: true,\n // Pre-accept onboarding so the in-box Claude doesn't show the theme\n // picker on first run. AgentBox installing implies the user has\n // already used Claude Code on the host.\n hasCompletedOnboarding: true,\n projects: { [CLOUD_WORKSPACE]: { hasTrustDialogAccepted: true } },\n };\n } else {\n working = filterHostHooks(working, hostHome).data;\n working = setInstallMethodNative(working).data;\n if (hostWorkspace) {\n working = addProjectAlias(working, hostWorkspace, CLOUD_WORKSPACE).data;\n }\n working = trustWorkspace(working, CLOUD_WORKSPACE).data;\n // Belt-and-suspenders for hosts that have ~/.claude.json but haven't\n // completed onboarding (e.g. a CI runner or a fresh dev machine that's\n // never opened Claude interactively).\n if (typeof working === 'object' && working !== null) {\n const w = working as Record<string, unknown>;\n if (w['hasCompletedOnboarding'] !== true) w['hasCompletedOnboarding'] = true;\n }\n }\n return working;\n}\n\n/**\n * Tarball with **only** `_claude.json` at the root, built from the host's\n * current `~/.claude.json` state. Used at cloud create-time to overlay the\n * box's onboarding state, so a stale prepare-time snapshot doesn't trap the\n * in-box Claude at the theme picker. E2B (which doesn't bake `_claude.json`\n * at prepare-time at all) relies on this overlay for any onboarding state.\n *\n * Returns a real tarball even when the host has no `~/.claude.json` — the\n * default falls back to a minimal pre-onboarded shape (see\n * {@link buildBoxClaudeJsonFromHost}).\n */\nexport async function stageClaudeJsonOnlyForUpload(\n opts: StageClaudeOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const stageDir = await mkStageDir('claude-json-only');\n let tarballPath: string | null = null;\n try {\n const claudeJson = await buildBoxClaudeJsonFromHost({\n hostHome,\n hostWorkspace: opts.hostWorkspace,\n });\n await writeFile(join(stageDir, '_claude.json'), JSON.stringify(claudeJson, null, 2));\n tarballPath = await tarballFromDir(stageDir, 'claude-json-only');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n/**\n * Filtered tarball of `~/.claude/` (+ `~/.claude.json` as `_claude.json` at\n * tarball root) **excluding** `.credentials.json`. Extracts into\n * `/home/vscode/.claude/` on the sandbox FS at snapshot-bake time.\n *\n * Mirrors `ensureClaudeVolume`'s rsync excludes (drops `node_modules`),\n * filters host-path hooks out of `settings.json` / `_claude.json`, coerces\n * install-method to native, aliases the host workspace path to `/workspace`,\n * and pre-trusts `/workspace`. Plugin `installed_plugins.json` and\n * `known_marketplaces.json` get their host-home `installPath` values rewritten\n * to the box's `/home/vscode/.claude/`.\n */\nexport async function stageClaudeStaticForUpload(\n opts: StageClaudeOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostClaude = join(hostHome, '.claude');\n if (!(await pathExists(hostClaude))) return emptyResult();\n\n const stageDir = await mkStageDir('claude-static');\n let tarballPath: string | null = null;\n try {\n // rsync host ~/.claude → stage. --copy-unsafe-links dereferences user\n // skill symlinks; --exclude=node_modules drops host-platform binaries\n // (fsevents.node, esbuild, ...). Broken symlinks would abort the whole\n // sync under --copy-unsafe-links, so pre-scan and exclude them.\n //\n // Drop runtime/history state so the snapshot bake doesn't capture\n // per-machine session data the in-box claude will regenerate anyway.\n const broken = await findBrokenSymlinks(hostClaude);\n const excludes = [\n ...CLAUDE_STATIC_EXCLUDES.map((p) => `--exclude=${p}`),\n ...broken.map((r) => `--exclude=/${r}`),\n ];\n await execa('rsync', [\n '-a',\n '--copy-unsafe-links',\n ...excludes,\n `${hostClaude}/`,\n `${stageDir}/`,\n ]);\n\n // settings.json: filter host-path hooks; rewrite in place when changed.\n const settingsPath = join(stageDir, 'settings.json');\n if (await pathExists(settingsPath)) {\n try {\n const parsed = JSON.parse(await readFile(settingsPath, 'utf8'));\n const filtered = filterHostHooks(parsed, hostHome);\n if (filtered.removedCommands.length > 0) {\n await writeFile(settingsPath, JSON.stringify(filtered.data, null, 2));\n }\n } catch {\n // Leave the rsynced copy if parse failed.\n }\n }\n\n // _claude.json — sourced from $HOME/.claude.json (which lives outside\n // ~/.claude). Apply the same filter chain `ensureClaudeVolume` uses:\n // host-path hooks, install-method=native, host->/workspace project alias,\n // and /workspace trust pre-accept. The Dockerfile.box bakes a symlink\n // `~/.claude.json -> ~/.claude/_claude.json` so the in-box claude reads\n // through to this file at runtime.\n const claudeJson = await buildBoxClaudeJsonFromHost({\n hostHome,\n hostWorkspace: opts.hostWorkspace,\n });\n await writeFile(join(stageDir, '_claude.json'), JSON.stringify(claudeJson, null, 2));\n\n // plugins/*.json: rewrite host-home installPath/installLocation values to\n // the box's /home/vscode/.claude/plugins/ tree. Without this, claude\n // resolves plugin paths to /Users/<you>/... inside the box and the\n // marketplace fails to load.\n const pluginsDir = join(stageDir, 'plugins');\n if (await pathExists(pluginsDir)) {\n try {\n const entries = await readdir(pluginsDir, { withFileTypes: true });\n for (const ent of entries) {\n if (!ent.isFile() || !ent.name.endsWith('.json')) continue;\n const file = join(pluginsDir, ent.name);\n const raw = await readFile(file, 'utf8');\n const replaced = raw\n .split(`${hostHome}/.claude/plugins/`)\n .join('/home/vscode/.claude/plugins/');\n if (replaced !== raw) await writeFile(file, replaced);\n }\n } catch {\n // Best-effort: a broken plugins/ dir mustn't sink the whole seed.\n }\n }\n\n tarballPath = await tarballFromDir(stageDir, 'claude-static');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n/**\n * Tarball with **only** `.credentials.json` (sourced from\n * `~/.agentbox/claude-credentials.json`, the portable backup the Docker\n * provider's `syncClaudeCredentials` mirrors from the macOS Keychain). The\n * cloud path extracts this into `/home/vscode/.agentbox-creds/claude/` on the\n * shared `agentbox-credentials` volume; a baked symlink in the snapshot at\n * `~/.claude/.credentials.json` resolves through to it at runtime.\n *\n * Returns an empty result when no backup exists (the in-box claude falls back\n * to interactive sign-in).\n */\nexport async function stageClaudeCredentialsForUpload(): Promise<StageResult> {\n if (!(await pathExists(CREDENTIALS_BACKUP_FILE))) return emptyResult();\n return stageSingleFileTarball('claude-creds', CREDENTIALS_BACKUP_FILE, '.credentials.json');\n}\n\n// ---------- codex ----------\n\nexport interface StageCodexOptions {\n hostHome?: string;\n}\n\n// Registry data (single source of truth, drift-guarded by the registry test).\n// Bare patterns mapped to `--exclude=` at the rsync call. Highlights: the\n// `state_*.sqlite*` threads index is the resume-cwd source (rebuilt in-box from\n// rollouts, so seeding it would trap a teleported session at the host cwd);\n// `packages`/`plugins/.plugin-appserver`/`computer-use` are heavy macOS-only\n// artifacts that balloon the staged tarball (~800 MB → ~0.5 MB).\nconst CODEX_STATIC_EXCLUDES = resolveAgentSpec('codex').staticPaths[0]?.exclude ?? [];\n\nconst CODEX_KEYCHAIN_WARNING =\n 'codex: ~/.codex/auth.json missing. On macOS the codex CLI defaults to ' +\n 'storing the OAuth token in the system Keychain, which isn\\'t reachable ' +\n 'from a remote sandbox. To share creds with cloud boxes either:\\n' +\n ' - add `cli_auth_credentials_store = \"file\"` to ~/.codex/config.toml ' +\n 'then re-run `codex login`, or\\n' +\n ' - set OPENAI_API_KEY in your environment, or\\n' +\n ' - run `codex login --with-api-key` for a file-backed login.\\n' +\n 'Skipping codex seed; in-box codex will prompt for sign-in.';\n\n/**\n * Filtered tarball of `~/.codex/` **excluding** `auth.json`. Extracts into\n * `/home/vscode/.codex/` on the sandbox FS at snapshot-bake time.\n *\n * `-L` dereferences EVERY symlink (codex sprouts links into `~/.nvm` for the\n * `applypatch` argv0 trick and into `~/.agents/skills/*`); produces a\n * symlink-free archive suitable for the FUSE-backed Daytona volume and the\n * sandbox FS alike. Broken symlinks would abort rsync under `-L`, so pre-scan\n * and skip them.\n */\n/**\n * Best-effort, in-place sanitize of a staged `config.toml`: drops host-only-path\n * `mcp_servers` / `notify` / local marketplaces via {@link\n * sanitizeCodexConfigForBox}. A missing file, a parse failure, or any IO error\n * leaves the file untouched — staging must never fail on config sanitization.\n */\nasync function sanitizeStagedCodexConfig(configPath: string, hostHome: string): Promise<void> {\n try {\n if (!(await pathExists(configPath))) return;\n const { text, changed } = sanitizeCodexConfigForBox(await readFile(configPath, 'utf8'), hostHome);\n if (changed) await writeFile(configPath, text);\n } catch {\n // leave the rsynced copy as-is\n }\n}\n\nexport async function stageCodexStaticForUpload(\n opts: StageCodexOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostCodex = join(hostHome, '.codex');\n if (!(await pathExists(hostCodex))) return emptyResult();\n\n const stageDir = await mkStageDir('codex-static');\n let tarballPath: string | null = null;\n try {\n const codexBroken = await findBrokenSymlinks(hostCodex);\n await execa('rsync', [\n '-a',\n '-L',\n ...codexBroken.map((r) => `--exclude=/${r}`),\n ...CODEX_STATIC_EXCLUDES.map((p) => `--exclude=${p}`),\n `${hostCodex}/`,\n `${stageDir}/`,\n ]);\n // Strip host-only-path entries (desktop-Codex.app MCP servers like\n // node_repl, a macOS notify helper, local-source marketplaces) from the\n // staged config.toml so the in-box codex doesn't try to exec macOS paths.\n // Best-effort: a parse failure leaves the rsynced copy intact.\n await sanitizeStagedCodexConfig(join(stageDir, 'config.toml'), hostHome);\n tarballPath = await tarballFromDir(stageDir, 'codex-static');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n// ---------- agents (shared ~/.agents skills) ----------\n\n/**\n * Filtered tarball of `~/.agents/` (the cross-agent \"Agent Skills\" dir).\n * Extracts into `/home/vscode/.agents/` on the sandbox FS at snapshot-bake time\n * so the in-box agents (codex reads `~/.agents/skills` directly) see the same\n * skill set the host does. `-L` dereferences each skill's symlinks into real\n * files; broken ones are excluded so the sync can't abort.\n */\nexport async function stageAgentsStaticForUpload(\n opts: { hostHome?: string } = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostAgents = join(hostHome, '.agents');\n if (!(await pathExists(hostAgents))) return emptyResult();\n\n const stageDir = await mkStageDir('agents-static');\n let tarballPath: string | null = null;\n try {\n const broken = await findBrokenSymlinks(hostAgents);\n await execa('rsync', [\n '-a',\n '-L',\n ...broken.map((r) => `--exclude=/${r}`),\n `${hostAgents}/`,\n `${stageDir}/`,\n ]);\n tarballPath = await tarballFromDir(stageDir, 'agents-static');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n/**\n * Tarball with **only** `auth.json`. Prefers the cloud backup\n * `~/.agentbox/codex-credentials.json` (a login captured from a previous cloud\n * box by `extractCloudAgentCredentials`); falls back to the host's real\n * `~/.codex/auth.json` so a fresh project still bootstraps from a host login.\n * Surfaces the macOS Keychain landmine as a warning when neither exists — see\n * `CODEX_KEYCHAIN_WARNING`.\n */\nexport async function stageCodexCredentialsForUpload(\n opts: StageCodexOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n // Prefer the cloud backup under <hostHome>/.agentbox. Derive it from hostHome\n // (rather than the module-load `CODEX_CREDENTIALS_BACKUP_FILE` constant) so the\n // path tracks the active home: production uses the real home — identical to the\n // constant — while tests/callers can redirect the whole lookup via hostHome.\n const cloudBackup = join(hostHome, '.agentbox', 'codex-credentials.json');\n if (await pathExists(cloudBackup)) {\n return stageSingleFileTarball('codex-creds', cloudBackup, 'auth.json');\n }\n const hostAuth = join(hostHome, '.codex', 'auth.json');\n if (!(await pathExists(hostAuth))) return emptyResult([CODEX_KEYCHAIN_WARNING]);\n return stageSingleFileTarball('codex-creds', hostAuth, 'auth.json');\n}\n\n// ---------- opencode ----------\n\nexport interface StageOpencodeOptions {\n hostHome?: string;\n}\n\n// Registry data (single source of truth, drift-guarded by the registry test).\n// Bare patterns mapped to `--exclude=` at the rsync call. `auth.json` ships\n// separately; the rest is host-only runtime state.\nconst OPENCODE_DATA_EXCLUDES = resolveAgentSpec('opencode').staticPaths[0]?.exclude ?? [];\n\n/**\n * Filtered tarball of opencode static config. Layout extracts into\n * `/home/vscode/.local/share/opencode/`:\n *\n * ./<data files> ← from ~/.local/share/opencode/ (minus auth.json)\n * ./config/<config files> ← from ~/.config/opencode/\n *\n * `auth.json` is **excluded** — it ships separately via the credentials\n * variant.\n */\nexport async function stageOpencodeStaticForUpload(\n opts: StageOpencodeOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostData = join(hostHome, '.local', 'share', 'opencode');\n const hostConfig = join(hostHome, '.config', 'opencode');\n const hasData = await pathExists(hostData);\n const hasConfig = await pathExists(hostConfig);\n if (!hasData && !hasConfig) return emptyResult();\n\n const stageDir = await mkStageDir('opencode-static');\n let tarballPath: string | null = null;\n try {\n // `-L` dereferences every symlink — Daytona's FUSE volumes reject symlink\n // creation, and the sandbox FS doesn't care either way. Broken symlinks\n // would abort rsync under `-L`, so pre-scan and skip them.\n if (hasData) {\n const dataBroken = await findBrokenSymlinks(hostData);\n await execa('rsync', [\n '-a',\n '-L',\n ...dataBroken.map((r) => `--exclude=/${r}`),\n ...OPENCODE_DATA_EXCLUDES.map((p) => `--exclude=${p}`),\n `${hostData}/`,\n `${stageDir}/`,\n ]);\n }\n if (hasConfig) {\n const configStage = join(stageDir, 'config');\n const cfgBroken = await findBrokenSymlinks(hostConfig);\n await execa('rsync', [\n '-a',\n '-L',\n ...cfgBroken.map((r) => `--exclude=/${r}`),\n `${hostConfig}/`,\n `${configStage}/`,\n ]);\n }\n tarballPath = await tarballFromDir(stageDir, 'opencode-static');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n/**\n * Tarball with **only** `auth.json`. Prefers the cloud backup\n * `~/.agentbox/opencode-credentials.json` (captured from a previous cloud box);\n * falls back to the host's real `~/.local/share/opencode/auth.json`. Returns an\n * empty result when neither exists.\n */\nexport async function stageOpencodeCredentialsForUpload(\n opts: StageOpencodeOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n // Cloud backup under <hostHome>/.agentbox, derived from hostHome (see the\n // codex stager above) so the path tracks the active home and tests stay\n // hermetic; production matches OPENCODE_CREDENTIALS_BACKUP_FILE.\n const cloudBackup = join(hostHome, '.agentbox', 'opencode-credentials.json');\n if (await pathExists(cloudBackup)) {\n return stageSingleFileTarball('opencode-creds', cloudBackup, 'auth.json');\n }\n const hostAuth = join(hostHome, '.local', 'share', 'opencode', 'auth.json');\n if (!(await pathExists(hostAuth))) return emptyResult();\n return stageSingleFileTarball('opencode-creds', hostAuth, 'auth.json');\n}\n\n/**\n * Tarball with **only** the selected-model state (`model.json`, sourced from\n * `~/.local/state/opencode/model.json`). Extracts to a box's state dir so a\n * fresh box inherits the host's active model instead of OpenCode's default.\n * Returns an empty result when the host has never picked a model.\n */\nexport async function stageOpencodeStateForUpload(\n opts: StageOpencodeOptions = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostModel = join(hostHome, '.local', 'state', 'opencode', 'model.json');\n if (!(await pathExists(hostModel))) return emptyResult();\n return stageSingleFileTarball('opencode-state', hostModel, 'model.json');\n}\n\n// ---------- all-agent static bake (shared across cloud prepare paths) ----------\n\n/** Box-side dir each tool's static tarball extracts into. Provider-neutral —\n * the same target on every backend (docker model). */\nconst CLAUDE_STATIC_BOX_DIR = '/home/vscode/.claude';\nconst CODEX_STATIC_BOX_DIR = '/home/vscode/.codex';\nconst OPENCODE_STATIC_BOX_DIR = '/home/vscode/.local/share/opencode';\nconst AGENTS_STATIC_BOX_DIR = '/home/vscode/.agents';\n\nexport interface AgentStaticStage {\n kind: 'claude' | 'codex' | 'opencode' | 'agents';\n /** Absolute box path the static tarball extracts into. */\n extractDir: string;\n staged: StageResult;\n}\n\n/**\n * Stage all four host static-config trees in parallel, each paired with the\n * box-side dir it extracts into. This is the single source of truth for the\n * cloud prepare paths (vercel / hetzner / daytona / e2b): every provider walks\n * this list and supplies only its own upload + extract transport, never its own\n * copy of the producer→dir mapping. The caller must `staged.cleanup()` each\n * result after the build has picked the tarball up.\n */\nexport async function stageAllAgentStatic(\n opts: { hostWorkspace?: string } = {},\n): Promise<AgentStaticStage[]> {\n const [claude, codex, opencode, agents] = await Promise.all([\n stageClaudeStaticForUpload({ hostWorkspace: opts.hostWorkspace }),\n stageCodexStaticForUpload(),\n stageOpencodeStaticForUpload(),\n stageAgentsStaticForUpload(),\n ]);\n return [\n { kind: 'claude', extractDir: CLAUDE_STATIC_BOX_DIR, staged: claude },\n { kind: 'codex', extractDir: CODEX_STATIC_BOX_DIR, staged: codex },\n { kind: 'opencode', extractDir: OPENCODE_STATIC_BOX_DIR, staged: opencode },\n { kind: 'agents', extractDir: AGENTS_STATIC_BOX_DIR, staged: agents },\n ];\n}\n","export interface HookFilterResult<T = unknown> {\n data: T;\n removedCommands: string[];\n}\n\n/**\n * Predicate for the filter: does `command` look like it points at a host path\n * outside the project, i.e. under the user's host home directory?\n *\n * Uses `.includes(hostHome + '/')` so we also catch shell-quoted forms like\n * `bash -c '/Users/marco/.config/iterm2/cc-status'`. The trailing slash gates\n * against false matches on similar-prefix home dirs (e.g. `/Users/marco`\n * shouldn't match `/Users/marco-other/...`).\n *\n * Returns false when `hostHome` is empty so we degrade safely if no home is\n * resolvable for some reason.\n */\nexport function isHostPathHookCommand(command: string, hostHome: string): boolean {\n if (typeof command !== 'string' || command.length === 0) return false;\n if (hostHome.length === 0) return false;\n return command.includes(hostHome + '/');\n}\n\ninterface HookLeaf {\n type?: string;\n command?: string;\n [k: string]: unknown;\n}\n\ninterface HookMatcherEntry {\n hooks?: unknown;\n [k: string]: unknown;\n}\n\n/**\n * Walk Claude Code's documented `hooks.<Trigger>[].hooks[]` structure and drop\n * any leaf `{ type: 'command', command: '<host-path>' }` whose `command` matches\n * {@link isHostPathHookCommand}. Empty `hooks: []` arrays and their matcher\n * wrappers are left intact — they don't break Claude and avoiding recursive\n * cleanup keeps the filter predictable.\n *\n * Returns a deep clone; input is not mutated. Tolerant of unexpected shapes\n * (string, number, null at any level): unrecognized branches pass through\n * unchanged, removed count stays accurate.\n */\nexport function filterHostHooks<T = unknown>(data: T, hostHome: string): HookFilterResult<T> {\n // structuredClone is in node >= 17; the repo targets node20, so this is safe.\n const clone = structuredClone(data) as unknown;\n const removedCommands: string[] = [];\n\n if (clone === null || typeof clone !== 'object' || Array.isArray(clone)) {\n return { data: clone as T, removedCommands };\n }\n\n const top = clone as { hooks?: unknown };\n const hooksRoot = top.hooks;\n if (hooksRoot === null || typeof hooksRoot !== 'object' || Array.isArray(hooksRoot)) {\n return { data: clone as T, removedCommands };\n }\n\n for (const triggerName of Object.keys(hooksRoot as Record<string, unknown>)) {\n const triggerValue = (hooksRoot as Record<string, unknown>)[triggerName];\n if (!Array.isArray(triggerValue)) continue;\n for (const entry of triggerValue) {\n if (entry === null || typeof entry !== 'object') continue;\n const matcher = entry as HookMatcherEntry;\n const inner = matcher.hooks;\n if (!Array.isArray(inner)) continue;\n // In-place filter on the cloned array.\n for (let i = inner.length - 1; i >= 0; i--) {\n const leaf = inner[i] as HookLeaf | null;\n if (leaf === null || typeof leaf !== 'object') continue;\n if (\n leaf.type === 'command' &&\n typeof leaf.command === 'string' &&\n isHostPathHookCommand(leaf.command, hostHome)\n ) {\n removedCommands.push(leaf.command);\n inner.splice(i, 1);\n }\n }\n }\n }\n\n return { data: clone as T, removedCommands };\n}\n\nexport interface SetInstallMethodNativeResult<T = unknown> {\n data: T;\n applied: boolean;\n}\n\nexport interface AddProjectAliasResult<T = unknown> {\n data: T;\n aliased: boolean;\n}\n\nexport interface TrustWorkspaceResult<T = unknown> {\n data: T;\n trusted: boolean;\n}\n\n/**\n * Force `projects[workspacePath].hasTrustDialogAccepted = true` in a parsed\n * `~/.claude.json`, creating the `projects` map and the project entry if\n * absent.\n *\n * The box is a sandbox: the agent is created explicitly to work in\n * `/workspace`, and the box is isolated from the host — so the folder-trust\n * dialog is pointless there. More importantly, Claude Code, when it opens an\n * *untrusted* folder, sends a malformed first API request that Anthropic\n * rejects with `400 role 'system' is not supported on this model`. Pre-trusting\n * the box's workspace skips the dialog *and* dodges that bug.\n *\n * Returns a deep-cloned, modified copy plus a flag for whether anything\n * changed (`false` when it was already trusted). Input is not mutated; no-op\n * for non-object data or an empty path.\n */\nexport function trustWorkspace<T = unknown>(\n data: T,\n workspacePath: string,\n): TrustWorkspaceResult<T> {\n const clone = structuredClone(data) as unknown;\n if (clone === null || typeof clone !== 'object' || Array.isArray(clone)) {\n return { data: clone as T, trusted: false };\n }\n if (workspacePath.length === 0) return { data: clone as T, trusted: false };\n const obj = clone as { projects?: unknown };\n if (obj.projects === null || typeof obj.projects !== 'object' || Array.isArray(obj.projects)) {\n obj.projects = {};\n }\n const projects = obj.projects as Record<string, unknown>;\n const existing = projects[workspacePath];\n const entry =\n existing !== null && typeof existing === 'object' && !Array.isArray(existing)\n ? (existing as Record<string, unknown>)\n : {};\n if (entry.hasTrustDialogAccepted === true) {\n projects[workspacePath] = entry;\n return { data: clone as T, trusted: false };\n }\n entry.hasTrustDialogAccepted = true;\n projects[workspacePath] = entry;\n return { data: clone as T, trusted: true };\n}\n\n/**\n * Claude Code keys project-scoped state (history, mcpServers, enabledPlugins,\n * trust prompts) under `projects[<absolute-workspace-path>]` in\n * `~/.claude.json`. On the host the key is something like\n * `/Users/marco/Projects/foo`; inside the box the workspace is always\n * `/workspace`. Without rewriting, the box never sees the host's project-\n * scoped settings.\n *\n * Copy (don't move) the host-keyed entry to `toPath` if present. Existing\n * `projects[toPath]` is preserved by merging the host entry on top — host\n * is authoritative for keys it sets; box-only keys (e.g. session ids\n * accumulated inside earlier boxes) stay intact.\n *\n * No-op (returns `aliased: false`) when:\n * - data isn't an object, or `projects` isn't an object\n * - fromPath equals toPath\n * - projects[fromPath] doesn't exist or isn't an object\n *\n * Returns a deep-cloned, modified copy; input is not mutated.\n */\nexport function addProjectAlias<T = unknown>(\n data: T,\n fromPath: string,\n toPath: string,\n): AddProjectAliasResult<T> {\n const clone = structuredClone(data) as unknown;\n if (clone === null || typeof clone !== 'object' || Array.isArray(clone)) {\n return { data: clone as T, aliased: false };\n }\n if (fromPath === toPath || fromPath.length === 0 || toPath.length === 0) {\n return { data: clone as T, aliased: false };\n }\n const obj = clone as { projects?: unknown };\n const projects = obj.projects;\n if (projects === null || typeof projects !== 'object' || Array.isArray(projects)) {\n return { data: clone as T, aliased: false };\n }\n const projectsMap = projects as Record<string, unknown>;\n const src = projectsMap[fromPath];\n if (src === null || typeof src !== 'object' || Array.isArray(src)) {\n return { data: clone as T, aliased: false };\n }\n const existing = projectsMap[toPath];\n if (existing !== null && typeof existing === 'object' && !Array.isArray(existing)) {\n projectsMap[toPath] = { ...(existing as Record<string, unknown>), ...(src as Record<string, unknown>) };\n } else {\n projectsMap[toPath] = structuredClone(src);\n }\n return { data: clone as T, aliased: true };\n}\n\n/**\n * Force the install-method fields in a parsed `~/.claude.json` to match the\n * box's native install. Sets exactly what `claude install` writes:\n * installMethod: \"native\"\n * autoUpdates: false\n * autoUpdatesProtectedForNative: true\n *\n * Without this, the in-box claude reports\n * `Running native installation but config install method is 'not set'` in\n * /status — the host's value (often `npm-global` on Mac, or absent) doesn't\n * match the box's `~/.local/bin/claude` install location, and merely\n * clearing the field leaves it unset rather than fixing it.\n *\n * Returns a deep-cloned, fixed copy plus a flag indicating whether any of\n * the three fields actually changed. Input is not mutated.\n */\nexport function setInstallMethodNative<T = unknown>(data: T): SetInstallMethodNativeResult<T> {\n const clone = structuredClone(data) as unknown;\n if (clone === null || typeof clone !== 'object' || Array.isArray(clone)) {\n return { data: clone as T, applied: false };\n }\n const obj = clone as Record<string, unknown>;\n const changed =\n obj.installMethod !== 'native' ||\n obj.autoUpdates !== false ||\n obj.autoUpdatesProtectedForNative !== true;\n obj.installMethod = 'native';\n obj.autoUpdates = false;\n obj.autoUpdatesProtectedForNative = true;\n return { data: clone as T, applied: changed };\n}\n","import { homedir } from 'node:os';\nimport { parse, stringify } from 'smol-toml';\n\n/**\n * Sanitize the host's `~/.codex/config.toml` before it is seeded into a box.\n *\n * The host config routinely points at host-only absolute paths — the desktop\n * Codex.app's bundled MCP servers (`/Applications/Codex.app/...`), a macOS\n * `notify` helper, and local-source plugin marketplaces under the host home.\n * None of those exist in the Linux box, so in-box codex emits startup warnings\n * (`MCP client for \\`node_repl\\` failed to start: No such file or directory`,\n * etc.). We strip exactly the entries whose paths cannot resolve in the box and\n * leave everything else (model, reasoning effort, project trust, features, and\n * any MCP server reachable via PATH or a Linux-plausible absolute path).\n */\n\n/**\n * True when `cmd` is an absolute path under a location guaranteed absent in the\n * Linux box: the host home, or a macOS-only / host-package root. Bare program\n * names (PATH-resolved, e.g. `node`, `npx`, `uvx`) and Linux-plausible\n * absolutes (`/usr/...`, `/bin/...`) are kept — we never over-strip.\n */\nexport function isHostOnlyPath(cmd: unknown, hostHome: string): boolean {\n if (typeof cmd !== 'string' || cmd.length === 0) return false;\n if (!cmd.startsWith('/')) return false; // PATH-resolved bare name — may exist in box\n const hostOnlyRoots = [\n hostHome.endsWith('/') ? hostHome : `${hostHome}/`,\n '/Applications/',\n '/opt/homebrew/',\n '/Library/',\n '/System/',\n '/private/',\n '/Users/',\n ];\n return hostOnlyRoots.some((root) => cmd.startsWith(root));\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** The box workspace path — Codex must trust it so it doesn't pop the \"trust\n * this folder?\" prompt on first attach. Same value the docker + cloud paths\n * mount the project at. */\nexport const BOX_WORKSPACE = '/workspace';\n\n/** Minimal config.toml that pre-trusts `/workspace`, for a host with no\n * `~/.codex/config.toml` to sanitize (so the box still skips the trust prompt). */\nexport const MINIMAL_TRUSTED_CODEX_CONFIG = `[projects.\"${BOX_WORKSPACE}\"]\\ntrust_level = \"trusted\"\\n`;\n\nexport interface SanitizeCodexConfigResult {\n /** Sanitized TOML (re-serialized); equals the input semantically when `changed` is false. */\n text: string;\n /** True when at least one host-only entry was stripped. */\n changed: boolean;\n}\n\n/**\n * Parse → mutate → re-serialize the codex `config.toml`, dropping entries that\n * reference host-only paths. Throws on a TOML parse failure so callers can fall\n * back to copying the file verbatim. Reformatting (lost comments / reordered\n * keys) is acceptable: the box copy is derived and consumed only by in-box codex.\n *\n * Returns `changed: false` (so callers can keep the host's original copy\n * untouched) when nothing host-only was found.\n */\nexport function sanitizeCodexConfigForBox(\n tomlText: string,\n hostHome: string = homedir(),\n): SanitizeCodexConfigResult {\n const cfg = parse(tomlText) as Record<string, unknown>;\n let changed = false;\n\n // mcp_servers: drop servers whose `command` is a host-only path.\n if (isRecord(cfg['mcp_servers'])) {\n const servers = cfg['mcp_servers'];\n for (const [name, def] of Object.entries(servers)) {\n if (isRecord(def) && isHostOnlyPath(def['command'], hostHome)) {\n delete servers[name];\n changed = true;\n }\n }\n }\n\n // notify: an array whose first element is the program to run. Drop the key\n // when that program is a host-only path.\n const notify = cfg['notify'];\n if (Array.isArray(notify) && isHostOnlyPath(notify[0], hostHome)) {\n delete cfg['notify'];\n changed = true;\n }\n\n // marketplaces: drop local-source marketplaces under a host-only path, then\n // drop the plugins that reference them (`\"<plugin>@<marketplace>\"`).\n const droppedMarkets = new Set<string>();\n if (isRecord(cfg['marketplaces'])) {\n const markets = cfg['marketplaces'];\n for (const [name, def] of Object.entries(markets)) {\n if (\n isRecord(def) &&\n def['source_type'] === 'local' &&\n isHostOnlyPath(def['source'], hostHome)\n ) {\n delete markets[name];\n droppedMarkets.add(name);\n changed = true;\n }\n }\n }\n if (droppedMarkets.size > 0 && isRecord(cfg['plugins'])) {\n const plugins = cfg['plugins'];\n for (const key of Object.keys(plugins)) {\n const marketplace = key.split('@')[1];\n if (marketplace !== undefined && droppedMarkets.has(marketplace)) {\n delete plugins[key];\n changed = true;\n }\n }\n }\n\n // Pre-trust the box workspace so codex doesn't prompt \"trust this folder?\" on\n // first attach. The box mounts the project at /workspace; the host config only\n // trusts host-absolute project paths, never /workspace. (Codex's own\n // path-based `[projects.\"<path>\"].trust_level` is stable — unlike the\n // hash-based hook trust — so this is safe to persist.)\n if (!isRecord(cfg['projects'])) cfg['projects'] = {};\n const projects = cfg['projects'] as Record<string, unknown>;\n const wsEntry = isRecord(projects[BOX_WORKSPACE]) ? projects[BOX_WORKSPACE] : {};\n if (wsEntry['trust_level'] !== 'trusted') {\n wsEntry['trust_level'] = 'trusted';\n projects[BOX_WORKSPACE] = wsEntry;\n changed = true;\n }\n\n return { text: changed ? stringify(cfg) : tomlText, changed };\n}\n","/**\n * Cross-provider versioning primitives for `~/.agentbox/<provider>-prepared.json`.\n *\n * Each provider records what it has baked (docker image / hetzner snapshot /\n * daytona snapshot) under a per-provider JSON file with a shared `base.*`\n * substructure so the CLI can detect when the on-disk artifact is stale\n * relative to the current CLI's build context.\n *\n * The invalidation key is `base.contextSha256`: a deterministic SHA-256\n * over every file in the build context (Dockerfile + scripts + baked\n * config), keyed by the file's relative path. Two CLIs with the same\n * staged runtime tree produce the same hash; an edit to any baked asset\n * — even a one-byte tweak to `custom-system-CLAUDE.md` — flips it.\n *\n * Checkpoints embed the captured `contextSha256` so restoring an older\n * checkpoint can warn the user that the baked layers predate the current\n * base image.\n */\n\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, resolve as pathResolve } from 'node:path';\n\nimport type { ProviderKind } from '@agentbox/config';\n\n/**\n * Providers that bake a `~/.agentbox/<provider>-prepared.json` artifact. The\n * built-in set is the config `ProviderKind`; the `(string & {})` arm keeps\n * autocomplete for those while also admitting an external plugin's open-string\n * provider name (a plugin manages its own prepared-state — see docs/provider-plugins.md).\n */\nexport type PreparedProviderKind = ProviderKind | (string & {});\n\n/**\n * The cross-provider record. `TImage` is the provider's opaque image\n * identifier: a string tag for docker/daytona, a numeric image id for\n * hetzner. The `TExtra` slot lets a provider attach provider-specific\n * fields (e.g. hetzner's `description` and `projects[]`) without forking\n * the whole shape.\n */\nexport interface PreparedBaseSnapshot<TImage = string, TExtra = unknown> {\n /** Schema version. Bumped when the on-disk shape changes incompatibly. */\n schema: number;\n base?: {\n /** Provider-opaque image identifier (docker tag | hetzner imageId | daytona snapshot name). */\n imageRef: TImage;\n /** Deterministic SHA-256 of the build context — the invalidation key. */\n contextSha256: string;\n /** Informational: CLI version that produced this artifact. */\n cliVersion: string;\n /** Informational: git short SHA injected at CLI build time (or 'dev'). */\n cliCommit?: string;\n /** ISO timestamp of bake completion. */\n createdAt: string;\n };\n /** Provider-specific extras (e.g. hetzner's per-project snapshot tier). */\n extras?: TExtra;\n}\n\nexport function preparedStatePathFor(provider: PreparedProviderKind): string {\n // The name lands in a filename; a plugin's open-string name could otherwise\n // carry a path separator. Provider names are `[a-z0-9-]` by convention — reject\n // anything else rather than resolve outside ~/.agentbox.\n if (!/^[A-Za-z0-9._-]+$/.test(provider)) {\n throw new Error(`invalid provider name for prepared-state: ${JSON.stringify(provider)}`);\n }\n return pathResolve(homedir(), '.agentbox', `${provider}-prepared.json`);\n}\n\n/**\n * Read the prepared-state file for `provider`. Returns `null` when the file\n * is missing, malformed, or carries a schema this code doesn't recognise —\n * callers treat all three as \"rebuild needed\". Sync so it can run from\n * non-async setup paths (mirrors the hetzner helper it generalises).\n */\nexport function readPreparedStateRaw(provider: PreparedProviderKind): unknown {\n const path = preparedStatePathFor(provider);\n if (!existsSync(path)) return null;\n try {\n return JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n return null;\n }\n}\n\n/**\n * Atomic write: write to `<path>.tmp` then rename. `mode: 0o600` because\n * the file is informational but lives alongside `secrets.env` — same dir,\n * same permissions hygiene.\n */\nexport function writePreparedStateRaw(provider: PreparedProviderKind, state: unknown): void {\n const path = preparedStatePathFor(provider);\n mkdirSync(dirname(path), { recursive: true });\n const body = JSON.stringify(state, null, 2) + '\\n';\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, body, { mode: 0o600 });\n renameSync(tmp, path);\n}\n\nexport async function sha256OfFile(path: string): Promise<string> {\n const buf = await readFile(path);\n return createHash('sha256').update(buf).digest('hex');\n}\n\nexport interface ContextFile {\n /**\n * Logical relative path. Used as the canonical key for hash determinism\n * — two stagings with identical contents but different absolute paths\n * must hash the same.\n */\n rel: string;\n /** Absolute path the file is read from. */\n abs: string;\n}\n\n/**\n * Deterministic hash over a set of context files. Entries are sorted by\n * `rel` then hashed as `<rel>\\0<sha256(file)>\\n` lines into a final SHA-256.\n *\n * - Sort order = determinism (the caller can pass files in any order).\n * - NUL separator = no collision between a `rel` ending in hex and the\n * following digest.\n * - Trailing newline per record = stable framing.\n *\n * Missing files raise — silently skipping would let a partial dev rebuild\n * stamp a hash that doesn't represent what's actually in the image.\n */\nexport async function computeContextSha256(files: ContextFile[]): Promise<string> {\n const sorted = [...files].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));\n const outer = createHash('sha256');\n for (const f of sorted) {\n const inner = await sha256OfFile(f.abs);\n outer.update(`${f.rel}\\0${inner}\\n`);\n }\n return outer.digest('hex');\n}\n\n/** Short form for log lines — first 12 hex chars of a sha256. */\nexport function shortFingerprint(sha: string): string {\n return sha.slice(0, 12);\n}\n\n/**\n * Fold the Claude install method into a base context fingerprint so switching\n * `box.claudeInstall` native↔npm forces a re-bake. `native` returns the base\n * hash unchanged — existing native snapshots keep their fingerprint and never\n * spuriously rebuild; only `npm` derives a distinct hash.\n */\nexport function claudeInstallFingerprint(baseSha: string, mode: 'native' | 'npm'): string {\n if (mode === 'native') return baseSha;\n return createHash('sha256').update(`${baseSha}\\0claude-install=npm`).digest('hex');\n}\n\n/**\n * CLI version stamps set by `apps/cli/src/index.ts` at startup via env vars\n * (the values themselves come from tsup's build-time `define`). Providers\n * record them onto prepared-state files and checkpoint manifests so a stale\n * artifact carries a human-readable hint about which CLI built it.\n *\n * Fallbacks cover the unit-test and unbundled-dev paths (the CLI never\n * loaded, env unset). `unknown` is a sentinel — never a real version.\n */\nexport interface CliStamp {\n cliVersion: string;\n cliCommit: string;\n}\n\nexport function readCliStamp(): CliStamp {\n return {\n cliVersion: process.env.AGENTBOX_CLI_VERSION ?? 'unknown',\n cliCommit: process.env.AGENTBOX_CLI_COMMIT ?? 'unknown',\n };\n}\n\n/**\n * Canonical map of files that go into the Docker base image build context\n * — every file `Dockerfile.box` COPYs, plus the Dockerfile itself. Two\n * layouts resolve the same logical entries:\n *\n * - staged: `<contextDir>/<staged>` (production CLI runtime + dev with `apps/cli/runtime/docker`)\n * - dev: `<sandboxDockerRoot>/<dev>` (workspace dev, no staged tree)\n *\n * Shared across providers because:\n * - sandbox-docker uses it to fingerprint its locally-built image.\n * - sandbox-daytona uses it to fingerprint the snapshot it bakes from the\n * same Dockerfile.box + the daytona-specific CLAUDE.md overlay.\n *\n * If you add a COPY line to `Dockerfile.box`, add the file here AND in\n * `apps/cli/scripts/stage-runtime.mjs` — failure to do so means the image\n * won't get re-built when that file changes.\n */\nexport const DOCKER_CONTEXT_FILE_MAP: Record<string, { staged: string; dev: string }> = {\n 'Dockerfile.box': { staged: 'Dockerfile.box', dev: 'Dockerfile.box' },\n 'ctl/bin.cjs': {\n staged: 'packages/ctl/dist/bin.cjs',\n dev: '../ctl/dist/bin.cjs',\n },\n 'share/agentbox-setup/SKILL.md': {\n staged: 'apps/cli/share/agentbox-setup/SKILL.md',\n dev: '../../apps/cli/share/agentbox-setup/SKILL.md',\n },\n 'scripts/agentbox-vnc-start': {\n staged: 'packages/sandbox-docker/scripts/agentbox-vnc-start',\n dev: 'scripts/agentbox-vnc-start',\n },\n 'scripts/agentbox-dockerd-start': {\n staged: 'packages/sandbox-docker/scripts/agentbox-dockerd-start',\n dev: 'scripts/agentbox-dockerd-start',\n },\n 'scripts/agentbox-checkpoint-cleanup': {\n staged: 'packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup',\n dev: 'scripts/agentbox-checkpoint-cleanup',\n },\n 'scripts/agentbox-open': {\n staged: 'packages/sandbox-docker/scripts/agentbox-open',\n dev: 'scripts/agentbox-open',\n },\n 'scripts/custom-system-CLAUDE.md': {\n staged: 'packages/sandbox-docker/scripts/custom-system-CLAUDE.md',\n dev: 'scripts/custom-system-CLAUDE.md',\n },\n 'scripts/claude-managed-settings.json': {\n staged: 'packages/sandbox-docker/scripts/claude-managed-settings.json',\n dev: 'scripts/claude-managed-settings.json',\n },\n 'scripts/agentbox-codex-hooks.json': {\n staged: 'packages/sandbox-docker/scripts/agentbox-codex-hooks.json',\n dev: 'scripts/agentbox-codex-hooks.json',\n },\n};\n\n/**\n * Resolve every entry in `fileMap` to an absolute path. Tries `<contextDir>/<staged>`\n * first; falls back to `<devRoot>/<dev>`. Returns `null` if any required file\n * is missing — callers treat that as \"can't fingerprint\" and skip the\n * cache-hit shortcut. Pure (no I/O beyond `existsSync`), so safe for use\n * from the provider's prepare path.\n */\nexport function resolveContextFilesFrom(\n fileMap: Record<string, { staged: string; dev: string }>,\n opts: { contextDir: string; devRoot: string },\n): ContextFile[] | null {\n const out: ContextFile[] = [];\n for (const [rel, paths] of Object.entries(fileMap)) {\n const candidates = [\n pathResolve(opts.contextDir, paths.staged),\n pathResolve(opts.devRoot, paths.dev),\n ];\n const hit = candidates.find((p) => existsSync(p));\n if (!hit) return null;\n out.push({ rel, abs: hit });\n }\n return out;\n}\n","/**\n * Docker provider's `~/.agentbox/docker-prepared.json` reader/writer + the\n * build-context fingerprint that drives base-image invalidation.\n *\n * The fingerprint is a SHA-256 over every file `docker build` would COPY\n * into the image — Dockerfile + scripts + baked config files. Two CLIs\n * with identical staged runtime trees produce the same hash; a one-byte\n * edit to any baked asset flips it, which is the signal `ensureImage()`\n * uses to rebuild instead of reusing the cached image.\n */\n\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n computeContextSha256,\n DOCKER_CONTEXT_FILE_MAP,\n readCliStamp,\n readPreparedStateRaw,\n resolveContextFilesFrom,\n writePreparedStateRaw,\n type ContextFile,\n type PreparedBaseSnapshot,\n} from '@agentbox/sandbox-core';\nimport { BUILD_CONTEXT_DIR, DEFAULT_BOX_IMAGE, DOCKERFILE_PATH } from './image.js';\n\nconst SCHEMA = 1 as const;\n\nexport type PreparedDockerState = PreparedBaseSnapshot<string, never>;\n\n/**\n * Resolve every fingerprint input to an absolute path. The canonical file\n * list lives in `@agentbox/sandbox-core` (DOCKER_CONTEXT_FILE_MAP) so the\n * daytona provider can hash the same inputs without depending on this\n * package. Two layouts are tried in order, mirroring `resolveDockerBuild()`\n * in `image.ts`:\n * 1. Build context dir (staged runtime / env override).\n * 2. Sandbox-docker package root (dev fallback).\n *\n * Returns `null` when *any* required file is missing — callers treat that\n * as \"can't fingerprint\" and skip the cache-hit shortcut (always rebuild).\n */\nexport function resolveContextFiles(opts: { contextDir?: string } = {}): ContextFile[] | null {\n const ctx = opts.contextDir ?? BUILD_CONTEXT_DIR;\n const here = dirname(fileURLToPath(import.meta.url));\n // sandbox-docker's package root = parent of src/ or parent of dist/.\n const packageRoot = resolve(here, '..');\n return resolveContextFilesFrom(DOCKER_CONTEXT_FILE_MAP, {\n contextDir: ctx,\n devRoot: packageRoot,\n });\n}\n\nexport interface ResolvedFingerprint {\n contextSha256: string;\n /** Files that fed the hash (in canonical sorted order). */\n files: ContextFile[];\n}\n\nexport async function computeDockerContextFingerprint(opts: {\n contextDir?: string;\n} = {}): Promise<ResolvedFingerprint | null> {\n const files = resolveContextFiles(opts);\n if (!files) return null;\n return { contextSha256: await computeContextSha256(files), files };\n}\n\nexport function readPreparedDockerState(): PreparedDockerState | null {\n const raw = readPreparedStateRaw('docker');\n if (raw === null || typeof raw !== 'object') return null;\n const parsed = raw as Partial<PreparedDockerState>;\n if (parsed.schema !== SCHEMA) return null;\n return { schema: SCHEMA, base: parsed.base };\n}\n\nexport function writePreparedDockerState(opts: {\n imageRef?: string;\n contextSha256: string;\n}): void {\n const stamp = readCliStamp();\n const state: PreparedDockerState = {\n schema: SCHEMA,\n base: {\n imageRef: opts.imageRef ?? DEFAULT_BOX_IMAGE,\n contextSha256: opts.contextSha256,\n cliVersion: stamp.cliVersion,\n cliCommit: stamp.cliCommit,\n createdAt: new Date().toISOString(),\n },\n };\n writePreparedStateRaw('docker', state);\n}\n\n/** Convenience for `ensureImage` and `prepare` — true when the stamped fingerprint matches. */\nexport function preparedMatches(state: PreparedDockerState | null, current: string): boolean {\n return state?.base?.contextSha256 === current;\n}\n\n/** Re-export so callers don't reach into image.ts just for the Dockerfile path. */\nexport { DOCKERFILE_PATH };\n","import { execa } from 'execa';\nimport { existsSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, resolve } from 'node:path';\nimport { claudeInstallFingerprint } from '@agentbox/sandbox-core';\n\nexport const DEFAULT_BOX_IMAGE = 'agentbox/box:dev';\n\n/**\n * Resolve the effective `box.claudeInstall` for the current project. Docker\n * builds its image lazily at create time, so every `ensureImage` path must\n * agree on the mode or a native rebuild would clobber an npm-baked image (and\n * vice-versa). Lazy-imported to keep the module load cheap; falls back to\n * `native` if config can't be read.\n */\nasync function resolveClaudeInstallMode(): Promise<'native' | 'npm'> {\n try {\n const { loadEffectiveConfig } = await import('@agentbox/config');\n const cfg = await loadEffectiveConfig(process.cwd());\n return cfg.effective.box.claudeInstall;\n } catch {\n return 'native';\n }\n}\n\n/**\n * Public registry repo the box image is published to (see\n * `.github/workflows/box-image.yml`). The CLI pulls a fingerprint-tagged\n * image from here on first use instead of building locally — a multi-minute\n * build collapses to a `docker pull`. An empty registry (config override)\n * disables pulling and always builds.\n */\nexport const BOX_IMAGE_REGISTRY = 'ghcr.io/madarco/agentbox/box';\n\n/**\n * The pull target for a given build-context fingerprint. The tag *is* the\n * content identity: a local staged context that matches a published build\n * has the same sha, so a pull hit can be retagged to `agentbox/box:dev` and\n * stamped into docker-prepared.json without risk of a stale image (a locally\n * edited context has a different sha, its tag 404s, and we build instead).\n */\nexport function registryRefForSha(sha: string, registry: string = BOX_IMAGE_REGISTRY): string {\n return `${registry}:sha-${sha.slice(0, 16)}`;\n}\n\nconst here = dirname(fileURLToPath(import.meta.url));\n\n// The Dockerfile's COPY lines reference monorepo-relative paths\n// (packages/ctl/dist/bin.cjs, apps/cli/share/..., packages/sandbox-docker/scripts/*),\n// so the build context must be a dir containing that tree.\n//\n// Resolution order:\n// 0. AGENTBOX_DOCKER_CONTEXT env override (dir holding Dockerfile.box).\n// 1. Staged context shipped with the bundled `agent-box` package: this\n// module is bundled into the CLI at <root>/dist, the stage step mirrors\n// the COPY tree at <root>/runtime/docker (sibling of dist/, uniform in\n// dev and when installed).\n// 2. Legacy monorepo: Dockerfile.box at the sandbox-docker package root,\n// build context = monorepo root.\nfunction resolveDockerBuild(): { dockerfile: string; context: string } {\n const override = process.env.AGENTBOX_DOCKER_CONTEXT;\n if (override && existsSync(resolve(override, 'Dockerfile.box'))) {\n return { dockerfile: resolve(override, 'Dockerfile.box'), context: override };\n }\n const staged = resolve(here, '..', 'runtime', 'docker');\n if (existsSync(resolve(staged, 'Dockerfile.box'))) {\n return { dockerfile: resolve(staged, 'Dockerfile.box'), context: staged };\n }\n // Legacy: src/ (or the unbundled package dist/) is one level under the\n // package root; the monorepo root is two more up.\n const packageRoot = resolve(here, '..');\n return {\n dockerfile: resolve(packageRoot, 'Dockerfile.box'),\n context: resolve(packageRoot, '..', '..'),\n };\n}\n\nconst { dockerfile: DOCKERFILE_PATH_RESOLVED, context: BUILD_CONTEXT_DIR_RESOLVED } =\n resolveDockerBuild();\nexport const DOCKERFILE_PATH = DOCKERFILE_PATH_RESOLVED;\nexport const BUILD_CONTEXT_DIR = BUILD_CONTEXT_DIR_RESOLVED;\n\nexport async function imageExists(ref: string): Promise<boolean> {\n const result = await execa('docker', ['image', 'inspect', ref], { reject: false });\n return result.exitCode === 0;\n}\n\n/**\n * Attempt `docker pull <target>`. Returns true on success, false on any\n * failure (missing tag, offline, auth) — callers fall back to a local build.\n * Never throws. Single attempt: a missing tag is the expected \"build locally\"\n * signal, not a transient error worth retrying.\n */\nexport async function pullImage(\n target: string,\n opts: { onProgress?: (line: string) => void } = {},\n): Promise<boolean> {\n const subprocess = execa('docker', ['pull', target], {\n stderr: 'pipe',\n stdout: 'pipe',\n reject: false,\n });\n let heartbeat: NodeJS.Timeout | undefined;\n if (opts.onProgress) {\n let lastLineAt = Date.now();\n const forward = (chunk: Buffer | string): void => {\n lastLineAt = Date.now();\n const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (line.length > 0) opts.onProgress?.(line);\n }\n };\n subprocess.stdout?.on('data', forward);\n subprocess.stderr?.on('data', forward);\n // Piped (non-TTY) `docker pull` prints nothing between the last\n // \"Download complete\" and each \"Pull complete\" — the entire extraction\n // phase is silent, which for a multi-GB image reads as a hang. Emit a\n // keepalive so the create spinner keeps moving.\n heartbeat = setInterval(() => {\n if (Date.now() - lastLineAt >= 20_000) {\n opts.onProgress?.(`still extracting ${target} — large layers can take a few minutes`);\n }\n }, 20_000);\n }\n try {\n const result = await subprocess;\n return result.exitCode === 0;\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n }\n}\n\nexport async function tagImage(source: string, target: string): Promise<void> {\n await execa('docker', ['tag', source, target]);\n}\n\nexport interface ImageInfo {\n /** Image ref (e.g. `agentbox/box:dev`). */\n ref: string;\n /** True when the engine has the image locally. */\n exists: boolean;\n /** Image size in bytes, when known. */\n sizeBytes?: number;\n /** ISO-8601 creation time, when known. */\n createdAt?: string;\n}\n\n/**\n * Read-only inspect of a Docker image. Used by `agentbox prepare` (no-args\n * status mode) to surface base-image state. Never throws — returns\n * `{ exists: false }` on any error so the status command works even when\n * the docker daemon is unreachable.\n */\nexport async function imageInfo(ref: string = DEFAULT_BOX_IMAGE): Promise<ImageInfo> {\n const result = await execa(\n 'docker',\n ['image', 'inspect', '--format', '{{.Size}}|{{.Created}}', ref],\n { reject: false },\n );\n if (result.exitCode !== 0) return { ref, exists: false };\n const [sizeStr, createdAt] = result.stdout.trim().split('|');\n const sizeBytes = sizeStr ? Number.parseInt(sizeStr, 10) : NaN;\n return {\n ref,\n exists: true,\n sizeBytes: Number.isFinite(sizeBytes) ? sizeBytes : undefined,\n createdAt: createdAt && createdAt.length > 0 ? createdAt : undefined,\n };\n}\n\nexport interface BuildImageOptions {\n ref?: string;\n dockerfile?: string;\n contextDir?: string;\n /** `--build-arg K=V` pairs forwarded to `docker build` (e.g. AGENTBOX_CLAUDE_INSTALL). */\n buildArgs?: Record<string, string>;\n onProgress?: (line: string) => void;\n}\n\nexport async function buildImage(opts: BuildImageOptions = {}): Promise<string> {\n const ref = opts.ref ?? DEFAULT_BOX_IMAGE;\n const dockerfile = opts.dockerfile ?? DOCKERFILE_PATH;\n const contextDir = opts.contextDir ?? BUILD_CONTEXT_DIR;\n\n // Dogfood path: when building from inside an agentbox (docker-in-docker),\n // the default bridge network can't bind-mount /proc/<pid>/ns/net for the\n // build container, breaking any RUN that needs network (e.g. apt, curl).\n // Falling back to host networking sidesteps the missing capability.\n const args = ['build', '-t', ref, '-f', dockerfile];\n for (const [k, v] of Object.entries(opts.buildArgs ?? {})) {\n args.push('--build-arg', `${k}=${v}`);\n }\n args.push(contextDir);\n if (process.env.AGENTBOX === '1') {\n args.splice(1, 0, '--network=host');\n }\n\n const subprocess = execa('docker', args, {\n stderr: 'pipe',\n stdout: 'pipe',\n });\n\n if (opts.onProgress) {\n const forward = (chunk: Buffer | string): void => {\n const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (line.length > 0) opts.onProgress?.(line);\n }\n };\n subprocess.stdout?.on('data', forward);\n subprocess.stderr?.on('data', forward);\n }\n\n await subprocess;\n return ref;\n}\n\nexport interface PullOrBuildOptions {\n onProgress?: (line: string) => void;\n /** Dockerfile path. Defaults to `Dockerfile.box` next to this package. */\n dockerfile?: string;\n /** Build context directory. Defaults to the staged runtime / monorepo root. */\n contextDir?: string;\n /** Try the registry before building. Defaults to true. */\n allowPull?: boolean;\n /** Registry repo to pull from. Defaults to `BOX_IMAGE_REGISTRY`; empty disables pulling. */\n registry?: string;\n /** `--build-arg K=V` pairs forwarded to the local `docker build` (ignored on a registry pull). */\n buildArgs?: Record<string, string>;\n}\n\n/**\n * Make `ref` present locally, preferring a registry pull over a local build.\n *\n * When `fingerprint` is non-null and pulling is allowed, pull the\n * fingerprint-tagged image and retag it to `ref`; on a miss (or when pulling\n * is disabled / unfingerprintable) build from the staged context. Either way,\n * a known fingerprint is stamped into docker-prepared.json so the next\n * `ensureImage()` treats this as a cache hit.\n */\nexport async function pullOrBuild(\n ref: string,\n fingerprint: { contextSha256: string } | null,\n opts: PullOrBuildOptions = {},\n): Promise<{ source: 'pulled' | 'built' }> {\n const { writePreparedDockerState } = await import('./prepared-state.js');\n const registry = opts.registry ?? BOX_IMAGE_REGISTRY;\n const allowPull = opts.allowPull !== false;\n\n if (allowPull && registry && fingerprint) {\n const target = registryRefForSha(fingerprint.contextSha256, registry);\n opts.onProgress?.(`[image] pulling ${target}`);\n if (await pullImage(target, { onProgress: opts.onProgress })) {\n await tagImage(target, ref);\n writePreparedDockerState({ imageRef: ref, contextSha256: fingerprint.contextSha256 });\n opts.onProgress?.(`[image] pulled ${target} -> ${ref}`);\n return { source: 'pulled' };\n }\n opts.onProgress?.(`[image] registry miss, building ${ref} locally`);\n }\n\n await buildImage({\n ref,\n dockerfile: opts.dockerfile,\n contextDir: opts.contextDir,\n buildArgs: opts.buildArgs,\n onProgress: opts.onProgress,\n });\n if (fingerprint) {\n writePreparedDockerState({ imageRef: ref, contextSha256: fingerprint.contextSha256 });\n }\n return { source: 'built' };\n}\n\nexport interface EnsureImageOptions {\n onProgress?: (line: string) => void;\n /** Dockerfile path. Defaults to `Dockerfile.box` next to this package. */\n dockerfile?: string;\n /** Build context directory. Defaults to the monorepo root. */\n contextDir?: string;\n /** Try the registry before building. Defaults to true. */\n allowPull?: boolean;\n /** Registry repo to pull from. Defaults to `BOX_IMAGE_REGISTRY`; empty disables pulling. */\n registry?: string;\n /**\n * How Claude Code is installed into the image. Folded into the build-context\n * fingerprint so a mode switch rebuilds (and an npm image isn't clobbered by\n * a native rebuild). Defaults to the resolved `box.claudeInstall`.\n */\n claudeInstall?: 'native' | 'npm';\n}\n\nexport async function ensureImage(\n ref: string = DEFAULT_BOX_IMAGE,\n opts: EnsureImageOptions = {},\n): Promise<{ ref: string; built: boolean; reason?: string }> {\n // Lazy import: prepared-state imports back into image.ts for the default\n // DOCKERFILE_PATH/BUILD_CONTEXT_DIR constants, so loading it at top-level\n // would create a circular ESM init order.\n const { computeDockerContextFingerprint, readPreparedDockerState, preparedMatches } =\n await import('./prepared-state.js');\n\n const claudeInstall = opts.claudeInstall ?? (await resolveClaudeInstallMode());\n const rawFingerprint = await computeDockerContextFingerprint({\n contextDir: opts.contextDir,\n });\n // Fold the install mode into the sha so native↔npm are distinct cache\n // identities (`native` leaves the hash unchanged).\n const fingerprint = rawFingerprint\n ? {\n ...rawFingerprint,\n contextSha256: claudeInstallFingerprint(rawFingerprint.contextSha256, claudeInstall),\n }\n : null;\n const prepared = readPreparedDockerState();\n const exists = await imageExists(ref);\n\n let reason: string | undefined;\n if (!exists) {\n reason = `image ${ref} not present`;\n } else if (!fingerprint) {\n // Couldn't enumerate the context (partial dev rebuild?). Don't rebuild\n // unconditionally — that would surprise users mid-iteration. Trust the\n // image-exists check and leave the prepared file untouched.\n return { ref, built: false, reason: 'image present (fingerprint skipped)' };\n } else if (!prepared) {\n reason = 'no docker-prepared.json on disk';\n } else if (!preparedMatches(prepared, fingerprint.contextSha256)) {\n reason =\n `build context changed (was ${prepared.base?.contextSha256?.slice(0, 12) ?? '<none>'}, ` +\n `now ${fingerprint.contextSha256.slice(0, 12)})`;\n }\n\n if (!reason) {\n return { ref, built: false, reason: 'image up to date' };\n }\n\n opts.onProgress?.(`[image] ${ref}: ${reason}`);\n const npm = claudeInstall === 'npm';\n const { source } = await pullOrBuild(ref, fingerprint, {\n onProgress: opts.onProgress,\n dockerfile: opts.dockerfile,\n contextDir: opts.contextDir,\n // The published GHCR image is native-only, so npm mode must build locally.\n allowPull: npm ? false : opts.allowPull,\n registry: opts.registry,\n buildArgs: npm ? { AGENTBOX_CLAUDE_INSTALL: 'npm' } : undefined,\n });\n return { ref, built: source === 'built', reason };\n}\n\n/**\n * Read-only freshness classification of the docker base image, for surfaces\n * (hub API, tray) that want to announce an upcoming bake without triggering\n * it. `unknown` means \"couldn't fingerprint\" and MUST stay inert — the\n * matching `ensureImage` path trusts the existing image and does not rebuild.\n */\nexport type DockerBaseFreshness =\n | { state: 'fresh' }\n | { state: 'unknown' }\n | { state: 'unprepared' }\n | { state: 'stale'; reason: string };\n\n/**\n * Pure decision core shared by `evaluateDockerBaseFreshness`. Mirrors\n * `ensureImage`'s rebuild predicate exactly — if the two ever disagree, the\n * freshness surfaces would announce a bake that create then skips (or miss\n * one it performs). `stampedSha` is `docker-prepared.json`'s fingerprint,\n * null when the stamp is missing/invalid.\n */\nexport function classifyDockerBaseFreshness(input: {\n imagePresent: boolean;\n fingerprint: string | null;\n stampedSha: string | null;\n}): DockerBaseFreshness {\n if (!input.imagePresent) return { state: 'unprepared' };\n if (!input.fingerprint) return { state: 'unknown' };\n if (!input.stampedSha) return { state: 'stale', reason: 'no docker-prepared.json on disk' };\n if (input.stampedSha !== input.fingerprint) {\n return {\n state: 'stale',\n reason:\n `build context changed (was ${input.stampedSha.slice(0, 12)}, ` +\n `now ${input.fingerprint.slice(0, 12)})`,\n };\n }\n return { state: 'fresh' };\n}\n\n/**\n * Cheap live check: would `ensureImage` bake on the next create? The only\n * docker work is one `docker image inspect`; the rest hashes the ~15 build\n * context files. Never builds, pulls, or writes the prepared stamp.\n */\nexport async function evaluateDockerBaseFreshness(\n opts: { ref?: string; claudeInstall?: 'native' | 'npm'; contextDir?: string } = {},\n): Promise<DockerBaseFreshness> {\n // Lazy import for the same circular-init reason as in ensureImage above.\n const { computeDockerContextFingerprint, readPreparedDockerState } =\n await import('./prepared-state.js');\n const ref = opts.ref ?? DEFAULT_BOX_IMAGE;\n const imagePresent = await imageExists(ref);\n if (!imagePresent) return { state: 'unprepared' };\n const claudeInstall = opts.claudeInstall ?? (await resolveClaudeInstallMode());\n const raw = await computeDockerContextFingerprint({ contextDir: opts.contextDir });\n return classifyDockerBaseFreshness({\n imagePresent,\n fingerprint: raw ? claudeInstallFingerprint(raw.contextSha256, claudeInstall) : null,\n stampedSha: readPreparedDockerState()?.base?.contextSha256 ?? null,\n });\n}\n\n"],"mappings":";;;AIAA,SAAS,mBAAmB;AKY5B,SAAS,gBAAgB;AACzB,SAAS,UAAU,SAAS,cAAAA,aAAY,WAAW,WAAAC,UAAS,WAAW;ATNvE,IAAM,qBAAoC;EACxC,MAAM;;;;EAIN,UAAU,gBAAgB,UAAU;AAClC,QAAI,CAAC,eAAgB,QAAO,CAAC,GAAG,QAAQ;AACxC,WAAO,CAAC,gBAAgB,GAAG,QAAQ;EACrC;AACF;AAKA,IAAM,gBAA+B;EACnC,MAAM;EACN,UAAU,gBAAgB,UAAU;AAClC,QAAI,CAAC,eAAgB,QAAO,CAAC,GAAG,QAAQ;AACxC,WAAO,CAAC,gBAAgB,GAAG,QAAQ;EACrC;AACF;AAIA,IAAM,mBAAkC;EACtC,MAAM;EACN,UAAU,gBAAgB,UAAU;AAClC,QAAI,CAAC,eAAgB,QAAO,CAAC,GAAG,QAAQ;AACxC,WAAO,CAAC,gBAAgB,GAAG,QAAQ;EACrC;AACF;AAEO,SAAS,qBAAqB,MAAgC;AACnE,MAAI,SAAS,cAAe,QAAO;AACnC,MAAI,SAAS,QAAS,QAAO;AAC7B,MAAI,SAAS,WAAY,QAAO;AAChC,QAAM,IAAI,MAAM,uBAAuB,OAAO,IAAI,CAAC,EAAE;AACvD;AE/BO,IAAM,mBAAmB;EAC9B;EACA;EACA;EACA;EACA;;;;;;EAMA;AACF;AAIA,IAAM,kBAAkB,IAAI,IAAY,gBAAgB;AAYjD,IAAM,eAAN,cAA2B,MAAM;EACtC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;EACd;AACF;AAEA,IAAM,iBAAiB;AAQhB,SAAS,uBACd,MACA,SACA,QACQ;AACR,SAAO,KAAK,QAAQ,gBAAgB,CAAC,OAAO,SAAiB;AAC3D,QAAI,CAAC,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QAAQ;IACR,MAAM;MACJ,UAAU,KAAK,YAAY;MAC3B,eAAe,KAAK;MACpB,YAAY,MAAM;MAClB,WAAW,MAAM;MACjB,YAAW,oBAAI,KAAK,GAAE,YAAY;IACpC;EACF;AACA,wBAAsB,UAAU,KAAK;AACvC;AAGO,SAAS,gBAAgB,OAAmC,SAA0B;AAC3F,SAAO,OAAO,MAAM,kBAAkB;AACxC;","names":["isAbsolute","resolve","resolve","dirname","stat","join","homedir","mkdir","readFile","execa","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","dirname","resolve","mkdir","open","readFile","rename","rm","stat","writeFile","join","delay","basename","join","homedir","mkdtemp","rm","tmpdir","execa","readdir","stat","realpath","mkdir","readFile","writeFile","dirname","createHash","basename","copyFile","relative","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","resolve","join","homedir","EMPTY","LOCK_STALE_MS","LOCK_ACQUIRE_TIMEOUT_MS","LOCK_RETRY_MS","mkdir","dirname","open","stat","rm","delay","normalize","existsSync","readFileSync","readFile","EMPTY","mkdir","dirname","writeFile","rename","join","basename","join","homedir","execa","mkdtemp","join","tmpdir","rm","stat","readdir","realpath","pathExists","readFile","mkdir","dirname","writeFile","createHash","basename","BOX_WORKSPACE","relative","copyFile","existsSync","readFileSync","mkdirSync","writeFileSync","renameSync","createHash","existsSync","dirname","resolve","fileURLToPath","execa","existsSync","dirname","resolve","dirname","existsSync","resolve","execa","writePreparedDockerState","computeDockerContextFingerprint","readPreparedDockerState","preparedMatches","here","fileURLToPath"]}