@madarco/agentbox 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +44 -0
- package/README.md +1 -1
- package/dist/{_cloud-attach-7WRQH6XZ.js → _cloud-attach-WDGM6FL5.js} +4 -4
- package/dist/{chunk-UIFL7F2G.js → chunk-26IKZRTT.js} +2 -2
- package/dist/{chunk-DJQMK4RN.js → chunk-HR7NHH5J.js} +14 -9
- package/dist/chunk-HR7NHH5J.js.map +1 -0
- package/dist/{chunk-K5KOLYIL.js → chunk-IDH5A4RR.js} +2 -2
- package/dist/{chunk-ZY7M7MXH.js → chunk-JE6UI5YR.js} +10 -10
- package/dist/{chunk-7ZZAZPYX.js → chunk-KWOEUFVA.js} +2 -2
- package/dist/{chunk-BA2VLJVU.js → chunk-LL7NCMUU.js} +3 -3
- package/dist/{chunk-I2OAJS3L.js → chunk-NEF6MDJO.js} +4 -4
- package/dist/{chunk-I2OAJS3L.js.map → chunk-NEF6MDJO.js.map} +1 -1
- package/dist/{dist-YA7EXBGG.js → chunk-SJ75AIA2.js} +486 -92
- package/dist/chunk-SJ75AIA2.js.map +1 -0
- package/dist/{chunk-PK2QF4IR.js → chunk-UJEH2NJT.js} +27 -14
- package/dist/chunk-UJEH2NJT.js.map +1 -0
- package/dist/{chunk-DQHMDDAT.js → chunk-V5XXJH63.js} +2 -2
- package/dist/{dist-DTNYMBQ5.js → dist-FTKS2GI4.js} +5 -5
- package/dist/{dist-5IICYSR6.js → dist-KQTMCVME.js} +5 -5
- package/dist/{dist-5IICYSR6.js.map → dist-KQTMCVME.js.map} +1 -1
- package/dist/{dist-AR5CHRSV.js → dist-O3LKOIE7.js} +5 -5
- package/dist/{dist-POVRY7HO.js → dist-OO52HARR.js} +3 -3
- package/dist/{dist-K4LNH3EC.js → dist-TSFVB7AI.js} +5 -5
- package/dist/{dist-XYY6SIKG.js → dist-WVYAURMF.js} +5 -5
- package/dist/dist-Z6L5MM5D.js +46 -0
- package/dist/index.js +401 -219
- package/dist/index.js.map +1 -1
- package/dist/{prepared-state-75DIZ55S-W6NU3S3B.js → prepared-state-75DIZ55S-TNJXWMXV.js} +2 -2
- package/dist/prepared-state-75DIZ55S-TNJXWMXV.js.map +1 -0
- package/package.json +8 -8
- package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
- package/runtime/hub/apps/hub/.next/app-path-routes-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
- package/runtime/hub/apps/hub/.next/routes-manifest.json +22 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route.js +2 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route.js +2 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_hosts_route_actions_0b_404_.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0web_next-internal_server_app_(dashboard)_api_v1_hosts_[alias]_route_actions_0swypy5.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_hosts_[alias]_bake_route_actions_1-_pu3n.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a7djvw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0bmro0b._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0t4qmv-._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xh14bo._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13ioh5z._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4xycg._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hqla7-._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1md9kdw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_1bng7w9._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/apps_hub_app_(dashboard)_api_v1_lib_openapi_ts_1yokmzt._.js +14 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_1uccfbf._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_03s-ah2._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0r4px38._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_18w2zeh._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_0od97-d._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_boxes_components_box-table_tsx_0a9pyn_._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_settings_page_tsx_0hv6n82._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/functions-config-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
- package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
- package/runtime/hub/apps/hub/.next/static/chunks/0xdtiy_m2ygv8.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/1_ur0im1g7_s9.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/26rwu1f2gzemi.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/3v6kx35_lwjs8.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/{3dfjrxx-dy644.css → 42uysd_max-yq.css} +1 -1
- package/runtime/hub/apps/hub/.next/static/chunks/44j61g8lm9nvw.js +1 -0
- package/runtime/hub/apps/hub/{chunk-BARD2DI6.js → chunk-EHBJKZCL.js} +13 -8
- package/runtime/hub/apps/hub/{chunk-4QY2VZCF.js → chunk-RXYOWSSN.js} +19 -13
- package/runtime/hub/apps/hub/{chunk-XZZXPEVV.js → chunk-YJ5MJOXK.js} +1 -1
- package/runtime/hub/apps/hub/{dist-3ENKQN5G.js → dist-3I7KUI6W.js} +3 -3
- package/runtime/hub/apps/hub/{dist-WAZKGVYL.js → dist-6FPPUSWZ.js} +2 -2
- package/runtime/hub/apps/hub/{dist-NNBELNA7.js → dist-DX6IYMAH.js} +300 -109
- package/runtime/hub/apps/hub/{dist-RJJ2SDYO.js → dist-G6TXUSPZ.js} +3 -3
- package/runtime/hub/apps/hub/{dist-AE6IV4FV.js → dist-GTVVXCBP.js} +3 -3
- package/runtime/hub/apps/hub/{dist-6VGJOQYK.js → dist-JG45OFT2.js} +3 -3
- package/runtime/hub/apps/hub/{dist-TU7D6UTB.js → dist-LYDHYTP2.js} +3 -3
- package/runtime/hub/apps/hub/{prepared-state-75DIZ55S-NYEDSU2U.js → prepared-state-75DIZ55S-2IFNUHHM.js} +1 -1
- package/runtime/hub/apps/hub/server.js +136 -19
- package/dist/chunk-DJQMK4RN.js.map +0 -1
- package/dist/chunk-PK2QF4IR.js.map +0 -1
- package/dist/chunk-ZYKNSHOH.js +0 -259
- package/dist/chunk-ZYKNSHOH.js.map +0 -1
- package/dist/dist-YA7EXBGG.js.map +0 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bqbkd5._.js +0 -14
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qa4a0v._.js +0 -14
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_09gdzmo._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0tgpglr._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_1laion6._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_0b_hsjl._.js +0 -3
- package/runtime/hub/apps/hub/.next/static/chunks/1c5w3kqosumog.js +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/1o3ot_9-8jgzc.js +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/1z4elhg8gyq98.js +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/3uq9hf-roasav.js +0 -1
- /package/dist/{_cloud-attach-7WRQH6XZ.js.map → _cloud-attach-WDGM6FL5.js.map} +0 -0
- /package/dist/{chunk-UIFL7F2G.js.map → chunk-26IKZRTT.js.map} +0 -0
- /package/dist/{chunk-K5KOLYIL.js.map → chunk-IDH5A4RR.js.map} +0 -0
- /package/dist/{chunk-ZY7M7MXH.js.map → chunk-JE6UI5YR.js.map} +0 -0
- /package/dist/{chunk-7ZZAZPYX.js.map → chunk-KWOEUFVA.js.map} +0 -0
- /package/dist/{chunk-BA2VLJVU.js.map → chunk-LL7NCMUU.js.map} +0 -0
- /package/dist/{chunk-DQHMDDAT.js.map → chunk-V5XXJH63.js.map} +0 -0
- /package/dist/{dist-DTNYMBQ5.js.map → dist-FTKS2GI4.js.map} +0 -0
- /package/dist/{dist-AR5CHRSV.js.map → dist-O3LKOIE7.js.map} +0 -0
- /package/dist/{dist-POVRY7HO.js.map → dist-OO52HARR.js.map} +0 -0
- /package/dist/{dist-K4LNH3EC.js.map → dist-TSFVB7AI.js.map} +0 -0
- /package/dist/{dist-XYY6SIKG.js.map → dist-WVYAURMF.js.map} +0 -0
- /package/dist/{prepared-state-75DIZ55S-W6NU3S3B.js.map → dist-Z6L5MM5D.js.map} +0 -0
- /package/runtime/hub/apps/hub/.next/static/{mrhWWwzD3oh05le9SRnlA → S-yw9-SVffiEHRGm85NzP}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{mrhWWwzD3oh05le9SRnlA → S-yw9-SVffiEHRGm85NzP}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{mrhWWwzD3oh05le9SRnlA → S-yw9-SVffiEHRGm85NzP}/_ssgManifest.js +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../packages/sandbox-remote-docker/src/target.ts","../../../packages/sandbox-remote-docker/src/hosts-registry.ts","../../../packages/sandbox-remote-docker/src/remote-docker.ts","../../../packages/sandbox-remote-docker/src/image.ts","../../../packages/sandbox-remote-docker/src/prepared-state.ts","../../../packages/sandbox-remote-docker/src/prepare.ts","../../../packages/sandbox-remote-docker/src/index.ts","../../../packages/sandbox-remote-docker/src/backend.ts","../../../packages/sandbox-remote-docker/src/build-attach.ts","../../../packages/sandbox-remote-docker/src/box-ssh.ts","../../../packages/sandbox-remote-docker/src/provider-module.ts","../../../packages/sandbox-remote-docker/src/host-setup.ts"],"sourcesContent":["/**\n * The remote-docker addressing model.\n *\n * A box lives on *some* remote engine, and the code that has to reach it is not\n * always the code that created it: the host relay resolves a backend from a\n * bare `CloudHandle` (`{ sandboxId }`) with no access to the box record or the\n * user's config. So the SSH destination is encoded INTO the sandbox id:\n *\n * sandboxId = \"<ssh-destination>/<container-name>\"\n * e.g. \"buildbox/agentbox-brave-otter\"\n * \"dev@10.0.0.9:2222/agentbox-brave-otter\"\n *\n * That makes the handle self-describing and multi-host support fall out for\n * free — no per-box registry to keep in sync.\n *\n * What the id bakes is a host **alias**, not a raw connection string: aliases are\n * registered in `hosts-registry.ts` (`~/.agentbox/remote-docker-hosts.json`), and\n * the alias→connection lookup happens at connection time (`ensureTunnel`). That\n * indirection is deliberate — `remote-docker update <alias>` remints the\n * connection and every existing box created against that alias follows it. The\n * functions here stay PURE (no registry I/O): they only split/validate the\n * destination string; resolution is a separate step at the connection chokepoints.\n *\n * A parsed destination is anything OpenSSH accepts once resolved: an\n * `~/.ssh/config` alias (`buildbox`), or `[user@]host[:port]`. We deliberately do\n * NOT parse it into our own notion of identity/port beyond the `:port` suffix —\n * the user's `~/.ssh/config` is the source of truth for keys, ports and usernames.\n */\n\nimport type { SshTargetArgs } from '@agentbox/sandbox-core';\n\n/** A parsed SSH destination. `user` / `port` are absent unless spelled out. */\nexport interface RemoteTarget {\n /** Host, IP, or `~/.ssh/config` alias. */\n host: string;\n user?: string;\n port?: number;\n /** The destination as the user wrote it — the canonical id-carrying form. */\n spec: string;\n}\n\n/** Container names are `agentbox-<box-name>`, matching the docker provider. */\nexport function containerNameFor(boxName: string): string {\n return `agentbox-${boxName}`;\n}\n\n/**\n * Parse `[user@]host[:port]` (or a bare ssh alias). Throws on an empty or\n * malformed destination — a bad host is worth failing loudly on, since every\n * later error would be an opaque ssh failure.\n */\nexport function parseRemoteTarget(spec: string): RemoteTarget {\n const raw = spec.trim();\n if (raw.length === 0) {\n throw new Error('remote-docker: empty SSH destination');\n }\n if (raw.includes('/')) {\n throw new Error(\n `remote-docker: invalid SSH destination \"${raw}\" — \"/\" separates the destination from the container in a sandbox id`,\n );\n }\n const at = raw.lastIndexOf('@');\n const user = at >= 0 ? raw.slice(0, at) : undefined;\n const hostPort = at >= 0 ? raw.slice(at + 1) : raw;\n if (hostPort.length === 0 || (user !== undefined && user.length === 0)) {\n throw new Error(`remote-docker: invalid SSH destination \"${raw}\"`);\n }\n\n // A bracketed IPv6 literal is the only form that can carry a port:\n // `[fe80::1]:2222`. Bare `fe80::1` is all host — its final `:1` is an address\n // group, not a port, and reading it as one would silently connect to :1.\n const bracketed = /^\\[(.+)\\](?::(\\d+))?$/.exec(hostPort);\n if (bracketed?.[1]) {\n const host = bracketed[1];\n if (bracketed[2] === undefined) return { host, user, spec: raw };\n return { host, user, port: checkedPort(bracketed[2], raw), spec: raw };\n }\n if (hostPort.includes(':')) {\n const colon = hostPort.lastIndexOf(':');\n const head = hostPort.slice(0, colon);\n const tail = hostPort.slice(colon + 1);\n // More than one colon ⇒ an unbracketed IPv6 literal ⇒ no port.\n if (!head.includes(':') && /^\\d+$/.test(tail)) {\n return { host: head, user, port: checkedPort(tail, raw), spec: raw };\n }\n }\n return { host: hostPort, user, spec: raw };\n}\n\nfunction checkedPort(digits: string, raw: string): number {\n const port = Number.parseInt(digits, 10);\n if (port <= 0 || port > 65535) {\n throw new Error(`remote-docker: invalid SSH port in \"${raw}\"`);\n }\n return port;\n}\n\n/** `<ssh-destination>/<container>` — the persisted sandbox id. */\nexport function makeSandboxId(targetSpec: string, container: string): string {\n // Validate the destination now so a malformed one can't be persisted.\n parseRemoteTarget(targetSpec);\n return `${targetSpec}/${container}`;\n}\n\nexport interface ParsedSandboxId {\n target: RemoteTarget;\n container: string;\n}\n\n/** Split a sandbox id back into its SSH destination and container name. */\nexport function parseSandboxId(sandboxId: string): ParsedSandboxId {\n const slash = sandboxId.lastIndexOf('/');\n if (slash <= 0 || slash === sandboxId.length - 1) {\n throw new Error(\n `remote-docker: malformed sandbox id \"${sandboxId}\" — expected \"<ssh-destination>/<container>\"`,\n );\n }\n return {\n target: parseRemoteTarget(sandboxId.slice(0, slash)),\n container: sandboxId.slice(slash + 1),\n };\n}\n\n/**\n * The `SshTargetArgs` for a destination. No `identity` and no `knownHosts`:\n * both come from the user's `~/.ssh/config` / agent / `~/.ssh/known_hosts`,\n * which is the whole point of pointing at a machine you already reach.\n */\nexport function sshTargetFor(target: RemoteTarget, controlPath?: string): SshTargetArgs {\n return {\n host: target.host,\n ...(target.user !== undefined ? { user: target.user } : {}),\n ...(target.port !== undefined ? { port: target.port } : {}),\n ...(controlPath !== undefined ? { controlPath } : {}),\n };\n}\n","/**\n * `~/.agentbox/remote-docker-hosts.json` — the alias registry.\n *\n * A remote engine is addressed by a short **alias** (`macmini`), not by its raw\n * SSH connection string. The alias is what gets baked into a box's sandbox id\n * (`<alias>/<container>`); the connection string is resolved from this registry\n * at connection time. That indirection is the whole point: `remote-docker update\n * <alias> <new-ssh>` remints the connection and every existing box created against\n * that alias follows it — no stale IP baked into an id.\n *\n * Two resolution modes:\n * - `resolveConnection(ref)` — LENIENT, for connection time. A registered alias\n * resolves to its ssh string; anything else passes through unchanged, so a box\n * whose id predates this registry (or names a raw/ssh-config destination) stays\n * reachable.\n * - `requireHostAlias(ref)` — STRICT, for entry points (create / prepare /\n * doctor). An unregistered reference throws — you must `add` it first. This is\n * what enforces the alias-only model for NEW boxes without stranding old ones.\n *\n * Shape mirrors `prepared-state.ts` (a provider-owned `Record<string,T>` JSON doc),\n * but with its own filename and inline atomic read/write. `homedir()` is resolved\n * at call time so tests can redirect `$HOME`.\n */\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, resolve as pathResolve } from 'node:path';\n\nconst SCHEMA = 1;\n\nexport interface RemoteHostEntry {\n /** The SSH connection string: `[user@]host[:port]` or an `~/.ssh/config` alias. */\n ssh: string;\n createdAt: string;\n updatedAt?: string;\n}\n\nexport interface RemoteHostsRegistry {\n schema: number;\n /** Keyed by alias — the user-facing name, also what a box's sandbox id bakes. */\n hosts: Record<string, RemoteHostEntry>;\n}\n\n/** Aliases must be a plain name: no `@`/`:` (would look like a connection string),\n * no `/` (sandbox-id separator), no whitespace. Keeps them unambiguous + id-safe. */\nconst ALIAS_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\nexport function isValidAlias(alias: string): boolean {\n return ALIAS_RE.test(alias);\n}\n\nexport function assertValidAlias(alias: string): void {\n if (!isValidAlias(alias)) {\n throw new Error(\n `invalid host alias ${JSON.stringify(alias)} — use a plain name (letters, digits, \\`.\\`, \\`_\\`, \\`-\\`; no \\`@\\`, \\`:\\`, \\`/\\` or spaces)`,\n );\n }\n}\n\nfunction registryPath(): string {\n return pathResolve(homedir(), '.agentbox', 'remote-docker-hosts.json');\n}\n\nexport function readHostsRegistry(): RemoteHostsRegistry | null {\n const path = registryPath();\n if (!existsSync(path)) return null;\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n return null;\n }\n if (raw === null || typeof raw !== 'object') return null;\n const parsed = raw as Partial<RemoteHostsRegistry>;\n if (parsed.schema !== SCHEMA || typeof parsed.hosts !== 'object' || parsed.hosts === null) {\n return null;\n }\n return { schema: SCHEMA, hosts: parsed.hosts };\n}\n\n/** Atomic write (tmp + rename), 0600 — same hygiene as `writePreparedStateRaw`. */\nexport function writeHostsRegistry(reg: RemoteHostsRegistry): void {\n const path = registryPath();\n mkdirSync(dirname(path), { recursive: true });\n const body = JSON.stringify({ schema: SCHEMA, hosts: reg.hosts }, null, 2) + '\\n';\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, body, { mode: 0o600 });\n renameSync(tmp, path);\n}\n\nexport function getHostAlias(alias: string): RemoteHostEntry | undefined {\n return readHostsRegistry()?.hosts[alias];\n}\n\n/** All registered aliases, sorted by name for stable `list` output. */\nexport function listHostAliases(): Array<{ alias: string; entry: RemoteHostEntry }> {\n const reg = readHostsRegistry();\n if (!reg) return [];\n return Object.entries(reg.hosts)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([alias, entry]) => ({ alias, entry }));\n}\n\n/**\n * Register or re-point an alias. Preserves `createdAt` on an update and stamps\n * `updatedAt`. Caller validates the alias name + probes the connection first.\n */\nexport function upsertHostAlias(alias: string, ssh: string): void {\n const reg = readHostsRegistry() ?? { schema: SCHEMA, hosts: {} };\n const existing = reg.hosts[alias];\n const now = new Date().toISOString();\n reg.hosts[alias] = existing\n ? { ...existing, ssh, updatedAt: now }\n : { ssh, createdAt: now };\n writeHostsRegistry(reg);\n}\n\n/** Drop an alias. Returns whether it was present. */\nexport function removeHostAlias(alias: string): boolean {\n const reg = readHostsRegistry();\n if (!reg || !(alias in reg.hosts)) return false;\n const hosts = { ...reg.hosts };\n delete hosts[alias];\n writeHostsRegistry({ schema: SCHEMA, hosts });\n return true;\n}\n\n/**\n * Connection-time resolution (LENIENT): a registered alias → its ssh string;\n * anything else → unchanged, so pre-registry / raw-baked box ids stay reachable.\n */\nexport function resolveConnection(ref: string): string {\n return getHostAlias(ref)?.ssh ?? ref;\n}\n\n/**\n * Entry-point resolution (STRICT): a registered alias → its entry; otherwise\n * throw. This is what makes the model alias-only for anything that CREATES a\n * reference (create / prepare / doctor) without stranding existing boxes.\n */\nexport function requireHostAlias(ref: string): RemoteHostEntry {\n const entry = getHostAlias(ref);\n if (!entry) {\n throw new Error(\n `no such remote-docker host alias ${JSON.stringify(ref)} — register it with \\`agentbox remote-docker add <name> <[user@]host[:port]>\\``,\n );\n }\n return entry;\n}\n","/**\n * The single chokepoint through which every `docker` command reaches the remote\n * engine: one persistent SSH ControlMaster per box, `docker …` run inside a\n * remote LOGIN shell.\n *\n * Why not `DOCKER_HOST=ssh://user@host`? Two reasons, both fatal in practice:\n *\n * 1. Docker's ssh transport runs `docker system dial-stdio` on the remote,\n * which needs `docker` on the NON-login-shell PATH. That is exactly where\n * OrbStack (`~/.orbstack/bin`) and Colima break, so a Mac remote — a case\n * we explicitly support — would fail with an opaque \"command not found\".\n * A login shell (`bash -lc`) sources the profile and finds them.\n * 2. It opens a fresh SSH connection per `docker` invocation. Create issues\n * dozens; the ControlMaster amortizes the handshake to ~nothing.\n *\n * The trade is that we compose docker's argv into a shell string ourselves, so\n * every argument must be quoted — `quoteShellArgv` from @agentbox/sandbox-cloud\n * does that, and nothing in this package may build a remote command by\n * concatenation.\n */\n\nimport { execa } from 'execa';\nimport type { Readable, Writable } from 'node:stream';\nimport { quoteShellArg, quoteShellArgv } from '@agentbox/sandbox-cloud';\nimport {\n SshTunnelManager,\n sshDestination,\n sshExec,\n sshOptArgs,\n type SshTargetArgs,\n} from '@agentbox/sandbox-core';\nimport { parseRemoteTarget, sshTargetFor, type RemoteTarget } from './target.js';\nimport { resolveConnection } from './hosts-registry.js';\n\n/**\n * A box's sandbox id bakes an ALIAS, not a raw connection string. Turn the\n * baked target into one that dials the alias's current connection — so\n * `remote-docker update` retargets existing boxes. Lenient: a non-alias spec\n * (raw destination, or a pre-registry id) passes through unchanged.\n */\nfunction dialTarget(target: RemoteTarget): RemoteTarget {\n const resolved = resolveConnection(target.spec);\n return resolved === target.spec ? target : parseRemoteTarget(resolved);\n}\n\n/** One ControlMaster per box, namespaced so ids can't collide with a VPS provider's. */\nexport const tunnels = new SshTunnelManager('remote-docker');\n\nexport interface RemoteExecResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Open (or reuse) the ControlMaster for a box and return an ssh target bound to\n * it. Every exec/upload/download/forward for that box rides this one connection.\n */\nexport async function ensureTunnel(\n sandboxId: string,\n target: RemoteTarget,\n): Promise<SshTargetArgs> {\n // Dial the alias's current connection; keep the tunnel keyed by sandboxId.\n const dial = dialTarget(target);\n if (!tunnels.has(sandboxId)) {\n try {\n await tunnels.open({\n boxId: sandboxId,\n vpsHost: dial.host,\n ...(dial.user !== undefined ? { vpsUser: dial.user } : {}),\n ...(dial.port !== undefined ? { port: dial.port } : {}),\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const where = dial.spec === target.spec ? `\"${target.spec}\"` : `\"${target.spec}\" (${dial.spec})`;\n throw new Error(\n `remote-docker: cannot SSH to ${where}. Check that \\`ssh ${dial.spec} true\\` works from this machine ` +\n `(the provider uses your own ~/.ssh/config, agent and known_hosts — it mints no keys).\\n${msg}`,\n );\n }\n }\n const controlPath = tunnels.controlPath(sandboxId);\n return sshTargetFor(dial, controlPath);\n}\n\n/** Re-open a dead master (host sleep/wake, network blip) and drop stale forwards. */\nexport async function refreshTunnel(sandboxId: string, target: RemoteTarget): Promise<void> {\n const dial = dialTarget(target);\n await tunnels.refresh({\n boxId: sandboxId,\n vpsHost: dial.host,\n ...(dial.user !== undefined ? { vpsUser: dial.user } : {}),\n ...(dial.port !== undefined ? { port: dial.port } : {}),\n });\n}\n\n/**\n * Run `docker <argv…>` on the remote engine. `argv` is quoted, so callers pass\n * a plain array and never think about the shell.\n */\nexport async function dockerOnRemote(\n target: SshTargetArgs,\n argv: string[],\n opts: { timeoutMs?: number; onLine?: (line: string) => void } = {},\n): Promise<RemoteExecResult> {\n return sshExec(target, loginShell(`docker ${quoteShellArgv(argv)}`), {\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n ...(opts.onLine !== undefined ? { onLine: opts.onLine } : {}),\n });\n}\n\n/** Same, but throws with the remote's stderr on a non-zero exit. */\nexport async function dockerOnRemoteOrThrow(\n target: SshTargetArgs,\n argv: string[],\n opts: { timeoutMs?: number; onLine?: (line: string) => void } = {},\n): Promise<string> {\n const res = await dockerOnRemote(target, argv, opts);\n if (res.exitCode !== 0) {\n throw new Error(\n `remote-docker: \\`docker ${argv.join(' ')}\\` failed (exit ${String(res.exitCode)}): ${\n res.stderr.trim() || res.stdout.trim() || '(no output)'\n }`,\n );\n }\n return res.stdout;\n}\n\n/**\n * Run a command INSIDE the box's container: `docker exec … bash -lc '<cmd>'`.\n * This is what `CloudBackend.exec` is built on, so it carries the same\n * semantics the cloud scaffold expects (login shell, so `/etc/profile.d`\n * exports are visible).\n */\nexport function dockerExecArgv(\n container: string,\n command: string,\n opts: { user?: string; cwd?: string; env?: Record<string, string>; interactive?: boolean } = {},\n): string[] {\n const argv = ['exec'];\n if (opts.interactive) argv.push('-i');\n if (opts.user) argv.push('-u', opts.user);\n if (opts.cwd) argv.push('-w', opts.cwd);\n for (const [k, v] of Object.entries(opts.env ?? {})) {\n argv.push('-e', `${k}=${v}`);\n }\n argv.push(container, 'bash', '-lc', command);\n return argv;\n}\n\n/**\n * The user every exec and every file transfer runs as. It must be ONE user:\n * a file written as root that `exec` (as vscode) later has to delete leaves the\n * box wedged — and on a nested engine, where the container init is forced to\n * uid 0, `docker exec` with no `-u` would default to root and do exactly that.\n * So both sides name the user explicitly rather than inheriting the container's.\n */\nexport const CONTAINER_USER = 'vscode';\n\n/**\n * Stream a local file into a file inside the container, over the ControlMaster.\n *\n * Not `docker cp`: that would need the bytes staged on the remote host first\n * (an extra hop and a temp file to clean up). Piping into `cat` inside the\n * container is one hop, binary-safe, and leaves nothing behind. `execa` is\n * driven directly here because the transfer needs a stdin stream, which the\n * text-in/text-out `sshExec` deliberately doesn't model.\n */\nexport async function pipeFileIntoContainer(\n target: SshTargetArgs,\n container: string,\n input: Readable,\n remotePath: string,\n): Promise<void> {\n const remote = loginShell(\n `docker ${quoteShellArgv(['exec', '-i', '-u', CONTAINER_USER, container, 'sh', '-c', `cat > ${quoteShellArg(remotePath)}`])}`,\n );\n const res = await execa('ssh', [...sshOptArgs(target), sshDestination(target), remote], {\n reject: false,\n input,\n });\n if (res.exitCode !== 0) {\n throw new Error(\n `remote-docker: upload to ${container}:${remotePath} failed (exit ${String(res.exitCode)}): ${\n typeof res.stderr === 'string' ? res.stderr : ''\n }`,\n );\n }\n}\n\n/** Stream a file out of the container into a local writable stream. */\nexport async function pipeFileFromContainer(\n target: SshTargetArgs,\n container: string,\n remotePath: string,\n output: Writable,\n): Promise<void> {\n const remote = loginShell(\n `docker ${quoteShellArgv(['exec', '-u', CONTAINER_USER, container, 'cat', remotePath])}`,\n );\n const child = execa('ssh', [...sshOptArgs(target), sshDestination(target), remote], {\n reject: false,\n stdout: 'pipe',\n stderr: 'pipe',\n });\n child.stdout?.pipe(output);\n const res = await child;\n if (res.exitCode !== 0) {\n throw new Error(\n `remote-docker: download of ${container}:${remotePath} failed (exit ${String(res.exitCode)}): ${\n typeof res.stderr === 'string' ? res.stderr : ''\n }`,\n );\n }\n}\n\n/**\n * `bash -lc '<cmd>'` — a LOGIN shell, so the remote user's profile is sourced\n * and `docker` is found wherever their engine put it (Docker Desktop in\n * /usr/local/bin, OrbStack in ~/.orbstack/bin, Linux packages in /usr/bin).\n * This is the single reason a macOS remote works without a PATH config key.\n */\nexport function loginShell(command: string): string {\n return `bash -lc ${quoteShellArg(command)}`;\n}\n\n/** One preflight check, so `remote-docker doctor` can render a row per step. */\nexport interface RemoteEngineStep {\n label: 'ssh' | 'docker';\n ok: boolean;\n /** Success line or failure reason, shown after the status badge. */\n detail: string;\n hint?: string;\n}\n\nexport interface RemoteEngineProbe {\n /** True iff every attempted step passed. */\n ok: boolean;\n /** The steps that ran, in order (ssh, then docker). A failed step is last. */\n steps: RemoteEngineStep[];\n /** From the docker step when `ok`. */\n version?: string;\n arch?: string;\n os?: string;\n /** First failing step's detail — convenience for single-line callers. */\n error?: string;\n}\n\n/**\n * Preflight a destination: SSH reachable, `docker` on the login-shell PATH, and\n * the daemon actually answering. Returns a per-step result so `remote-docker\n * doctor` can render one `[ ok ]`/`[FAIL]` row per check (like `agentbox\n * doctor`); `add` and the provider's doctorChecks read the rolled-up fields.\n */\nexport async function probeRemoteEngine(spec: string): Promise<RemoteEngineProbe> {\n let target: SshTargetArgs;\n try {\n target = sshTargetFor(parseRemoteTarget(spec));\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n return { ok: false, steps: [{ label: 'ssh', ok: false, detail }], error: detail };\n }\n const reach = await sshExec({ ...target, options: { ConnectTimeout: '10' } }, 'true', {\n timeoutMs: 20_000,\n });\n if (reach.exitCode !== 0) {\n const detail = `cannot SSH to ${spec}: ${reach.stderr.trim() || `exit ${String(reach.exitCode)}`}`;\n return {\n ok: false,\n steps: [{ label: 'ssh', ok: false, detail, hint: `\\`ssh ${spec} true\\` must work from here` }],\n error: detail,\n };\n }\n const sshStep: RemoteEngineStep = { label: 'ssh', ok: true, detail: `reachable (${spec})` };\n const res = await dockerOnRemote(\n target,\n ['version', '--format', '{{.Server.Version}}|{{.Server.Arch}}|{{.Server.Os}}'],\n {\n timeoutMs: 30_000,\n },\n );\n if (res.exitCode !== 0) {\n const err = res.stderr.trim() || res.stdout.trim();\n const notFound = /command not found|not found/i.test(err);\n const detail = notFound\n ? `\\`docker\\` is not on ${spec}'s login-shell PATH (${err}). Install Docker there, or add it to the remote user's profile.`\n : `docker on ${spec} is not answering: ${err}`;\n return {\n ok: false,\n steps: [sshStep, { label: 'docker', ok: false, detail }],\n error: detail,\n };\n }\n const [version = '', arch = '', os = ''] = res.stdout.trim().split('|');\n const dockerStep: RemoteEngineStep = {\n label: 'docker',\n ok: true,\n detail: `${version} (${os}/${arch})`,\n };\n return { ok: true, steps: [sshStep, dockerStep], version, arch, os };\n}\n","/**\n * Getting the box image onto the remote engine.\n *\n * The image ref IS the build-context fingerprint: `agentbox/box:<sha16>`, the\n * same sha the local docker provider computes. That one decision removes a\n * whole class of state:\n *\n * - \"is this host prepared?\" == `docker image inspect agentbox/box:<sha>` on it.\n * No prepared-state file is consulted to decide, so it can't go stale or\n * disagree with reality, and it is naturally PER HOST (which a single\n * `~/.agentbox/remote-docker-prepared.json` could never be).\n * - a CLI upgrade that changes any baked file changes the sha, so the next\n * create ensures a new ref rather than silently running an old image.\n *\n * Ensure order: already present → pull the fingerprint-tagged image from GHCR\n * (published multi-arch, so an amd64 remote gets amd64 even though the laptop\n * is arm64) → stream the local build context to a remote `docker build -`.\n */\n\nimport { createReadStream } from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport { quoteShellArgv } from '@agentbox/sandbox-cloud';\nimport {\n BOX_IMAGE_REGISTRY,\n BUILD_CONTEXT_DIR,\n computeDockerContextFingerprint,\n registryRefForSha,\n} from '@agentbox/sandbox-docker';\nimport {\n claudeInstallFingerprint,\n sshDestination,\n sshOptArgs,\n type SshTargetArgs,\n} from '@agentbox/sandbox-core';\nimport { dockerOnRemote, loginShell } from './remote-docker.js';\n\nexport type ClaudeInstall = 'native' | 'npm';\n\nexport interface EnsureRemoteImageOptions {\n /** Pin an explicit image ref on the remote (`box.imageRemoteDocker`); skips the ensure. */\n imageRef?: string;\n claudeInstall?: ClaudeInstall;\n /** Registry to pull from. Empty string disables the pull and forces a build. */\n registry?: string;\n /** Force the build path even on a registry hit (`--build`). */\n allowPull?: boolean;\n /** Rebuild even when the ref is already present on the remote. */\n force?: boolean;\n onLog?: (line: string) => void;\n}\n\nexport interface EnsureRemoteImageResult {\n ref: string;\n source: 'pinned' | 'present' | 'pulled' | 'built';\n /** The build-context fingerprint the ref encodes, when we derived it. */\n contextSha256?: string;\n}\n\n/** The image ref a given build-context fingerprint maps to on the remote. */\nexport function remoteImageRef(contextSha256: string): string {\n return `agentbox/box:${contextSha256.slice(0, 16)}`;\n}\n\n/**\n * Resolve the fingerprint of the build context this CLI would bake, folding in\n * the Claude install mode exactly as the docker provider does (so an npm-baked\n * image and a native-baked one are different refs, not the same ref with\n * different contents). Null when the context can't be resolved — a dev tree\n * without `pnpm -w build`.\n */\nexport async function currentContextSha(claudeInstall?: ClaudeInstall): Promise<string | null> {\n const fp = await computeDockerContextFingerprint({});\n if (!fp) return null;\n return claudeInstall\n ? claudeInstallFingerprint(fp.contextSha256, claudeInstall)\n : fp.contextSha256;\n}\n\n/**\n * Make the box image present on the remote engine. Idempotent and cheap on the\n * hot path: a single `docker image inspect` when it's already there.\n */\nexport async function ensureRemoteImage(\n target: SshTargetArgs,\n opts: EnsureRemoteImageOptions = {},\n): Promise<EnsureRemoteImageResult> {\n const log = opts.onLog ?? ((): void => {});\n\n // An explicitly pinned ref is the user's problem to keep present — we neither\n // pull nor build it, because we have no idea what it contains.\n if (opts.imageRef && opts.imageRef.trim().length > 0) {\n const ref = opts.imageRef.trim();\n const probe = await dockerOnRemote(target, ['image', 'inspect', ref]);\n if (probe.exitCode !== 0) {\n throw new Error(\n `remote-docker: box.imageRemoteDocker pins \"${ref}\", which is not present on the remote engine. ` +\n `Build/pull it there, or unset the key to let AgentBox manage the image.`,\n );\n }\n return { ref, source: 'pinned' };\n }\n\n const sha = await currentContextSha(opts.claudeInstall);\n if (!sha) {\n throw new Error(\n 'remote-docker: cannot resolve the box build context (a dev tree needs `pnpm -w build` first)',\n );\n }\n const ref = remoteImageRef(sha);\n\n if (!opts.force) {\n const probe = await dockerOnRemote(target, ['image', 'inspect', ref]);\n if (probe.exitCode === 0) {\n log(`[image] ${ref} already present on the remote`);\n return { ref, source: 'present', contextSha256: sha };\n }\n }\n\n const registry = opts.registry ?? BOX_IMAGE_REGISTRY;\n if (opts.allowPull !== false && registry) {\n const remote = registryRefForSha(sha, registry);\n log(`[image] pulling ${remote} on the remote engine`);\n const pull = await dockerOnRemote(target, ['pull', remote], {\n timeoutMs: 900_000,\n onLine: (l) => log(`[image] ${l}`),\n });\n if (pull.exitCode === 0) {\n await dockerOnRemote(target, ['tag', remote, ref]);\n log(`[image] pulled ${remote} -> ${ref}`);\n return { ref, source: 'pulled', contextSha256: sha };\n }\n log('[image] registry miss — building on the remote from the local context');\n }\n\n await buildOnRemote(target, ref, opts);\n return { ref, source: 'built', contextSha256: sha };\n}\n\n/**\n * Stream the local build context to `docker build -` on the remote.\n *\n * `docker build -` reads a tar of the context from stdin, so the whole build\n * happens on the remote engine with no files staged on its disk beforehand —\n * and no dependency on the remote having a checkout of anything.\n */\nasync function buildOnRemote(\n target: SshTargetArgs,\n ref: string,\n opts: EnsureRemoteImageOptions,\n): Promise<void> {\n const log = opts.onLog ?? ((): void => {});\n const tarPath = join(tmpdir(), `agentbox-box-ctx-${String(process.pid)}.tar`);\n try {\n // COPYFILE_DISABLE stops macOS tar from emitting ._* AppleDouble entries,\n // which would land in the image as junk files.\n await execa('tar', ['-C', BUILD_CONTEXT_DIR, '-cf', tarPath, '.'], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n\n const buildArgs = ['build', '-t', ref, '-f', 'Dockerfile.box'];\n if (opts.claudeInstall) {\n buildArgs.push('--build-arg', `AGENTBOX_CLAUDE_INSTALL=${opts.claudeInstall}`);\n }\n buildArgs.push('-');\n\n log(`[image] building ${ref} on the remote (streaming the build context)`);\n const res = await execa(\n 'ssh',\n [\n ...sshOptArgs(target),\n sshDestination(target),\n loginShell(`docker ${quoteShellArgv(buildArgs)}`),\n ],\n { reject: false, input: createReadStream(tarPath), stdout: 'pipe', stderr: 'pipe' },\n );\n const out = `${typeof res.stdout === 'string' ? res.stdout : ''}${typeof res.stderr === 'string' ? res.stderr : ''}`;\n for (const line of out.split(/\\r?\\n/)) {\n if (line.trim().length > 0) log(`[image] ${line}`);\n }\n if (res.exitCode !== 0) {\n throw new Error(\n `remote-docker: remote \\`docker build\\` failed (exit ${String(res.exitCode)}). See the build output above.`,\n );\n }\n log(`[image] built ${ref}`);\n } finally {\n await rm(tarPath, { force: true });\n }\n}\n","/**\n * `~/.agentbox/remote-docker-prepared.json`.\n *\n * Unlike every other cloud provider, this file is NOT load-bearing. The image\n * ref on a remote engine is its build-context fingerprint (`agentbox/box:<sha>`),\n * so \"is this host prepared?\" is answered by asking the engine, not by trusting\n * a local file — and it is answered per host, which a single file could never\n * do. What this records is the *history*: which hosts we have baked, with what,\n * and when, for `agentbox prepare --status` and `doctor` to report.\n */\n\nimport { readPreparedStateRaw, writePreparedStateRaw, readCliStamp } from '@agentbox/sandbox-core';\n\nconst SCHEMA = 1;\nconst PROVIDER = 'remote-docker';\n\nexport interface PreparedRemoteHost {\n imageRef: string;\n contextSha256: string;\n cliVersion?: string;\n cliCommit?: string;\n createdAt: string;\n}\n\nexport interface PreparedRemoteDockerState {\n schema: number;\n /** Keyed by SSH destination, exactly as the user spelled it. */\n hosts: Record<string, PreparedRemoteHost>;\n}\n\nexport function readPreparedState(): PreparedRemoteDockerState | null {\n const raw = readPreparedStateRaw(PROVIDER);\n if (raw === null || typeof raw !== 'object') return null;\n const parsed = raw as Partial<PreparedRemoteDockerState>;\n if (parsed.schema !== SCHEMA || typeof parsed.hosts !== 'object' || parsed.hosts === null) {\n return null;\n }\n return { schema: SCHEMA, hosts: parsed.hosts };\n}\n\n/** Drop one host from the prepared-image history. Returns whether it was present. */\nexport function removePreparedHost(host: string): boolean {\n const existing = readPreparedState();\n if (!existing || !(host in existing.hosts)) return false;\n const hosts = { ...existing.hosts };\n delete hosts[host];\n writePreparedStateRaw(PROVIDER, { schema: SCHEMA, hosts });\n return true;\n}\n\nexport function recordPreparedHost(\n host: string,\n fields: { imageRef: string; contextSha256: string },\n): void {\n const stamp = readCliStamp();\n const existing = readPreparedState();\n const next: PreparedRemoteDockerState = {\n schema: SCHEMA,\n hosts: {\n ...(existing?.hosts ?? {}),\n [host]: {\n imageRef: fields.imageRef,\n contextSha256: fields.contextSha256,\n ...(stamp.cliVersion ? { cliVersion: stamp.cliVersion } : {}),\n ...(stamp.cliCommit ? { cliCommit: stamp.cliCommit } : {}),\n createdAt: new Date().toISOString(),\n },\n },\n };\n writePreparedStateRaw(PROVIDER, next);\n}\n","/**\n * `agentbox prepare --provider docker:<host>` — bake the box image on a remote\n * engine.\n *\n * Unlike the VPS providers, this is not a mandatory gate: a remote engine can\n * build from a Dockerfile, so `create` ensures the image itself and prepare is\n * simply the eager form (\"do the slow part now, not when I'm waiting for a\n * box\"). It is also the only place that writes `remote-docker-prepared.json`,\n * which exists purely so `prepare --status` / `doctor` can report what has been\n * baked where.\n */\n\nimport type { PrepareOptions, PrepareResult } from '@agentbox/core';\nimport { ensureRemoteImage } from './image.js';\nimport { ensureTunnel } from './remote-docker.js';\nimport { recordPreparedHost } from './prepared-state.js';\nimport { requireHostAlias } from './hosts-registry.js';\nimport { parseRemoteTarget } from './target.js';\n\nexport async function prepareRemoteDocker(\n opts: PrepareOptions & { host?: string },\n): Promise<PrepareResult> {\n const log = opts.onLog ?? ((): void => {});\n const spec = (opts.host ?? '').trim();\n if (!spec) {\n throw new Error(\n 'remote-docker: prepare needs a host alias — `agentbox prepare --provider docker:<alias>`, ' +\n 'or set `box.remoteDockerHost`.',\n );\n }\n requireHostAlias(spec);\n const remote = parseRemoteTarget(spec);\n const target = await ensureTunnel(`engine:${remote.spec}`, remote);\n\n log(`[prepare] ensuring the box image on ${remote.spec}`);\n const res = await ensureRemoteImage(target, {\n ...(opts.claudeInstall ? { claudeInstall: opts.claudeInstall } : {}),\n ...(opts.registry !== undefined ? { registry: opts.registry } : {}),\n ...(opts.allowPull !== undefined ? { allowPull: opts.allowPull } : {}),\n ...(opts.force ? { force: true } : {}),\n onLog: log,\n });\n\n if (res.contextSha256) {\n recordPreparedHost(remote.spec, { imageRef: res.ref, contextSha256: res.contextSha256 });\n }\n log(`[prepare] ${remote.spec} ready — ${res.ref} (${res.source})`);\n\n // Deliberately no `snapshotName`: returning one makes the CLI pin\n // `box.imageRemoteDocker` to it, which would freeze every future create on\n // today's fingerprint and defeat the self-updating ref.\n return {};\n}\n","/**\n * The remote-docker provider: `createCloudProvider(remoteDockerBackend)` plus\n * the four things the scaffold can't supply.\n *\n * - `buildAttach` — the scaffold's SSH attach lands on the machine, not in\n * the container; ours wraps the inner command in a `docker exec`.\n * - `checkpoint` — `docker commit` on the engine that runs the box, with the\n * host carried in the snapshot name (see `parseSnapshotName`).\n * - `prepare` — bake the box image on a remote engine.\n * - `baseFingerprint` — the docker build-context sha, so the CLI's\n * \"your base is stale\" nag works the same way it does locally.\n */\n\nimport type { BoxRecord, Provider, ProviderCheckpoint } from '@agentbox/core';\nimport {\n createCloudProvider,\n currentCloudBaseFingerprint,\n listCloudCheckpoints,\n removeCloudCheckpointDir,\n resolveCloudCheckpoint,\n writeCloudCheckpointManifest,\n} from '@agentbox/sandbox-cloud';\nimport { hashProjectPath, sanitizeMnemonic } from '@agentbox/config';\nimport { readCliStamp, type ProviderModule } from '@agentbox/sandbox-core';\nimport { basename } from 'node:path';\nimport { BACKEND_NAME, makeSnapshotName, remoteDockerBackend } from './backend.js';\nimport { buildRemoteDockerAttach } from './build-attach.js';\nimport { resolveBoxSshTarget } from './box-ssh.js';\nimport { currentContextSha } from './image.js';\nimport { prepareRemoteDocker } from './prepare.js';\nimport { parseSandboxId } from './target.js';\nimport { doctorChecks } from './provider-module.js';\n\nconst cloudProvider = createCloudProvider(remoteDockerBackend, {\n // Empty on purpose. The cloud default (2 cpu / 4 GB) would silently cap a box\n // on a 32-core workstation; a remote engine is the user's own machine, so a\n // box is unlimited unless `--size` says otherwise — the same deal the local\n // docker provider offers.\n defaultResources: {},\n launchDockerd: true,\n});\n\n/** The docker image a checkpoint commits to on the remote engine. */\nfunction checkpointImageRef(projectRoot: string, name: string): string {\n const mnemonic = sanitizeMnemonic(basename(projectRoot));\n return `agentbox-ckpt-${hashProjectPath(projectRoot)}_${mnemonic}:${name}`;\n}\n\nconst remoteDockerCheckpoint: ProviderCheckpoint = {\n async create(box: BoxRecord, name: string) {\n if (!box.projectRoot) {\n throw new Error(\n 'checkpoint requires the box to have a project root (run `agentbox checkpoint` from inside the project)',\n );\n }\n const sandboxId = box.cloud?.sandboxId;\n if (!sandboxId) {\n throw new Error(`remote-docker box ${box.name} has no sandboxId — record is malformed`);\n }\n const { target } = parseSandboxId(sandboxId);\n const snapshotName = makeSnapshotName(target.spec, checkpointImageRef(box.projectRoot, name));\n await remoteDockerBackend.createSnapshot?.({ sandboxId }, snapshotName);\n\n const info = await writeCloudCheckpointManifest(box.projectRoot, BACKEND_NAME, name, {\n snapshotName,\n sourceBoxId: box.id,\n sourceBoxName: box.name,\n baseProvider: BACKEND_NAME,\n baseFingerprint: currentCloudBaseFingerprint(BACKEND_NAME),\n cliVersion: readCliStamp().cliVersion,\n });\n return { ref: info.name };\n },\n\n async list(projectRoot: string) {\n const entries = await listCloudCheckpoints(projectRoot, BACKEND_NAME);\n return entries.map((e) => ({ ref: e.name, createdAt: e.manifest.createdAt }));\n },\n\n async remove(projectRoot: string, ref: string) {\n const entry = await resolveCloudCheckpoint(projectRoot, BACKEND_NAME, ref);\n if (!entry) return;\n await remoteDockerBackend.deleteSnapshot?.(entry.manifest.snapshotName);\n await removeCloudCheckpointDir(projectRoot, BACKEND_NAME, ref);\n },\n};\n\nexport const remoteDockerProvider: Provider = {\n ...cloudProvider,\n buildAttach: buildRemoteDockerAttach,\n // The box's own sshd, reached by jumping through the engine — see box-ssh.ts.\n // Supplying this is what lets `open` / `code` / `connect` treat a remote-docker\n // box like any other SSH-capable box, without the scaffold having to guess a\n // target out of an attach argv that points at the engine rather than the box.\n sshTarget: resolveBoxSshTarget,\n checkpoint: remoteDockerCheckpoint,\n prepare: prepareRemoteDocker,\n baseFingerprint: async (claudeInstall) => (await currentContextSha(claudeInstall)) ?? undefined,\n};\n\n/** Uniform surface the CLI provider loader resolves this package through. */\nexport const providerModule: ProviderModule = {\n provider: remoteDockerProvider,\n backend: remoteDockerBackend,\n currentBaseFingerprintLive: async (claudeInstall) =>\n (await currentContextSha(claudeInstall)) ?? undefined,\n doctorChecks,\n};\n\nexport { remoteDockerBackend, BACKEND_NAME, listOnHost } from './backend.js';\nexport { probeRemoteEngine } from './remote-docker.js';\nexport { parseRemoteTarget, parseSandboxId } from './target.js';\nexport { interactiveRegisterHost } from './host-setup.js';\nexport {\n isValidAlias,\n readHostsRegistry,\n getHostAlias,\n listHostAliases,\n upsertHostAlias,\n removeHostAlias,\n type RemoteHostEntry,\n} from './hosts-registry.js';\nexport { readPreparedState, removePreparedHost } from './prepared-state.js';\n","/**\n * `remoteDockerBackend` — a `CloudBackend` whose \"sandbox\" is a container on a\n * remote machine's Docker engine, reached over one SSH ControlMaster per box.\n *\n * It is a cloud backend, not a second docker provider, and that is the whole\n * design. The docker provider's core mechanism — bind-mounting the host's\n * `.git/` into the container so in-box commits land in the host repo with zero\n * sync — cannot cross a network. Everything that follows from that (the ctl\n * unix socket on a host path, `-p 127.0.0.1:…` on the *local* loopback,\n * `host.docker.internal` reaching the laptop's relay) is equally local-only.\n *\n * The cloud scaffold already solved all of it: `seedCloudWorkspace` syncs the\n * workspace as a shallow clone + carried-over stash/untracked, the in-box relay\n * on :8788 is long-polled by the host `CloudBoxPoller`, and `git push` travels\n * back as a bundle. So we implement the ~14 `CloudBackend` primitives in terms\n * of `docker` over SSH and inherit the rest.\n *\n * What stays docker-shaped: the image (a real Dockerfile build), checkpoints\n * (`docker commit`), nested containers (DinD, same caps as the local provider),\n * and pause (`docker pause`, a true freeze rather than a snapshot).\n */\n\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport type {\n CloudBackend,\n CloudExecOptions,\n CloudExecResult,\n CloudFileEntry,\n CloudHandle,\n CloudPreviewUrl,\n CloudProvisionRequest,\n CloudSandboxSummary,\n CloudState,\n} from '@agentbox/core';\nimport { loadEffectiveConfig } from '@agentbox/config';\nimport { CLOUD_VNC_PORT, CLOUD_WEB_PROXY_PORT, bashScript } from '@agentbox/sandbox-cloud';\nimport { readState, sshExec, type SshTargetArgs } from '@agentbox/sandbox-core';\nimport { ensureRemoteImage } from './image.js';\nimport {\n CONTAINER_USER,\n dockerExecArgv,\n dockerOnRemote,\n dockerOnRemoteOrThrow,\n ensureTunnel,\n pipeFileFromContainer,\n pipeFileIntoContainer,\n refreshTunnel,\n tunnels,\n} from './remote-docker.js';\nimport {\n containerNameFor,\n makeSandboxId,\n parseRemoteTarget,\n parseSandboxId,\n type RemoteTarget,\n} from './target.js';\nimport { requireHostAlias } from './hosts-registry.js';\n\nexport const BACKEND_NAME = 'remote-docker';\n\n/**\n * A checkpoint is a `docker commit` on ONE engine — the image never leaves it —\n * so the snapshot name has to carry the host as well as the image ref:\n *\n * \"<ssh-destination>#<docker-image-ref>\"\n * e.g. \"dev@10.0.0.9:2222#agentbox-ckpt-9f2a_myrepo:setup\"\n *\n * `deleteSnapshot` and `snapshotExists` are handed nothing but this string (no\n * `CloudHandle`), so without the host they could not find the image at all. It\n * cannot go in the docker ref itself: a ref admits neither `@` nor `:` outside\n * the tag, and an ssh destination is full of both. `#` never appears in either\n * half, so it is an unambiguous separator.\n *\n * Nothing outside this package interprets the string — the `CloudBackend`\n * contract treats it as opaque, round-tripping it from `createSnapshot` through\n * the manifest to `provision({ snapshot })`.\n */\nconst SNAPSHOT_SEP = '#';\n\nexport interface ParsedSnapshot {\n host: string;\n imageRef: string;\n}\n\nexport function makeSnapshotName(host: string, imageRef: string): string {\n return `${host}${SNAPSHOT_SEP}${imageRef}`;\n}\n\nexport function parseSnapshotName(snapshotName: string): ParsedSnapshot {\n const sep = snapshotName.indexOf(SNAPSHOT_SEP);\n if (sep <= 0 || sep === snapshotName.length - 1) {\n throw new Error(\n `remote-docker: malformed snapshot name \"${snapshotName}\" — expected \"<ssh-destination>#<image-ref>\"`,\n );\n }\n return {\n host: snapshotName.slice(0, sep),\n imageRef: snapshotName.slice(sep + 1),\n };\n}\n\n/**\n * Tunnel id for a host-scoped (rather than box-scoped) connection — the image\n * ops, which act on an engine rather than a container.\n */\nfunction snapshotTunnelId(host: string): string {\n return `engine:${host}`;\n}\n\n/** In-box relay port the host CloudBoxPoller long-polls (`/bridge/*`). */\nconst BRIDGE_PORT = 8788;\n/** The box image's always-on sshd — published so `agentbox open` / `code` work. */\nconst SSH_PORT = 22;\n\n/**\n * Ports published at `docker run`. Docker port mappings are immutable for the\n * life of a container (the same constraint Vercel has), so everything the host\n * may ever need to reach must be listed at create: the WebProxy, noVNC, the\n * bridge, sshd, plus whatever `agentbox.yaml` exposes.\n */\nfunction portsToPublish(exposePorts: number[] | undefined): number[] {\n const base = [CLOUD_WEB_PROXY_PORT, CLOUD_VNC_PORT, BRIDGE_PORT, SSH_PORT];\n return [...new Set([...base, ...(exposePorts ?? [])])];\n}\n\ninterface Ctx {\n target: SshTargetArgs;\n remote: RemoteTarget;\n container: string;\n}\n\n/**\n * Is the remote engine itself running inside an AgentBox sandbox? Only true in\n * the agentbox-in-agentbox dev loop this repo is developed with (CLAUDE.md ->\n * \"Use Agentbox inside Agentbox\"), where the nested dockerd lacks the\n * capabilities a normal engine has. `/etc/agentbox/box.env` is written into\n * every box by the create path, so its presence is the box's own identity file.\n */\nasync function remoteIsNested(target: SshTargetArgs): Promise<boolean> {\n const res = await sshExec(target, 'test -f /etc/agentbox/box.env');\n return res.exitCode === 0;\n}\n\n/** Resolve a handle into a live SSH connection + the container it names. */\nasync function ctxFor(h: CloudHandle): Promise<Ctx> {\n const { target: remote, container } = parseSandboxId(h.sandboxId);\n const target = await ensureTunnel(h.sandboxId, remote);\n return { target, remote, container };\n}\n\n/** `docker inspect` state string -> the provider-neutral CloudState. */\nexport function mapDockerState(status: string): CloudState {\n switch (status.trim()) {\n case 'running':\n return 'running';\n case 'paused':\n return 'paused';\n case 'created':\n case 'exited':\n case 'dead':\n case 'restarting':\n case 'removing':\n return 'stopped';\n default:\n return 'missing';\n }\n}\n\n/**\n * `docker port <c> <p>` -> the ephemeral port docker bound on the remote's\n * loopback. Its output is `127.0.0.1:49153` (possibly several lines, one per\n * binding); we take the first with a port.\n */\nexport function parseDockerPort(stdout: string): number | null {\n for (const line of stdout.split(/\\r?\\n/)) {\n const m = /:(\\d+)\\s*$/.exec(line.trim());\n if (m?.[1]) {\n const port = Number.parseInt(m[1], 10);\n if (Number.isFinite(port) && port > 0) return port;\n }\n }\n return null;\n}\n\n/** Parse `--size` as `cpu-memory` GB (e2b's spec shape). */\nexport function parseSize(size: string | undefined): { cpu?: number; memory?: number } {\n if (!size) return {};\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(size.trim());\n if (!m?.[1]) return {};\n const cpu = Number.parseInt(m[1], 10);\n const memory = m[2] ? Number.parseInt(m[2], 10) : undefined;\n return { cpu, ...(memory !== undefined ? { memory } : {}) };\n}\n\n/**\n * The `docker run` argv for a box. Mirrors the local provider's `runBox` flags\n * — the cap/security/cgroup set is what makes the in-box dockerd work, and the\n * two must not drift.\n */\nexport function buildRunArgv(opts: {\n container: string;\n image: string;\n env: Record<string, string>;\n ports: number[];\n dockerVolume: string;\n cpu?: number;\n memory?: number;\n /** The remote engine is itself inside an AgentBox sandbox — see `remoteIsNested`. */\n nestedEngine?: boolean;\n}): string[] {\n const argv = [\n 'run',\n '-d',\n '--name',\n opts.container,\n '--hostname',\n opts.container,\n // The in-box dockerd needs these: SYS_ADMIN to `mount -t overlay` for\n // overlay2, NET_ADMIN for its bridge + iptables NAT, /dev/fuse +\n // apparmor:unconfined for the fuse-overlayfs fallback, seccomp:unconfined\n // because the default profile blocks syscalls nested containers need, and a\n // private cgroup namespace so runc can create its own slice. Same set as\n // the local docker provider; we still avoid --privileged.\n '--cap-add=SYS_ADMIN',\n '--cap-add=NET_ADMIN',\n '--device=/dev/fuse',\n '--security-opt=apparmor:unconfined',\n '--security-opt=seccomp=unconfined',\n '--cgroupns=private',\n ];\n if (opts.nestedEngine) {\n // The engine is itself inside an AgentBox sandbox, which has no\n // CAP_SYS_PTRACE. Its dockerd therefore cannot bind-mount /proc/<pid>/ns/net\n // for a container whose init runs as a different uid than the daemon —\n // and the box image's default USER is vscode (1000), so `docker run` dies\n // with \"bind-mount /proc/N/ns/net: permission denied\". Forcing init to uid 0\n // makes its /proc readable by the daemon and netns setup succeeds.\n //\n // The local docker provider does the same thing (see `runBox`), but keys it\n // off ITS OWN `AGENTBOX=1`. Here that would be the wrong signal: the CLI can\n // run inside a box while the engine sits on a real machine that has no such\n // limitation. What matters is whether the ENGINE is nested, so we ask it.\n argv.push('--user', '0');\n }\n if (opts.cpu) argv.push('--cpus', String(opts.cpu));\n if (opts.memory) argv.push('--memory', `${String(opts.memory)}g`);\n // /var/lib/docker on a volume, not the container layer: without it, every\n // image the agent pulls inside the box would be captured by `docker commit`\n // and bloat each checkpoint.\n argv.push('-v', `${opts.dockerVolume}:/var/lib/docker`);\n for (const port of opts.ports) {\n // Bind the REMOTE's loopback only: the box is reached through the SSH\n // tunnel, so there is no reason to expose it on the remote's LAN.\n argv.push('-p', `127.0.0.1:0:${String(port)}`);\n }\n for (const [k, v] of Object.entries(opts.env)) {\n argv.push('-e', `${k}=${v}`);\n }\n argv.push(opts.image, 'sleep', 'infinity');\n return argv;\n}\n\nexport const remoteDockerBackend: CloudBackend = {\n name: BACKEND_NAME,\n\n async provision(req: CloudProvisionRequest): Promise<CloudHandle> {\n const log = req.onLog ?? ((): void => {});\n // The SSH destination is resolved by the CLI (`docker:<host>` /\n // --remote-host / box.remoteDockerHost) and threaded through providerOptions.\n const spec = (req.host ?? '').trim();\n if (!spec) {\n throw new Error(\n 'remote-docker: no host. Register one with `agentbox remote-docker add <alias> <[user@]host[:port]>`, then use `agentbox docker:<alias> …` / `--remote-host <alias>` / `box.remoteDockerHost`.',\n );\n }\n // Alias-only: the box is created against a registered alias, and its sandbox\n // id bakes that alias. `requireHostAlias` fails fast (before any remote work)\n // if the reference isn't registered.\n requireHostAlias(spec);\n const remote = parseRemoteTarget(spec);\n const container = containerNameFor(req.name);\n const sandboxId = makeSandboxId(remote.spec, container);\n const target = await ensureTunnel(sandboxId, remote);\n\n // A checkpoint is a `docker commit`ed image on THIS engine; otherwise ensure\n // the fingerprint-tagged base image is present (pull, else build).\n let image: string;\n if (req.snapshot) {\n const snap = parseSnapshotName(req.snapshot);\n // A checkpoint cannot follow you to another machine: the image lives on\n // the engine that committed it. Read as \"gone\" rather than erroring, so\n // the scaffold prunes the dangling manifest and builds a fresh box.\n if (snap.host !== remote.spec) {\n throw new Error(\n `snapshot expired or deleted: it was captured on ${snap.host}, not ${remote.spec} (a remote-docker checkpoint is local to its engine)`,\n );\n }\n image = snap.imageRef;\n const probe = await dockerOnRemote(target, ['image', 'inspect', image]);\n if (probe.exitCode !== 0) {\n // Same contract as the other clouds: a vanished snapshot must read as\n // \"gone\" so the scaffold prunes the manifest and re-provisions from base.\n throw new Error(`snapshot expired or deleted: ${image} is not on ${remote.spec}`);\n }\n } else {\n const ensured = await ensureRemoteImage(target, {\n imageRef: req.image && req.image !== 'agentbox/box:dev' ? req.image : undefined,\n onLog: log,\n });\n image = ensured.ref;\n }\n\n const { cpu, memory } = parseSize(req.size);\n const dockerVolume = `agentbox-docker-${container}`;\n await dockerOnRemoteOrThrow(target, ['volume', 'create', dockerVolume]);\n\n const nestedEngine = await remoteIsNested(target);\n if (nestedEngine) {\n log('[provision] remote engine is itself an AgentBox box — running the box init as root');\n }\n\n const argv = buildRunArgv({\n container,\n image,\n env: req.env ?? {},\n ports: portsToPublish(req.exposePorts),\n dockerVolume,\n nestedEngine,\n ...(cpu !== undefined ? { cpu } : {}),\n ...(memory !== undefined ? { memory } : {}),\n });\n log(`[provision] docker run ${container} on ${remote.spec}`);\n await dockerOnRemoteOrThrow(target, argv, { timeoutMs: 300_000 });\n\n return {\n sandboxId,\n resources: {\n ...(cpu !== undefined ? { cpu } : {}),\n ...(memory !== undefined ? { memory } : {}),\n },\n };\n },\n\n async get(sandboxId: string): Promise<CloudHandle | null> {\n let ctx: Ctx;\n try {\n ctx = await ctxFor({ sandboxId });\n } catch {\n return null;\n }\n const res = await dockerOnRemote(ctx.target, [\n 'inspect',\n '-f',\n '{{.State.Status}}',\n ctx.container,\n ]);\n return res.exitCode === 0 ? { sandboxId } : null;\n },\n\n /**\n * Every other cloud can ask its API \"what sandboxes exist?\". Here there is no\n * API and no registry of engines — a machine only becomes ours by being named\n * in a box record or in `box.remoteDockerHost`. So enumeration means: work out\n * which engines we have ever used, and ask each of them. An engine that has\n * gone away is skipped rather than fatal, since prune must still report on the\n * ones that answer.\n */\n async list(): Promise<CloudSandboxSummary[]> {\n const hosts = await knownHosts();\n const out: CloudSandboxSummary[] = [];\n for (const host of hosts) {\n try {\n out.push(...(await listOnHost(host)));\n } catch {\n // unreachable engine — nothing to report from it\n }\n }\n return out;\n },\n\n async start(h): Promise<void> {\n const ctx = await ctxFor(h);\n await dockerOnRemoteOrThrow(ctx.target, ['start', ctx.container], { timeoutMs: 120_000 });\n },\n\n async stop(h): Promise<void> {\n const ctx = await ctxFor(h);\n await dockerOnRemoteOrThrow(ctx.target, ['stop', ctx.container], { timeoutMs: 120_000 });\n },\n\n /**\n * A true freeze (SIGSTOP-equivalent via the freezer cgroup), not cold storage:\n * the container keeps its memory and its published ports, so resume is instant\n * and the forwarded ports stay valid.\n */\n async pause(h): Promise<void> {\n const ctx = await ctxFor(h);\n const state = await currentState(ctx);\n if (state !== 'running') return;\n await dockerOnRemoteOrThrow(ctx.target, ['pause', ctx.container]);\n },\n\n async resume(h): Promise<void> {\n const ctx = await ctxFor(h);\n const state = await currentState(ctx);\n if (state === 'paused') {\n await dockerOnRemoteOrThrow(ctx.target, ['unpause', ctx.container]);\n return;\n }\n if (state !== 'running') {\n await dockerOnRemoteOrThrow(ctx.target, ['start', ctx.container], { timeoutMs: 120_000 });\n }\n },\n\n async destroy(h): Promise<void> {\n const ctx = await ctxFor(h);\n // Idempotent: `rm -f` on a missing container is a no-op we tolerate, since\n // destroy must converge even after a partially-failed create.\n await dockerOnRemote(ctx.target, ['rm', '-f', ctx.container], { timeoutMs: 120_000 });\n await dockerOnRemote(ctx.target, ['volume', 'rm', '-f', `agentbox-docker-${ctx.container}`]);\n await tunnels.close(h.sandboxId);\n },\n\n async state(h): Promise<CloudState> {\n let ctx: Ctx;\n try {\n ctx = await ctxFor(h);\n } catch {\n // Unreachable host — the box may well be fine, but we cannot see it.\n return 'missing';\n }\n return currentState(ctx);\n },\n\n async exec(h, cmd: string, opts: CloudExecOptions = {}): Promise<CloudExecResult> {\n const ctx = await ctxFor(h);\n const argv = dockerExecArgv(ctx.container, cmd, {\n user: opts.user ?? CONTAINER_USER,\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env ? { env: opts.env } : {}),\n });\n const res = await dockerOnRemote(ctx.target, argv, {\n timeoutMs: opts.attemptTimeoutMs ?? 300_000,\n });\n return { exitCode: res.exitCode, stdout: res.stdout, stderr: res.stderr };\n },\n\n async uploadFile(h, localPath: string, remotePath: string): Promise<void> {\n const ctx = await ctxFor(h);\n // The seed tars land in /tmp before an in-box extract; make sure the parent\n // exists, since `cat >` won't create it.\n await dockerOnRemote(\n ctx.target,\n dockerExecArgv(ctx.container, bashScript(`mkdir -p ${shellDir(remotePath)}`), {\n user: 'root',\n }),\n );\n await pipeFileIntoContainer(ctx.target, ctx.container, createReadStream(localPath), remotePath);\n },\n\n async downloadFile(h, remotePath: string, localPath: string): Promise<void> {\n const ctx = await ctxFor(h);\n await mkdir(dirname(localPath), { recursive: true });\n await pipeFileFromContainer(\n ctx.target,\n ctx.container,\n remotePath,\n createWriteStream(localPath),\n );\n },\n\n async listFiles(h, remoteDir: string): Promise<CloudFileEntry[]> {\n const ctx = await ctxFor(h);\n const res = await dockerOnRemote(\n ctx.target,\n dockerExecArgv(\n ctx.container,\n `find ${quote(remoteDir)} -mindepth 1 -maxdepth 1 -printf '%f\\\\t%y\\\\n'`,\n ),\n );\n if (res.exitCode !== 0) return [];\n const out: CloudFileEntry[] = [];\n for (const line of res.stdout.split(/\\r?\\n/)) {\n const [name, kind] = line.split('\\t');\n if (name) out.push({ name, isDir: kind === 'd' });\n }\n return out;\n },\n\n /**\n * The container's port is published on the REMOTE's loopback; we forward that\n * to a free local port over the box's ControlMaster. So the URL is always\n * `http://127.0.0.1:<local>` — reachable from the host browser and from the\n * host relay's poller alike.\n */\n async previewUrl(h, port: number): Promise<CloudPreviewUrl> {\n const ctx = await ctxFor(h);\n const remotePort = await publishedPort(ctx, port);\n const localPort = await tunnels.forward(h.sandboxId, remotePort);\n return { url: `http://127.0.0.1:${String(localPort)}` };\n },\n\n /** SSH is already the auth gate, so a \"signed\" URL is just the tunneled one. */\n async signedPreviewUrl(h, port: number): Promise<CloudPreviewUrl> {\n return remoteDockerBackend.previewUrl(h, port);\n },\n\n /**\n * The poller calls this when the local port stops answering — typically a\n * ControlMaster that died across a host sleep/wake. Re-open the master AND\n * re-read `docker port`: a container restart reassigns the remote's ephemeral\n * port, so a forward to the old one would connect to nothing.\n */\n async refreshPreviewUrl(h, port: number): Promise<CloudPreviewUrl> {\n const { target: remote } = parseSandboxId(h.sandboxId);\n await refreshTunnel(h.sandboxId, remote);\n return remoteDockerBackend.previewUrl(h, port);\n },\n\n async createSnapshot(h, snapshotName: string): Promise<void> {\n const ctx = await ctxFor(h);\n const snap = parseSnapshotName(snapshotName);\n await dockerOnRemoteOrThrow(ctx.target, ['commit', ctx.container, snap.imageRef], {\n timeoutMs: 600_000,\n });\n },\n\n async deleteSnapshot(snapshotName: string): Promise<void> {\n const snap = parseSnapshotName(snapshotName);\n try {\n const target = await ensureTunnel(snapshotTunnelId(snap.host), parseRemoteTarget(snap.host));\n await dockerOnRemote(target, ['image', 'rm', '-f', snap.imageRef]);\n } catch {\n // Unreachable host or already gone — best-effort, matching the other\n // clouds: the caller drops the local manifest either way.\n }\n },\n\n async snapshotExists(snapshotName: string): Promise<boolean> {\n let snap: ParsedSnapshot;\n try {\n snap = parseSnapshotName(snapshotName);\n } catch {\n return false;\n }\n try {\n const target = await ensureTunnel(snapshotTunnelId(snap.host), parseRemoteTarget(snap.host));\n const res = await dockerOnRemote(target, ['image', 'inspect', snap.imageRef]);\n return res.exitCode === 0;\n } catch {\n // Contract: must never throw. An unreachable engine reads as \"not\n // bootable\", which is the truth from here.\n return false;\n }\n },\n};\n\n/**\n * Engines this machine has used: every host named by a remote-docker box record,\n * plus the configured default. Deduped, order-stable.\n */\nasync function knownHosts(): Promise<string[]> {\n const hosts = new Set<string>();\n try {\n const state = await readState();\n for (const box of state.boxes) {\n if (box.provider !== BACKEND_NAME || !box.cloud?.sandboxId) continue;\n try {\n hosts.add(parseSandboxId(box.cloud.sandboxId).target.spec);\n } catch {\n // a malformed id names no engine we could ask\n }\n }\n } catch {\n // no state yet\n }\n try {\n const cfg = await loadEffectiveConfig(process.cwd());\n const dflt = (cfg.effective.box.remoteDockerHost || '').trim();\n if (dflt) hosts.add(dflt);\n } catch {\n // no config — the box records are all we have\n }\n return [...hosts];\n}\n\n/** List agentbox containers on one remote engine — the host-scoped `list()`. */\nexport async function listOnHost(spec: string): Promise<CloudSandboxSummary[]> {\n const remote = parseRemoteTarget(spec);\n const target = await ensureTunnel(`list:${remote.spec}`, remote);\n const res = await dockerOnRemote(target, [\n 'ps',\n '-a',\n '--filter',\n 'name=agentbox-',\n '--format',\n '{{.Names}}\\t{{.State}}\\t{{.CreatedAt}}',\n ]);\n if (res.exitCode !== 0) return [];\n const out: CloudSandboxSummary[] = [];\n for (const line of res.stdout.split(/\\r?\\n/)) {\n const [name, state, createdAt] = line.split('\\t');\n if (!name) continue;\n out.push({\n sandboxId: makeSandboxId(remote.spec, name),\n name,\n ...(createdAt ? { createdAt } : {}),\n state: mapDockerState(state ?? ''),\n });\n }\n return out;\n}\n\nasync function currentState(ctx: Ctx): Promise<CloudState> {\n const res = await dockerOnRemote(ctx.target, [\n 'inspect',\n '-f',\n '{{.State.Status}}',\n ctx.container,\n ]);\n if (res.exitCode !== 0) return 'missing';\n return mapDockerState(res.stdout);\n}\n\nasync function publishedPort(ctx: Ctx, containerPort: number): Promise<number> {\n const res = await dockerOnRemote(ctx.target, ['port', ctx.container, String(containerPort)]);\n const port = res.exitCode === 0 ? parseDockerPort(res.stdout) : null;\n if (port === null) {\n throw new Error(\n `remote-docker: container port ${String(containerPort)} is not published on ${ctx.container}. ` +\n 'Docker port mappings are fixed at create — a service exposed after the box was made is only ' +\n 'reachable through the :80 WebProxy until the box is recreated.',\n );\n }\n return port;\n}\n\nfunction shellDir(path: string): string {\n const slash = path.lastIndexOf('/');\n return quote(slash > 0 ? path.slice(0, slash) : '/');\n}\n\nfunction quote(s: string): string {\n return `'${s.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * `buildRemoteDockerAttach` — this provider's override of `Provider.buildAttach`.\n *\n * The cloud scaffold's default appends the inner command to the backend's\n * `attachArgv`, which for an SSH backend lands it on the *host* it connects to.\n * For hetzner that host IS the box. Here it is the machine running the engine —\n * the box is a container on it — so the inner command has to be wrapped in a\n * `docker exec` before it crosses the wire. Hence a full override (the same\n * pattern vercel and e2b use for their non-SSH attaches).\n *\n * The result is a plain `ssh … -t 'docker exec -it … bash -lc <tmux>'`, so the\n * CLI's PTY wrapper drives it exactly like any other provider's attach.\n */\n\nimport type { AttachKind, AttachSpec, BoxRecord, BuildAttachOptions } from '@agentbox/core';\nimport {\n hostTermForCloud,\n quoteShellArg,\n quoteShellArgv,\n renderInnerCommand,\n} from '@agentbox/sandbox-cloud';\nimport { sshDestination, sshOptArgs } from '@agentbox/sandbox-core';\nimport { ensureTunnel, loginShell } from './remote-docker.js';\nimport { parseSandboxId } from './target.js';\n\nconst CONTAINER_USER = 'vscode';\n\nexport async function buildRemoteDockerAttach(\n box: BoxRecord,\n kind: AttachKind,\n opts: BuildAttachOptions = {},\n): Promise<AttachSpec> {\n const sandboxId = box.cloud?.sandboxId;\n if (!sandboxId) {\n throw new Error(`remote-docker box ${box.name} has no sandboxId — record is malformed`);\n }\n const { target: remote, container } = parseSandboxId(sandboxId);\n const target = await ensureTunnel(sandboxId, remote);\n\n // The tmux session bring-up + attach, identical to every other cloud box.\n const inner = renderInnerCommand(kind, opts);\n const dockerArgv = [\n 'exec',\n // `detached` only creates the session, so it needs no TTY — and asking for\n // one would make docker fail when the CLI runs it without a terminal.\n ...(opts.detached ? ['-i'] : ['-it']),\n '-u',\n opts.user ?? CONTAINER_USER,\n '-e',\n `TERM=${hostTermForCloud()}`,\n container,\n 'bash',\n '-lc',\n inner,\n ];\n // Wrap in a LOGIN shell for the same reason every other remote invocation does\n // (see `loginShell` in ./remote-docker.ts): ssh runs this string in the remote\n // user's NON-login shell, where `docker` is often not on PATH (Docker Desktop\n // in /usr/local/bin, OrbStack in ~/.orbstack/bin). `bash -lc` sources the\n // profile so `docker` resolves. The `-t` PTY flows through bash into `docker\n // exec -it` unchanged.\n const remoteCommand = loginShell(`docker ${quoteShellArgv(dockerArgv)}`);\n\n const argv = [\n 'ssh',\n ...sshOptArgs(target),\n // -t forces TTY allocation through ssh; without it tmux and readline break.\n ...(opts.detached ? [] : ['-t']),\n sshDestination(target),\n // One argv element: ssh hands the string to the remote login shell, which\n // re-parses it — so the docker argv is quoted, not concatenated.\n remoteCommand,\n ];\n return { argv };\n}\n\n/** Exposed for the unit test — the quoting is the part worth pinning down. */\nexport const _internal = { quoteShellArg };\n","/**\n * Making the BOX (not the engine) reachable over SSH, so `agentbox open`\n * (sshfs), `agentbox code` (Remote-SSH) and `agentbox connect` work exactly as\n * they do for every other provider.\n *\n * The box is a container on someone else's machine, and its sshd is published\n * on THAT machine's loopback (`-p 127.0.0.1:0:22`). So there is no host:port a\n * local ssh could dial directly. The answer is `ProxyJump`: ssh connects to the\n * engine's machine, and the engine dials `127.0.0.1:<published port>` on our\n * behalf — which is precisely the address the box's sshd is listening on from\n * where the jump host stands.\n *\n * Host agentbox-<box>\n * HostName 127.0.0.1 # as resolved ON the jump host\n * Port <published>\n * User vscode\n * ProxyJump <engine> # the ssh destination the box lives on\n * IdentityFile ~/.agentbox/remote-docker/boxes/<id>/ssh/id_ed25519\n *\n * No `ssh -L` forward is involved: ssh's own transport does the hop, so the\n * alias keeps working in any process (VS Code, sshfs) without AgentBox having\n * to hold a tunnel open for it.\n *\n * The private key never leaves the host. The public half is installed into the\n * box's `authorized_keys` over the ControlMaster we already have.\n */\n\nimport type { BoxRecord, SshTargetRecord } from '@agentbox/core';\nimport { bashScript, quoteShellArg } from '@agentbox/sandbox-cloud';\nimport { defaultBoxSshDir, mintSshKey } from '@agentbox/sandbox-core';\nimport { CONTAINER_USER, dockerExecArgv, dockerOnRemote, ensureTunnel } from './remote-docker.js';\nimport { resolveConnection } from './hosts-registry.js';\nimport { parseSandboxId } from './target.js';\nimport { parseDockerPort } from './backend.js';\n\n/** The box image's sshd listens here; we publish it on the engine's loopback. */\nconst SSH_CONTAINER_PORT = 22;\n\n/**\n * Bring the box's sshd up, make sure it trusts this host's per-box key, and\n * return the connection target. Idempotent — safe to call on every start: the\n * key is reused when present, `authorized_keys` is only appended to when the key\n * isn't already there, and sshd is only launched if it isn't already listening.\n *\n * Returns null (rather than throwing) when sshd doesn't come up, so a failure\n * here degrades `open`/`code` instead of breaking the lifecycle command that\n * triggered it.\n */\nexport async function resolveBoxSshTarget(box: BoxRecord): Promise<SshTargetRecord | null> {\n const sandboxId = box.cloud?.sandboxId;\n if (!sandboxId) return null;\n const { target: remote, container } = parseSandboxId(sandboxId);\n const conn = await ensureTunnel(sandboxId, remote);\n\n const key = await mintSshKey(\n defaultBoxSshDir(sandboxId, 'remote-docker'),\n `agentbox-${box.name}`,\n );\n\n // Install the public key. `grep -q` first so a restart doesn't grow the file\n // without bound. Runs as root because on a nested engine the container's init\n // is uid 0 and ~vscode/.ssh may not exist yet; the chown puts it back.\n const install = [\n `install -d -m 700 -o ${CONTAINER_USER} -g ${CONTAINER_USER} /home/${CONTAINER_USER}/.ssh`,\n `touch /home/${CONTAINER_USER}/.ssh/authorized_keys`,\n `grep -qF ${quoteShellArg(key.publicKey)} /home/${CONTAINER_USER}/.ssh/authorized_keys || echo ${quoteShellArg(key.publicKey)} >> /home/${CONTAINER_USER}/.ssh/authorized_keys`,\n `chown -R ${CONTAINER_USER}:${CONTAINER_USER} /home/${CONTAINER_USER}/.ssh`,\n `chmod 600 /home/${CONTAINER_USER}/.ssh/authorized_keys`,\n ].join(' && ');\n const installRes = await dockerOnRemote(\n conn,\n dockerExecArgv(container, bashScript(install), { user: 'root' }),\n );\n if (installRes.exitCode !== 0) return null;\n\n // Start sshd (the image ships `agentbox-sshd-start`, which manages the host\n // keys and /run/sshd). Idempotent, and a no-op when it's already listening.\n await dockerOnRemote(\n conn,\n dockerExecArgv(container, bashScript('/usr/local/bin/agentbox-sshd-start'), {\n user: 'root',\n }),\n { timeoutMs: 60_000 },\n );\n\n // The port docker published on the ENGINE's loopback. Re-read every time: it\n // is ephemeral and gets reassigned whenever the container restarts.\n const portRes = await dockerOnRemote(conn, ['port', container, String(SSH_CONTAINER_PORT)]);\n const port = portRes.exitCode === 0 ? parseDockerPort(portRes.stdout) : null;\n if (port === null) return null;\n\n return {\n // Resolved on the jump host, not here.\n host: '127.0.0.1',\n port,\n user: CONTAINER_USER,\n identityFile: key.privatePath,\n // The box id bakes an alias; ssh on THIS host can't resolve an AgentBox\n // alias, so the ProxyJump must be the alias's real connection string.\n proxyJump: resolveConnection(remote.spec),\n };\n}\n","/**\n * Doctor probes for the remote-docker provider.\n *\n * There is no credential to check — the provider authenticates as you, through\n * your own `~/.ssh/config` and agent. What *can* be wrong is the destination:\n * unset, unreachable, or reachable but with no docker on the login-shell PATH.\n * So the checks are exactly those three, run against the configured default.\n */\n\nimport { loadEffectiveConfig } from '@agentbox/config';\nimport { detectPortless, portlessDoctorRow } from '@agentbox/sandbox-cloud';\nimport { errSummary, type CheckResult } from '@agentbox/sandbox-core';\nimport { probeRemoteEngine } from './remote-docker.js';\nimport { getHostAlias } from './hosts-registry.js';\nimport { readPreparedState } from './prepared-state.js';\n\n// No `readCredStatus` / `ensureCredentials` on this provider's module, and that\n// is not an omission: there is no credential to store or prompt for. The CLI\n// and the hub both feature-detect those, so they simply show no login row.\n\nexport async function doctorChecks(): Promise<CheckResult[]> {\n try {\n const cfg = await loadEffectiveConfig(process.cwd());\n const alias = (cfg.effective.box.remoteDockerHost || '').trim();\n if (!alias) {\n return [\n {\n label: 'remote engine',\n status: 'warn',\n detail: 'no default host alias set',\n hint: '`agentbox remote-docker add <alias> <[user@]host[:port]>`',\n },\n ];\n }\n // box.remoteDockerHost is an alias; resolve it through the registry.\n const entry = getHostAlias(alias);\n if (!entry) {\n return [\n {\n label: 'remote engine',\n status: 'warn',\n detail: `host alias '${alias}' is not registered`,\n hint: `\\`agentbox remote-docker add ${alias} <[user@]host[:port]>\\``,\n },\n ];\n }\n\n const probe = await probeRemoteEngine(entry.ssh);\n const engineRes: CheckResult = probe.ok\n ? {\n label: 'remote engine',\n status: 'ok',\n detail: `${alias} → ${entry.ssh} — docker ${probe.version} (${probe.os}/${probe.arch})`,\n }\n : {\n label: 'remote engine',\n status: 'fail',\n detail: probe.error ?? 'unusable',\n hint: `check that \\`ssh ${entry.ssh} true\\` works and docker is installed there`,\n };\n\n const prepared = readPreparedState();\n const baked = prepared?.hosts[alias];\n const imageRes: CheckResult = baked\n ? {\n label: 'box image',\n status: 'ok',\n detail: `${baked.imageRef} (${baked.cliVersion ?? '—'})`,\n }\n : {\n label: 'box image',\n status: 'warn',\n detail: 'not baked on this host yet',\n hint: `\\`agentbox prepare --provider docker:${alias}\\` (otherwise the first create bakes it)`,\n };\n\n // Host Portless mints the <box>.localhost alias for the SSH-forwarded port;\n // without it the box's web URL degrades to a raw loopback port.\n const portlessRes = portlessDoctorRow(await detectPortless());\n return [engineRes, imageRes, portlessRes];\n } catch (err) {\n return [{ label: 'remote engine', status: 'warn', detail: errSummary(err) }];\n }\n}\n","/**\n * Interactive host registration for the `agentbox install` wizard.\n *\n * remote-docker has no credential to log in with — what it needs instead is a\n * host: an alias name + an SSH connection string. This drives that prompt flow\n * (the interactive twin of `remote-docker add`), registers the alias, and pins it\n * as the default host so the wizard's subsequent bake step + plain `agentbox\n * claude` target it.\n *\n * Install-only on purpose: it must NOT hang off `providerModule.ensureCredentials`,\n * which `getProvider()` runs on every create AND every box lifecycle op — a prompt\n * there would fire constantly. The wizard calls this directly instead.\n */\n\nimport * as p from '@clack/prompts';\nimport { setConfigValue } from '@agentbox/config';\nimport { probeRemoteEngine } from './remote-docker.js';\nimport { assertValidAlias, getHostAlias, listHostAliases, upsertHostAlias } from './hosts-registry.js';\n\n/**\n * Prompt for an alias + SSH connection, probe it, register it, and set it as the\n * default host (`box.remoteDockerHost`, global). Returns the alias, or `null` if\n * there's no TTY or the user backs out. Never throws.\n */\nexport async function interactiveRegisterHost(): Promise<string | null> {\n if (!process.stdin.isTTY) {\n p.log.warn(\n 'remote-docker needs a host — run `agentbox remote-docker add <alias> <[user@]host[:port]>` to register one',\n );\n return null;\n }\n\n const alias = await p.text({\n message: 'Name this remote host (a short alias)',\n placeholder: 'buildbox',\n validate: (value) => {\n const v = (value ?? '').trim();\n if (!v) return 'required';\n try {\n assertValidAlias(v);\n } catch (err) {\n return err instanceof Error ? err.message : String(err);\n }\n if (getHostAlias(v)) return `'${v}' is already registered`;\n return undefined;\n },\n });\n if (p.isCancel(alias)) return null;\n const name = alias.trim();\n\n // Prompt + probe in a loop so a bad connection can be corrected without\n // restarting the wizard.\n for (;;) {\n const ssh = await p.text({\n message: 'SSH connection (an ~/.ssh/config alias or [user@]host[:port])',\n placeholder: 'user@host',\n validate: (value) => ((value ?? '').trim() ? undefined : 'required'),\n });\n if (p.isCancel(ssh)) return null;\n const conn = ssh.trim();\n\n const s = p.spinner();\n s.start(`probing ${conn}`);\n const res = await probeRemoteEngine(conn);\n if (!res.ok) {\n s.stop(`${conn}: unusable`);\n p.log.error(res.error ?? 'remote engine unusable');\n const retry = await p.confirm({\n message: 'Try a different SSH connection?',\n initialValue: true,\n });\n if (p.isCancel(retry) || !retry) return null;\n continue;\n }\n s.stop(`${conn}: docker ${res.version} (${res.os}/${res.arch})`);\n\n upsertHostAlias(name, conn);\n p.log.success(`registered '${name}' → ${conn}`);\n // Machine-level default, matching how the wizard pins box.provider global.\n await setConfigValue('global', 'box.remoteDockerHost', name, process.cwd(), { raw: true });\n // With more than one host registered, remind how to target a specific one.\n const hostCount = listHostAliases().length;\n if (hostCount > 1) {\n p.log.info(\n `you have ${String(hostCount)} remote hosts — run \\`agentbox docker:${name} claude\\` to use this one`,\n );\n }\n return name;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACwBA,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,eAAe;AACxB,SAAS,SAAS,WAAW,mBAAmB;ACLhD,SAAS,aAAa;ACFtB,SAAS,wBAAwB;AACjC,SAAS,UAAU;AACnB,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,SAAAA,cAAa;AHmBf,SAAS,iBAAiB,SAAyB;AACxD,SAAO,YAAY,OAAO;AAC5B;AAOO,SAAS,kBAAkB,MAA4B;AAC5D,QAAM,MAAM,KAAK,KAAK;AACtB,MAAI,IAAI,WAAW,GAAG;AACpB,UAAM,IAAI,MAAM,sCAAsC;EACxD;AACA,MAAI,IAAI,SAAS,GAAG,GAAG;AACrB,UAAM,IAAI;MACR,2CAA2C,GAAG;IAChD;EACF;AACA,QAAM,KAAK,IAAI,YAAY,GAAG;AAC9B,QAAM,OAAO,MAAM,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI;AAC1C,QAAM,WAAW,MAAM,IAAI,IAAI,MAAM,KAAK,CAAC,IAAI;AAC/C,MAAI,SAAS,WAAW,KAAM,SAAS,UAAa,KAAK,WAAW,GAAI;AACtE,UAAM,IAAI,MAAM,2CAA2C,GAAG,GAAG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AK,KAAK,KAAK;EAC1B;EAEA,MAAM,KAAK,aAAqB;AAC9B,UAAM,UAAU,MAAM,qBAAqB,aAAa,YAAY;AACpE,WAAO,QAAQ,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,EAAE,SAAS,UAAU,EAAE;EAC9E;EAEA,MAAM,OAAO,aAAqB,KAAa;AAC7C,UAAM,QAAQ,MAAM,uBAAuB,aAAa,cAAc,GAAG;AACzE,QAAI,CAAC,MAAO;AACZ,UAAM,oBAAoB,iBAAiB,MAAM,SAAS,YAAY;AACtE,UAAM,yBAAyB,aAAa,cAAc,GAAG;EAC/D;AACF;AAEO,IAAM,uBAAiC;EAC5C,GAAG;EACH,aAAa;;;;;EAKb,WAAW;EACX,YAAY;EACZ,SAAS;EACT,iBAAiB,OAAO,kBAAmB,MAAM,kBAAkB,aAAa,KAAM;AACxF;AAGO,IAAM,iBAAiC;EAC5C,UAAU;EACV,SAAS;EACT,4BAA4B,OAAO,kBAChC,MAAM,kBAAkB,aAAa,KAAM;EAC9C;AACF;","names":["execa","log","ref","execa","sshOptArgs","sshDestination","quoteShellArgv","SCHEMA","createReadStream","dirname","log","createReadStream","dirname","CONTAINER_USER","quoteShellArg","bashScript","loadEffectiveConfig"]}
|
|
@@ -284,6 +284,7 @@ import { mkdir as mkdir2, readFile as readFile2 } from "fs/promises";
|
|
|
284
284
|
import { join as join5, resolve } from "path";
|
|
285
285
|
import { execa as execa2 } from "execa";
|
|
286
286
|
import { execa as execa3 } from "execa";
|
|
287
|
+
import { createHash } from "crypto";
|
|
287
288
|
import { existsSync as existsSync2 } from "fs";
|
|
288
289
|
import { mkdir as mkdir3, rm as rm2 } from "fs/promises";
|
|
289
290
|
import { createServer } from "net";
|
|
@@ -322,11 +323,11 @@ import { stat as stat7 } from "fs/promises";
|
|
|
322
323
|
import { chmod as chmod2, mkdir as mkdir7, mkdtemp as mkdtemp4, readFile as readFile6, rename as rename3, rm as rm6, writeFile as writeFile6 } from "fs/promises";
|
|
323
324
|
import { tmpdir as tmpdir4 } from "os";
|
|
324
325
|
import { dirname as dirname8, join as join15 } from "path";
|
|
325
|
-
import { createHash } from "crypto";
|
|
326
|
+
import { createHash as createHash2 } from "crypto";
|
|
326
327
|
import { readFile as readFile7 } from "fs/promises";
|
|
327
328
|
import { join as join16 } from "path";
|
|
328
329
|
import { execa as execa6 } from "execa";
|
|
329
|
-
import { createHash as
|
|
330
|
+
import { createHash as createHash3 } from "crypto";
|
|
330
331
|
import { copyFile, mkdir as mkdir8, mkdtemp as mkdtemp5, readdir as readdir5, readFile as readFile8, rm as rm7, stat as stat8 } from "fs/promises";
|
|
331
332
|
import { homedir as homedir10, tmpdir as tmpdir5 } from "os";
|
|
332
333
|
import { basename as basename22, dirname as dirname9, join as join17 } from "path";
|
|
@@ -337,7 +338,7 @@ import { basename as basename3, join as join18, relative as relative2 } from "pa
|
|
|
337
338
|
import { execa as execa8 } from "execa";
|
|
338
339
|
import { homedir as homedir11 } from "os";
|
|
339
340
|
import { parse, stringify } from "smol-toml";
|
|
340
|
-
import { createHash as
|
|
341
|
+
import { createHash as createHash4 } from "crypto";
|
|
341
342
|
import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
342
343
|
import { readFile as readFile10 } from "fs/promises";
|
|
343
344
|
import { homedir as homedir13 } from "os";
|
|
@@ -1008,6 +1009,10 @@ async function waitForSsh(target, deadlineMs, intervalMs = 5e3) {
|
|
|
1008
1009
|
return false;
|
|
1009
1010
|
}
|
|
1010
1011
|
var HOST = "127.0.0.1";
|
|
1012
|
+
function controlSockPath(boxSshDir) {
|
|
1013
|
+
const hash = createHash("sha1").update(boxSshDir).digest("hex").slice(0, 12);
|
|
1014
|
+
return resolve22(homedir4(), ".agentbox", "cm", `${hash}.sock`);
|
|
1015
|
+
}
|
|
1011
1016
|
var SshTunnelManager = class {
|
|
1012
1017
|
/**
|
|
1013
1018
|
* `namespace` scopes the on-disk ssh dir so sandbox-ids from different
|
|
@@ -1026,7 +1031,8 @@ var SshTunnelManager = class {
|
|
|
1026
1031
|
async open(opts) {
|
|
1027
1032
|
const boxSshDir = opts.boxSshDir ?? defaultBoxSshDir(opts.boxId, this.namespace);
|
|
1028
1033
|
await mkdir3(boxSshDir, { recursive: true, mode: 448 });
|
|
1029
|
-
const controlPath =
|
|
1034
|
+
const controlPath = controlSockPath(boxSshDir);
|
|
1035
|
+
await mkdir3(join6(controlPath, ".."), { recursive: true, mode: 448 });
|
|
1030
1036
|
const knownHosts = join6(boxSshDir, "known_hosts");
|
|
1031
1037
|
const tunnel = {
|
|
1032
1038
|
controlPath,
|
|
@@ -1200,7 +1206,7 @@ var SshTunnelManager = class {
|
|
|
1200
1206
|
registerExisting(boxId, opts) {
|
|
1201
1207
|
const boxSshDir = opts.boxSshDir ?? defaultBoxSshDir(opts.boxId, this.namespace);
|
|
1202
1208
|
this.boxes.set(boxId, {
|
|
1203
|
-
controlPath:
|
|
1209
|
+
controlPath: controlSockPath(boxSshDir),
|
|
1204
1210
|
vpsHost: opts.vpsHost,
|
|
1205
1211
|
vpsUser: opts.vpsUser,
|
|
1206
1212
|
identity: opts.identity,
|
|
@@ -1348,6 +1354,12 @@ async function boxRestartServices(provider, box, names) {
|
|
|
1348
1354
|
}
|
|
1349
1355
|
return out;
|
|
1350
1356
|
}
|
|
1357
|
+
function statusBadge(s) {
|
|
1358
|
+
if (s === "ok") return "[ ok ]";
|
|
1359
|
+
if (s === "info") return "[info]";
|
|
1360
|
+
if (s === "warn") return "[warn]";
|
|
1361
|
+
return "[FAIL]";
|
|
1362
|
+
}
|
|
1351
1363
|
function firstLine(s) {
|
|
1352
1364
|
const i = s.indexOf("\n");
|
|
1353
1365
|
return i === -1 ? s : s.slice(0, i);
|
|
@@ -2778,7 +2790,7 @@ function makeHostGitPorts() {
|
|
|
2778
2790
|
return untracked.exitCode === 0 ? splitNul(untracked.stdout) : [];
|
|
2779
2791
|
},
|
|
2780
2792
|
async hashHostFile(hostMain, relPath) {
|
|
2781
|
-
return
|
|
2793
|
+
return createHash2("sha256").update(await readFile7(join16(hostMain, relPath))).digest("hex");
|
|
2782
2794
|
},
|
|
2783
2795
|
async packHostFiles(hostMain, relPaths) {
|
|
2784
2796
|
const tarOut = await execa6("tar", ["-C", hostMain, "--null", "-T", "-", "-cf", "-"], {
|
|
@@ -2828,7 +2840,7 @@ async function walkFiles(root, prefix = "") {
|
|
|
2828
2840
|
}
|
|
2829
2841
|
async function hashFile(absPath) {
|
|
2830
2842
|
const buf = await readFile8(absPath);
|
|
2831
|
-
return
|
|
2843
|
+
return createHash3("sha256").update(buf).digest("hex");
|
|
2832
2844
|
}
|
|
2833
2845
|
async function buildHostSet(name, hostDir, boxDst) {
|
|
2834
2846
|
if (hostDir === null) return { dst: boxDst, files: {}, hostDir: null };
|
|
@@ -3519,11 +3531,11 @@ function writePreparedStateRaw(provider, state) {
|
|
|
3519
3531
|
}
|
|
3520
3532
|
async function sha256OfFile(path) {
|
|
3521
3533
|
const buf = await readFile10(path);
|
|
3522
|
-
return
|
|
3534
|
+
return createHash4("sha256").update(buf).digest("hex");
|
|
3523
3535
|
}
|
|
3524
3536
|
async function computeContextSha256(files) {
|
|
3525
3537
|
const sorted = [...files].sort((a, b) => a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0);
|
|
3526
|
-
const outer =
|
|
3538
|
+
const outer = createHash4("sha256");
|
|
3527
3539
|
for (const f of sorted) {
|
|
3528
3540
|
const inner = await sha256OfFile(f.abs);
|
|
3529
3541
|
outer.update(`${f.rel}\0${inner}
|
|
@@ -3533,7 +3545,7 @@ async function computeContextSha256(files) {
|
|
|
3533
3545
|
}
|
|
3534
3546
|
function claudeInstallFingerprint(baseSha, mode) {
|
|
3535
3547
|
if (mode === "native") return baseSha;
|
|
3536
|
-
return
|
|
3548
|
+
return createHash4("sha256").update(`${baseSha}\0claude-install=npm`).digest("hex");
|
|
3537
3549
|
}
|
|
3538
3550
|
function readCliStamp() {
|
|
3539
3551
|
return {
|
|
@@ -3718,7 +3730,7 @@ async function buildImage(opts = {}) {
|
|
|
3718
3730
|
return ref;
|
|
3719
3731
|
}
|
|
3720
3732
|
async function pullOrBuild(ref, fingerprint, opts = {}) {
|
|
3721
|
-
const { writePreparedDockerState: writePreparedDockerState2 } = await import("./prepared-state-75DIZ55S-
|
|
3733
|
+
const { writePreparedDockerState: writePreparedDockerState2 } = await import("./prepared-state-75DIZ55S-TNJXWMXV.js");
|
|
3722
3734
|
const registry = opts.registry ?? BOX_IMAGE_REGISTRY;
|
|
3723
3735
|
const allowPull = opts.allowPull !== false;
|
|
3724
3736
|
if (allowPull && registry && fingerprint) {
|
|
@@ -3745,7 +3757,7 @@ async function pullOrBuild(ref, fingerprint, opts = {}) {
|
|
|
3745
3757
|
return { source: "built" };
|
|
3746
3758
|
}
|
|
3747
3759
|
async function ensureImage(ref = DEFAULT_BOX_IMAGE, opts = {}) {
|
|
3748
|
-
const { computeDockerContextFingerprint: computeDockerContextFingerprint2, readPreparedDockerState: readPreparedDockerState2, preparedMatches: preparedMatches2 } = await import("./prepared-state-75DIZ55S-
|
|
3760
|
+
const { computeDockerContextFingerprint: computeDockerContextFingerprint2, readPreparedDockerState: readPreparedDockerState2, preparedMatches: preparedMatches2 } = await import("./prepared-state-75DIZ55S-TNJXWMXV.js");
|
|
3749
3761
|
const claudeInstall = opts.claudeInstall ?? await resolveClaudeInstallMode();
|
|
3750
3762
|
const rawFingerprint = await computeDockerContextFingerprint2({
|
|
3751
3763
|
contextDir: opts.contextDir
|
|
@@ -3799,7 +3811,7 @@ function classifyDockerBaseFreshness(input) {
|
|
|
3799
3811
|
return { state: "fresh" };
|
|
3800
3812
|
}
|
|
3801
3813
|
async function evaluateDockerBaseFreshness(opts = {}) {
|
|
3802
|
-
const { computeDockerContextFingerprint: computeDockerContextFingerprint2, readPreparedDockerState: readPreparedDockerState2 } = await import("./prepared-state-75DIZ55S-
|
|
3814
|
+
const { computeDockerContextFingerprint: computeDockerContextFingerprint2, readPreparedDockerState: readPreparedDockerState2 } = await import("./prepared-state-75DIZ55S-TNJXWMXV.js");
|
|
3803
3815
|
const ref = opts.ref ?? DEFAULT_BOX_IMAGE;
|
|
3804
3816
|
const imagePresent = await imageExists(ref);
|
|
3805
3817
|
if (!imagePresent) return { state: "unprepared" };
|
|
@@ -3919,6 +3931,7 @@ export {
|
|
|
3919
3931
|
boxServicesStatusRaw,
|
|
3920
3932
|
boxRestartService,
|
|
3921
3933
|
boxRestartServices,
|
|
3934
|
+
statusBadge,
|
|
3922
3935
|
firstLine,
|
|
3923
3936
|
errSummary,
|
|
3924
3937
|
writeManagedSecrets,
|
|
@@ -4028,4 +4041,4 @@ export {
|
|
|
4028
4041
|
writePreparedDockerState,
|
|
4029
4042
|
preparedMatches
|
|
4030
4043
|
};
|
|
4031
|
-
//# sourceMappingURL=chunk-
|
|
4044
|
+
//# sourceMappingURL=chunk-UJEH2NJT.js.map
|