@madarco/agentbox 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +8 -7
  3. package/dist/{_cloud-attach-W2CFNXKO.js → _cloud-attach-7WRQH6XZ.js} +5 -5
  4. package/dist/{chunk-7PRLM3PH.js → chunk-7ZZAZPYX.js} +3 -3
  5. package/dist/{chunk-LU3WAHTU.js → chunk-BA2VLJVU.js} +3 -3
  6. package/dist/{chunk-GHFIKSBJ.js → chunk-DJQMK4RN.js} +12 -4
  7. package/dist/chunk-DJQMK4RN.js.map +1 -0
  8. package/dist/{chunk-4UNSBU5R.js → chunk-DQHMDDAT.js} +2 -2
  9. package/dist/{chunk-LCZOQTIX.js → chunk-I2OAJS3L.js} +40 -377
  10. package/dist/{chunk-LCZOQTIX.js.map → chunk-I2OAJS3L.js.map} +1 -1
  11. package/dist/{chunk-5F5SOSDY.js → chunk-JGZSA5ZI.js} +72 -23
  12. package/dist/chunk-JGZSA5ZI.js.map +1 -0
  13. package/dist/{chunk-7C5MOA4Z.js → chunk-K5KOLYIL.js} +3 -3
  14. package/dist/{chunk-Y3OPQWAQ.js → chunk-PK2QF4IR.js} +576 -198
  15. package/dist/chunk-PK2QF4IR.js.map +1 -0
  16. package/dist/{chunk-VZC5J44U.js → chunk-UIFL7F2G.js} +55 -38
  17. package/dist/chunk-UIFL7F2G.js.map +1 -0
  18. package/dist/{chunk-NH3W6HUZ.js → chunk-ZY7M7MXH.js} +41 -16
  19. package/dist/chunk-ZY7M7MXH.js.map +1 -0
  20. package/dist/chunk-ZYKNSHOH.js +259 -0
  21. package/dist/chunk-ZYKNSHOH.js.map +1 -0
  22. package/dist/{dist-IGQNVIV3.js → dist-5IICYSR6.js} +42 -374
  23. package/dist/{dist-IGQNVIV3.js.map → dist-5IICYSR6.js.map} +1 -1
  24. package/dist/{dist-KL73Z37T.js → dist-AR5CHRSV.js} +86 -45
  25. package/dist/{dist-KL73Z37T.js.map → dist-AR5CHRSV.js.map} +1 -1
  26. package/dist/{dist-3V5SLNK4.js → dist-DTNYMBQ5.js} +12 -12
  27. package/dist/{dist-UB3PYSCG.js → dist-K4LNH3EC.js} +6 -6
  28. package/dist/{dist-BIDAC4H4.js → dist-POVRY7HO.js} +8 -4
  29. package/dist/{dist-SBDYDH7H.js → dist-U2SVLJUQ.js} +4 -2
  30. package/dist/{dist-I5OBPLP2.js → dist-XYY6SIKG.js} +6 -6
  31. package/dist/dist-YA7EXBGG.js +809 -0
  32. package/dist/dist-YA7EXBGG.js.map +1 -0
  33. package/dist/index.js +962 -583
  34. package/dist/index.js.map +1 -1
  35. package/dist/{prepared-state-OBM2F7CU-DY7TZV4R.js → prepared-state-75DIZ55S-W6NU3S3B.js} +2 -2
  36. package/package.json +8 -7
  37. package/runtime/_shared/ctl.cjs +83 -36
  38. package/runtime/digitalocean/ctl.cjs +83 -36
  39. package/runtime/docker/packages/ctl/dist/bin.cjs +83 -36
  40. package/runtime/e2b/ctl.cjs +83 -36
  41. package/runtime/hetzner/ctl.cjs +83 -36
  42. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  43. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  44. package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js +1 -1
  45. package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js.nft.json +1 -1
  46. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  47. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  48. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  49. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  50. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  51. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  52. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  53. package/runtime/hub/apps/hub/.next/server/chunks/0-fj_better-auth_dist_adapters_kysely-adapter_index_mjs_0btft52._.js +3 -0
  54. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d1lmiq._.js +5 -5
  55. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +1 -1
  56. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-9g0ae._.js +1 -1
  57. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bqbkd5._.js +1 -1
  58. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__19pc87s._.js → [root-of-the-server]__1k8g143._.js} +2 -2
  59. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qa4a0v._.js +1 -1
  60. package/runtime/hub/apps/hub/.next/server/chunks/_0760z6y._.js +4 -4
  61. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_0xy-j7z._.js +1 -1
  62. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_010858m.js +1 -1
  63. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_04zwxnx.js +1 -1
  64. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_06exuc7.js +1 -1
  65. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2ldrt.js +1 -1
  66. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2tzep.js +1 -1
  67. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_116nh32.js +1 -1
  68. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_11dyjcb.js +1 -1
  69. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_1_4knli.js +1 -1
  70. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__08-1wwu._.js +1 -1
  71. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0c9mbcn._.js +1 -1
  72. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0gdfxj4._.js +1 -1
  73. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0kc-hwp._.js +1 -1
  74. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0lu73p6._.js +1 -1
  75. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__10bfmwi._.js +1 -1
  76. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__18qvdzb._.js +1 -1
  77. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1l2urlw._.js +1 -1
  78. package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0ro6vh6._.js +1 -1
  79. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  80. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  81. package/runtime/hub/apps/hub/{auth-MVL4NCQC.js → auth-DC44GQZY.js} +2 -2
  82. package/runtime/hub/apps/hub/{auth-config-GRIXACTV.js → auth-config-LALRDYDO.js} +2 -2
  83. package/runtime/hub/apps/hub/{chunk-JLG5JJXD.js → chunk-3FJNKSNZ.js} +1 -1
  84. package/runtime/hub/apps/hub/{chunk-LNHPLR3L.js → chunk-4QY2VZCF.js} +509 -135
  85. package/runtime/hub/apps/hub/{chunk-QBJOF5D3.js → chunk-BARD2DI6.js} +11 -3
  86. package/runtime/hub/apps/hub/{chunk-V3OMPMI3.js → chunk-QSMPSV5Z.js} +70 -21
  87. package/runtime/hub/apps/hub/{chunk-MA73PTOR.js → chunk-XZZXPEVV.js} +58 -37
  88. package/runtime/hub/apps/hub/{dist-7LB4D4ZQ.js → dist-3ENKQN5G.js} +35 -365
  89. package/runtime/hub/apps/hub/{dist-SIQJD72C.js → dist-6VGJOQYK.js} +84 -43
  90. package/runtime/hub/apps/hub/{dist-ERQDDSOY.js → dist-AE6IV4FV.js} +4 -4
  91. package/runtime/hub/apps/hub/{dist-IZ2JCN5R.js → dist-EQV4L7KP.js} +3 -1
  92. package/runtime/hub/apps/hub/dist-NNBELNA7.js +1017 -0
  93. package/runtime/hub/apps/hub/{dist-ZVY2FWG6.js → dist-RJJ2SDYO.js} +4 -4
  94. package/runtime/hub/apps/hub/{dist-26KVXHXV.js → dist-TU7D6UTB.js} +37 -366
  95. package/runtime/hub/apps/hub/{dist-YZJA4WRV.js → dist-WAZKGVYL.js} +7 -3
  96. package/runtime/hub/apps/hub/{hub-token-BJG6Q5II.js → hub-token-COBZGSLS.js} +2 -2
  97. package/runtime/hub/apps/hub/package.json +1 -0
  98. package/runtime/hub/apps/hub/{prepared-state-OBM2F7CU-ZEYFNYFI.js → prepared-state-75DIZ55S-NYEDSU2U.js} +1 -1
  99. package/runtime/hub/apps/hub/server.js +20 -16
  100. package/runtime/relay/bin.cjs +57 -20
  101. package/runtime/vercel/ctl.cjs +83 -36
  102. package/dist/chunk-5F5SOSDY.js.map +0 -1
  103. package/dist/chunk-GHFIKSBJ.js.map +0 -1
  104. package/dist/chunk-NH3W6HUZ.js.map +0 -1
  105. package/dist/chunk-VZC5J44U.js.map +0 -1
  106. package/dist/chunk-Y3OPQWAQ.js.map +0 -1
  107. package/runtime/hub/apps/hub/.next/server/chunks/0zhp_better-auth_dist_adapters_kysely-adapter_index_mjs_1rl4qnh._.js +0 -3
  108. /package/dist/{_cloud-attach-W2CFNXKO.js.map → _cloud-attach-7WRQH6XZ.js.map} +0 -0
  109. /package/dist/{chunk-7PRLM3PH.js.map → chunk-7ZZAZPYX.js.map} +0 -0
  110. /package/dist/{chunk-LU3WAHTU.js.map → chunk-BA2VLJVU.js.map} +0 -0
  111. /package/dist/{chunk-4UNSBU5R.js.map → chunk-DQHMDDAT.js.map} +0 -0
  112. /package/dist/{chunk-7C5MOA4Z.js.map → chunk-K5KOLYIL.js.map} +0 -0
  113. /package/dist/{dist-3V5SLNK4.js.map → dist-DTNYMBQ5.js.map} +0 -0
  114. /package/dist/{dist-UB3PYSCG.js.map → dist-K4LNH3EC.js.map} +0 -0
  115. /package/dist/{dist-BIDAC4H4.js.map → dist-POVRY7HO.js.map} +0 -0
  116. /package/dist/{dist-I5OBPLP2.js.map → dist-U2SVLJUQ.js.map} +0 -0
  117. /package/dist/{dist-SBDYDH7H.js.map → dist-XYY6SIKG.js.map} +0 -0
  118. /package/dist/{prepared-state-OBM2F7CU-DY7TZV4R.js.map → prepared-state-75DIZ55S-W6NU3S3B.js.map} +0 -0
  119. /package/runtime/hub/apps/hub/.next/static/{c82uDoByt-dPQUHilRojD → mrhWWwzD3oh05le9SRnlA}/_buildManifest.js +0 -0
  120. /package/runtime/hub/apps/hub/.next/static/{c82uDoByt-dPQUHilRojD → mrhWWwzD3oh05le9SRnlA}/_clientMiddlewareManifest.js +0 -0
  121. /package/runtime/hub/apps/hub/.next/static/{c82uDoByt-dPQUHilRojD → mrhWWwzD3oh05le9SRnlA}/_ssgManifest.js +0 -0
@@ -0,0 +1,1017 @@
1
+ import { createRequire as __cr } from 'node:module'; import { fileURLToPath as __f } from 'node:url'; import { dirname as __d } from 'node:path'; const require = __cr(import.meta.url); const __filename = __f(import.meta.url); const __dirname = __d(__filename);
2
+ import {
3
+ CLOUD_VNC_PORT,
4
+ CLOUD_WEB_PROXY_PORT,
5
+ bashScript,
6
+ createCloudProvider,
7
+ currentCloudBaseFingerprint,
8
+ hostTermForCloud,
9
+ listCloudCheckpoints,
10
+ quoteShellArg,
11
+ quoteShellArgv,
12
+ removeCloudCheckpointDir,
13
+ renderInnerCommand,
14
+ resolveCloudCheckpoint,
15
+ writeCloudCheckpointManifest
16
+ } from "./chunk-BARD2DI6.js";
17
+ import {
18
+ detectPortless,
19
+ portlessDoctorRow
20
+ } from "./chunk-XZZXPEVV.js";
21
+ import "./chunk-3LAHFDJF.js";
22
+ import {
23
+ BOX_IMAGE_REGISTRY,
24
+ BUILD_CONTEXT_DIR,
25
+ SshTunnelManager,
26
+ claudeInstallFingerprint,
27
+ computeDockerContextFingerprint,
28
+ defaultBoxSshDir,
29
+ errSummary,
30
+ mintSshKey,
31
+ readCliStamp,
32
+ readPreparedStateRaw,
33
+ readState,
34
+ registryRefForSha,
35
+ sshDestination,
36
+ sshExec,
37
+ sshOptArgs,
38
+ writePreparedStateRaw
39
+ } from "./chunk-4QY2VZCF.js";
40
+ import {
41
+ execa
42
+ } from "./chunk-UDZ3VXRF.js";
43
+ import {
44
+ hashProjectPath,
45
+ loadEffectiveConfig,
46
+ sanitizeMnemonic
47
+ } from "./chunk-QSMPSV5Z.js";
48
+ import "./chunk-OG4KH2FZ.js";
49
+
50
+ // ../../packages/sandbox-remote-docker/dist/chunk-KUTRXVTK.js
51
+ function containerNameFor(boxName) {
52
+ return `agentbox-${boxName}`;
53
+ }
54
+ function parseRemoteTarget(spec) {
55
+ const raw = spec.trim();
56
+ if (raw.length === 0) {
57
+ throw new Error("remote-docker: empty SSH destination");
58
+ }
59
+ if (raw.includes("/")) {
60
+ throw new Error(
61
+ `remote-docker: invalid SSH destination "${raw}" \u2014 "/" separates the destination from the container in a sandbox id`
62
+ );
63
+ }
64
+ const at = raw.lastIndexOf("@");
65
+ const user = at >= 0 ? raw.slice(0, at) : void 0;
66
+ const hostPort = at >= 0 ? raw.slice(at + 1) : raw;
67
+ if (hostPort.length === 0 || user !== void 0 && user.length === 0) {
68
+ throw new Error(`remote-docker: invalid SSH destination "${raw}"`);
69
+ }
70
+ const bracketed = /^\[(.+)\](?::(\d+))?$/.exec(hostPort);
71
+ if (bracketed?.[1]) {
72
+ const host = bracketed[1];
73
+ if (bracketed[2] === void 0) return { host, user, spec: raw };
74
+ return { host, user, port: checkedPort(bracketed[2], raw), spec: raw };
75
+ }
76
+ if (hostPort.includes(":")) {
77
+ const colon = hostPort.lastIndexOf(":");
78
+ const head = hostPort.slice(0, colon);
79
+ const tail = hostPort.slice(colon + 1);
80
+ if (!head.includes(":") && /^\d+$/.test(tail)) {
81
+ return { host: head, user, port: checkedPort(tail, raw), spec: raw };
82
+ }
83
+ }
84
+ return { host: hostPort, user, spec: raw };
85
+ }
86
+ function checkedPort(digits, raw) {
87
+ const port = Number.parseInt(digits, 10);
88
+ if (port <= 0 || port > 65535) {
89
+ throw new Error(`remote-docker: invalid SSH port in "${raw}"`);
90
+ }
91
+ return port;
92
+ }
93
+ function makeSandboxId(targetSpec, container) {
94
+ parseRemoteTarget(targetSpec);
95
+ return `${targetSpec}/${container}`;
96
+ }
97
+ function parseSandboxId(sandboxId) {
98
+ const slash = sandboxId.lastIndexOf("/");
99
+ if (slash <= 0 || slash === sandboxId.length - 1) {
100
+ throw new Error(
101
+ `remote-docker: malformed sandbox id "${sandboxId}" \u2014 expected "<ssh-destination>/<container>"`
102
+ );
103
+ }
104
+ return {
105
+ target: parseRemoteTarget(sandboxId.slice(0, slash)),
106
+ container: sandboxId.slice(slash + 1)
107
+ };
108
+ }
109
+ function sshTargetFor(target, controlPath) {
110
+ return {
111
+ host: target.host,
112
+ ...target.user !== void 0 ? { user: target.user } : {},
113
+ ...target.port !== void 0 ? { port: target.port } : {},
114
+ ...controlPath !== void 0 ? { controlPath } : {}
115
+ };
116
+ }
117
+ var tunnels = new SshTunnelManager("remote-docker");
118
+ async function ensureTunnel(sandboxId, target) {
119
+ if (!tunnels.has(sandboxId)) {
120
+ try {
121
+ await tunnels.open({
122
+ boxId: sandboxId,
123
+ vpsHost: target.host,
124
+ ...target.user !== void 0 ? { vpsUser: target.user } : {},
125
+ ...target.port !== void 0 ? { port: target.port } : {}
126
+ });
127
+ } catch (err) {
128
+ const msg = err instanceof Error ? err.message : String(err);
129
+ throw new Error(
130
+ `remote-docker: cannot SSH to "${target.spec}". Check that \`ssh ${target.spec} true\` works from this machine (the provider uses your own ~/.ssh/config, agent and known_hosts \u2014 it mints no keys).
131
+ ${msg}`
132
+ );
133
+ }
134
+ }
135
+ const controlPath = tunnels.controlPath(sandboxId);
136
+ return sshTargetFor(target, controlPath);
137
+ }
138
+ async function refreshTunnel(sandboxId, target) {
139
+ await tunnels.refresh({
140
+ boxId: sandboxId,
141
+ vpsHost: target.host,
142
+ ...target.user !== void 0 ? { vpsUser: target.user } : {},
143
+ ...target.port !== void 0 ? { port: target.port } : {}
144
+ });
145
+ }
146
+ async function dockerOnRemote(target, argv, opts = {}) {
147
+ return sshExec(target, loginShell(`docker ${quoteShellArgv(argv)}`), {
148
+ ...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {},
149
+ ...opts.onLine !== void 0 ? { onLine: opts.onLine } : {}
150
+ });
151
+ }
152
+ async function dockerOnRemoteOrThrow(target, argv, opts = {}) {
153
+ const res = await dockerOnRemote(target, argv, opts);
154
+ if (res.exitCode !== 0) {
155
+ throw new Error(
156
+ `remote-docker: \`docker ${argv.join(" ")}\` failed (exit ${String(res.exitCode)}): ${res.stderr.trim() || res.stdout.trim() || "(no output)"}`
157
+ );
158
+ }
159
+ return res.stdout;
160
+ }
161
+ function dockerExecArgv(container, command, opts = {}) {
162
+ const argv = ["exec"];
163
+ if (opts.interactive) argv.push("-i");
164
+ if (opts.user) argv.push("-u", opts.user);
165
+ if (opts.cwd) argv.push("-w", opts.cwd);
166
+ for (const [k, v] of Object.entries(opts.env ?? {})) {
167
+ argv.push("-e", `${k}=${v}`);
168
+ }
169
+ argv.push(container, "bash", "-lc", command);
170
+ return argv;
171
+ }
172
+ var CONTAINER_USER = "vscode";
173
+ async function pipeFileIntoContainer(target, container, input, remotePath) {
174
+ const remote = loginShell(
175
+ `docker ${quoteShellArgv(["exec", "-i", "-u", CONTAINER_USER, container, "sh", "-c", `cat > ${quoteShellArg(remotePath)}`])}`
176
+ );
177
+ const res = await execa("ssh", [...sshOptArgs(target), sshDestination(target), remote], {
178
+ reject: false,
179
+ input
180
+ });
181
+ if (res.exitCode !== 0) {
182
+ throw new Error(
183
+ `remote-docker: upload to ${container}:${remotePath} failed (exit ${String(res.exitCode)}): ${typeof res.stderr === "string" ? res.stderr : ""}`
184
+ );
185
+ }
186
+ }
187
+ async function pipeFileFromContainer(target, container, remotePath, output) {
188
+ const remote = loginShell(
189
+ `docker ${quoteShellArgv(["exec", "-u", CONTAINER_USER, container, "cat", remotePath])}`
190
+ );
191
+ const child = execa("ssh", [...sshOptArgs(target), sshDestination(target), remote], {
192
+ reject: false,
193
+ stdout: "pipe",
194
+ stderr: "pipe"
195
+ });
196
+ child.stdout?.pipe(output);
197
+ const res = await child;
198
+ if (res.exitCode !== 0) {
199
+ throw new Error(
200
+ `remote-docker: download of ${container}:${remotePath} failed (exit ${String(res.exitCode)}): ${typeof res.stderr === "string" ? res.stderr : ""}`
201
+ );
202
+ }
203
+ }
204
+ function loginShell(command) {
205
+ return `bash -lc ${quoteShellArg(command)}`;
206
+ }
207
+ async function probeRemoteEngine(spec) {
208
+ let target;
209
+ try {
210
+ target = sshTargetFor(parseRemoteTarget(spec));
211
+ } catch (err) {
212
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
213
+ }
214
+ const reach = await sshExec({ ...target, options: { ConnectTimeout: "10" } }, "true", {
215
+ timeoutMs: 2e4
216
+ });
217
+ if (reach.exitCode !== 0) {
218
+ return {
219
+ ok: false,
220
+ error: `cannot SSH to ${spec}: ${reach.stderr.trim() || `exit ${String(reach.exitCode)}`}`
221
+ };
222
+ }
223
+ const res = await dockerOnRemote(
224
+ target,
225
+ ["version", "--format", "{{.Server.Version}}|{{.Server.Arch}}|{{.Server.Os}}"],
226
+ {
227
+ timeoutMs: 3e4
228
+ }
229
+ );
230
+ if (res.exitCode !== 0) {
231
+ const err = res.stderr.trim() || res.stdout.trim();
232
+ if (/command not found|not found/i.test(err)) {
233
+ return {
234
+ ok: false,
235
+ error: `\`docker\` is not on ${spec}'s login-shell PATH (${err}). Install Docker there, or add it to the remote user's profile.`
236
+ };
237
+ }
238
+ return { ok: false, error: `docker on ${spec} is not answering: ${err}` };
239
+ }
240
+ const [version = "", arch = "", os = ""] = res.stdout.trim().split("|");
241
+ return { ok: true, version, arch, os };
242
+ }
243
+ var SCHEMA = 1;
244
+ var PROVIDER = "remote-docker";
245
+ function readPreparedState() {
246
+ const raw = readPreparedStateRaw(PROVIDER);
247
+ if (raw === null || typeof raw !== "object") return null;
248
+ const parsed = raw;
249
+ if (parsed.schema !== SCHEMA || typeof parsed.hosts !== "object" || parsed.hosts === null) {
250
+ return null;
251
+ }
252
+ return { schema: SCHEMA, hosts: parsed.hosts };
253
+ }
254
+ function recordPreparedHost(host, fields) {
255
+ const stamp = readCliStamp();
256
+ const existing = readPreparedState();
257
+ const next = {
258
+ schema: SCHEMA,
259
+ hosts: {
260
+ ...existing?.hosts ?? {},
261
+ [host]: {
262
+ imageRef: fields.imageRef,
263
+ contextSha256: fields.contextSha256,
264
+ ...stamp.cliVersion ? { cliVersion: stamp.cliVersion } : {},
265
+ ...stamp.cliCommit ? { cliCommit: stamp.cliCommit } : {},
266
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
267
+ }
268
+ }
269
+ };
270
+ writePreparedStateRaw(PROVIDER, next);
271
+ }
272
+
273
+ // ../../packages/sandbox-remote-docker/dist/index.js
274
+ import { basename } from "path";
275
+ import { createReadStream as createReadStream2, createWriteStream } from "fs";
276
+ import { mkdir } from "fs/promises";
277
+ import { dirname } from "path";
278
+ import { createReadStream } from "fs";
279
+ import { rm } from "fs/promises";
280
+ import { tmpdir } from "os";
281
+ import { join } from "path";
282
+ function remoteImageRef(contextSha256) {
283
+ return `agentbox/box:${contextSha256.slice(0, 16)}`;
284
+ }
285
+ async function currentContextSha(claudeInstall) {
286
+ const fp = await computeDockerContextFingerprint({});
287
+ if (!fp) return null;
288
+ return claudeInstall ? claudeInstallFingerprint(fp.contextSha256, claudeInstall) : fp.contextSha256;
289
+ }
290
+ async function ensureRemoteImage(target, opts = {}) {
291
+ const log = opts.onLog ?? (() => {
292
+ });
293
+ if (opts.imageRef && opts.imageRef.trim().length > 0) {
294
+ const ref2 = opts.imageRef.trim();
295
+ const probe = await dockerOnRemote(target, ["image", "inspect", ref2]);
296
+ if (probe.exitCode !== 0) {
297
+ throw new Error(
298
+ `remote-docker: box.imageRemoteDocker pins "${ref2}", which is not present on the remote engine. Build/pull it there, or unset the key to let AgentBox manage the image.`
299
+ );
300
+ }
301
+ return { ref: ref2, source: "pinned" };
302
+ }
303
+ const sha = await currentContextSha(opts.claudeInstall);
304
+ if (!sha) {
305
+ throw new Error(
306
+ "remote-docker: cannot resolve the box build context (a dev tree needs `pnpm -w build` first)"
307
+ );
308
+ }
309
+ const ref = remoteImageRef(sha);
310
+ if (!opts.force) {
311
+ const probe = await dockerOnRemote(target, ["image", "inspect", ref]);
312
+ if (probe.exitCode === 0) {
313
+ log(`[image] ${ref} already present on the remote`);
314
+ return { ref, source: "present", contextSha256: sha };
315
+ }
316
+ }
317
+ const registry = opts.registry ?? BOX_IMAGE_REGISTRY;
318
+ if (opts.allowPull !== false && registry) {
319
+ const remote = registryRefForSha(sha, registry);
320
+ log(`[image] pulling ${remote} on the remote engine`);
321
+ const pull = await dockerOnRemote(target, ["pull", remote], {
322
+ timeoutMs: 9e5,
323
+ onLine: (l) => log(`[image] ${l}`)
324
+ });
325
+ if (pull.exitCode === 0) {
326
+ await dockerOnRemote(target, ["tag", remote, ref]);
327
+ log(`[image] pulled ${remote} -> ${ref}`);
328
+ return { ref, source: "pulled", contextSha256: sha };
329
+ }
330
+ log("[image] registry miss \u2014 building on the remote from the local context");
331
+ }
332
+ await buildOnRemote(target, ref, opts);
333
+ return { ref, source: "built", contextSha256: sha };
334
+ }
335
+ async function buildOnRemote(target, ref, opts) {
336
+ const log = opts.onLog ?? (() => {
337
+ });
338
+ const tarPath = join(tmpdir(), `agentbox-box-ctx-${String(process.pid)}.tar`);
339
+ try {
340
+ await execa("tar", ["-C", BUILD_CONTEXT_DIR, "-cf", tarPath, "."], {
341
+ env: { ...process.env, COPYFILE_DISABLE: "1" }
342
+ });
343
+ const buildArgs = ["build", "-t", ref, "-f", "Dockerfile.box"];
344
+ if (opts.claudeInstall) {
345
+ buildArgs.push("--build-arg", `AGENTBOX_CLAUDE_INSTALL=${opts.claudeInstall}`);
346
+ }
347
+ buildArgs.push("-");
348
+ log(`[image] building ${ref} on the remote (streaming the build context)`);
349
+ const res = await execa(
350
+ "ssh",
351
+ [
352
+ ...sshOptArgs(target),
353
+ sshDestination(target),
354
+ loginShell(`docker ${quoteShellArgv(buildArgs)}`)
355
+ ],
356
+ { reject: false, input: createReadStream(tarPath), stdout: "pipe", stderr: "pipe" }
357
+ );
358
+ const out = `${typeof res.stdout === "string" ? res.stdout : ""}${typeof res.stderr === "string" ? res.stderr : ""}`;
359
+ for (const line of out.split(/\r?\n/)) {
360
+ if (line.trim().length > 0) log(`[image] ${line}`);
361
+ }
362
+ if (res.exitCode !== 0) {
363
+ throw new Error(
364
+ `remote-docker: remote \`docker build\` failed (exit ${String(res.exitCode)}). See the build output above.`
365
+ );
366
+ }
367
+ log(`[image] built ${ref}`);
368
+ } finally {
369
+ await rm(tarPath, { force: true });
370
+ }
371
+ }
372
+ var BACKEND_NAME = "remote-docker";
373
+ var SNAPSHOT_SEP = "#";
374
+ function makeSnapshotName(host, imageRef) {
375
+ return `${host}${SNAPSHOT_SEP}${imageRef}`;
376
+ }
377
+ function parseSnapshotName(snapshotName) {
378
+ const sep = snapshotName.indexOf(SNAPSHOT_SEP);
379
+ if (sep <= 0 || sep === snapshotName.length - 1) {
380
+ throw new Error(
381
+ `remote-docker: malformed snapshot name "${snapshotName}" \u2014 expected "<ssh-destination>#<image-ref>"`
382
+ );
383
+ }
384
+ return {
385
+ host: snapshotName.slice(0, sep),
386
+ imageRef: snapshotName.slice(sep + 1)
387
+ };
388
+ }
389
+ function snapshotTunnelId(host) {
390
+ return `engine:${host}`;
391
+ }
392
+ var BRIDGE_PORT = 8788;
393
+ var SSH_PORT = 22;
394
+ function portsToPublish(exposePorts) {
395
+ const base = [CLOUD_WEB_PROXY_PORT, CLOUD_VNC_PORT, BRIDGE_PORT, SSH_PORT];
396
+ return [.../* @__PURE__ */ new Set([...base, ...exposePorts ?? []])];
397
+ }
398
+ async function remoteIsNested(target) {
399
+ const res = await sshExec(target, "test -f /etc/agentbox/box.env");
400
+ return res.exitCode === 0;
401
+ }
402
+ async function ctxFor(h) {
403
+ const { target: remote, container } = parseSandboxId(h.sandboxId);
404
+ const target = await ensureTunnel(h.sandboxId, remote);
405
+ return { target, remote, container };
406
+ }
407
+ function mapDockerState(status) {
408
+ switch (status.trim()) {
409
+ case "running":
410
+ return "running";
411
+ case "paused":
412
+ return "paused";
413
+ case "created":
414
+ case "exited":
415
+ case "dead":
416
+ case "restarting":
417
+ case "removing":
418
+ return "stopped";
419
+ default:
420
+ return "missing";
421
+ }
422
+ }
423
+ function parseDockerPort(stdout) {
424
+ for (const line of stdout.split(/\r?\n/)) {
425
+ const m = /:(\d+)\s*$/.exec(line.trim());
426
+ if (m?.[1]) {
427
+ const port = Number.parseInt(m[1], 10);
428
+ if (Number.isFinite(port) && port > 0) return port;
429
+ }
430
+ }
431
+ return null;
432
+ }
433
+ function parseSize(size) {
434
+ if (!size) return {};
435
+ const m = /^(\d+)(?:-(\d+))?$/.exec(size.trim());
436
+ if (!m?.[1]) return {};
437
+ const cpu = Number.parseInt(m[1], 10);
438
+ const memory = m[2] ? Number.parseInt(m[2], 10) : void 0;
439
+ return { cpu, ...memory !== void 0 ? { memory } : {} };
440
+ }
441
+ function buildRunArgv(opts) {
442
+ const argv = [
443
+ "run",
444
+ "-d",
445
+ "--name",
446
+ opts.container,
447
+ "--hostname",
448
+ opts.container,
449
+ // The in-box dockerd needs these: SYS_ADMIN to `mount -t overlay` for
450
+ // overlay2, NET_ADMIN for its bridge + iptables NAT, /dev/fuse +
451
+ // apparmor:unconfined for the fuse-overlayfs fallback, seccomp:unconfined
452
+ // because the default profile blocks syscalls nested containers need, and a
453
+ // private cgroup namespace so runc can create its own slice. Same set as
454
+ // the local docker provider; we still avoid --privileged.
455
+ "--cap-add=SYS_ADMIN",
456
+ "--cap-add=NET_ADMIN",
457
+ "--device=/dev/fuse",
458
+ "--security-opt=apparmor:unconfined",
459
+ "--security-opt=seccomp=unconfined",
460
+ "--cgroupns=private"
461
+ ];
462
+ if (opts.nestedEngine) {
463
+ argv.push("--user", "0");
464
+ }
465
+ if (opts.cpu) argv.push("--cpus", String(opts.cpu));
466
+ if (opts.memory) argv.push("--memory", `${String(opts.memory)}g`);
467
+ argv.push("-v", `${opts.dockerVolume}:/var/lib/docker`);
468
+ for (const port of opts.ports) {
469
+ argv.push("-p", `127.0.0.1:0:${String(port)}`);
470
+ }
471
+ for (const [k, v] of Object.entries(opts.env)) {
472
+ argv.push("-e", `${k}=${v}`);
473
+ }
474
+ argv.push(opts.image, "sleep", "infinity");
475
+ return argv;
476
+ }
477
+ var remoteDockerBackend = {
478
+ name: BACKEND_NAME,
479
+ async provision(req) {
480
+ const log = req.onLog ?? (() => {
481
+ });
482
+ const spec = (req.host ?? "").trim();
483
+ if (!spec) {
484
+ throw new Error(
485
+ "remote-docker: no SSH destination. Use `agentbox docker:<host> \u2026`, `--remote-host <host>`, or set `box.remoteDockerHost`."
486
+ );
487
+ }
488
+ const remote = parseRemoteTarget(spec);
489
+ const container = containerNameFor(req.name);
490
+ const sandboxId = makeSandboxId(remote.spec, container);
491
+ const target = await ensureTunnel(sandboxId, remote);
492
+ let image;
493
+ if (req.snapshot) {
494
+ const snap = parseSnapshotName(req.snapshot);
495
+ if (snap.host !== remote.spec) {
496
+ throw new Error(
497
+ `snapshot expired or deleted: it was captured on ${snap.host}, not ${remote.spec} (a remote-docker checkpoint is local to its engine)`
498
+ );
499
+ }
500
+ image = snap.imageRef;
501
+ const probe = await dockerOnRemote(target, ["image", "inspect", image]);
502
+ if (probe.exitCode !== 0) {
503
+ throw new Error(`snapshot expired or deleted: ${image} is not on ${remote.spec}`);
504
+ }
505
+ } else {
506
+ const ensured = await ensureRemoteImage(target, {
507
+ imageRef: req.image && req.image !== "agentbox/box:dev" ? req.image : void 0,
508
+ onLog: log
509
+ });
510
+ image = ensured.ref;
511
+ }
512
+ const { cpu, memory } = parseSize(req.size);
513
+ const dockerVolume = `agentbox-docker-${container}`;
514
+ await dockerOnRemoteOrThrow(target, ["volume", "create", dockerVolume]);
515
+ const nestedEngine = await remoteIsNested(target);
516
+ if (nestedEngine) {
517
+ log("[provision] remote engine is itself an AgentBox box \u2014 running the box init as root");
518
+ }
519
+ const argv = buildRunArgv({
520
+ container,
521
+ image,
522
+ env: req.env ?? {},
523
+ ports: portsToPublish(req.exposePorts),
524
+ dockerVolume,
525
+ nestedEngine,
526
+ ...cpu !== void 0 ? { cpu } : {},
527
+ ...memory !== void 0 ? { memory } : {}
528
+ });
529
+ log(`[provision] docker run ${container} on ${remote.spec}`);
530
+ await dockerOnRemoteOrThrow(target, argv, { timeoutMs: 3e5 });
531
+ return {
532
+ sandboxId,
533
+ resources: {
534
+ ...cpu !== void 0 ? { cpu } : {},
535
+ ...memory !== void 0 ? { memory } : {}
536
+ }
537
+ };
538
+ },
539
+ async get(sandboxId) {
540
+ let ctx;
541
+ try {
542
+ ctx = await ctxFor({ sandboxId });
543
+ } catch {
544
+ return null;
545
+ }
546
+ const res = await dockerOnRemote(ctx.target, [
547
+ "inspect",
548
+ "-f",
549
+ "{{.State.Status}}",
550
+ ctx.container
551
+ ]);
552
+ return res.exitCode === 0 ? { sandboxId } : null;
553
+ },
554
+ /**
555
+ * Every other cloud can ask its API "what sandboxes exist?". Here there is no
556
+ * API and no registry of engines — a machine only becomes ours by being named
557
+ * in a box record or in `box.remoteDockerHost`. So enumeration means: work out
558
+ * which engines we have ever used, and ask each of them. An engine that has
559
+ * gone away is skipped rather than fatal, since prune must still report on the
560
+ * ones that answer.
561
+ */
562
+ async list() {
563
+ const hosts = await knownHosts();
564
+ const out = [];
565
+ for (const host of hosts) {
566
+ try {
567
+ out.push(...await listOnHost(host));
568
+ } catch {
569
+ }
570
+ }
571
+ return out;
572
+ },
573
+ async start(h) {
574
+ const ctx = await ctxFor(h);
575
+ await dockerOnRemoteOrThrow(ctx.target, ["start", ctx.container], { timeoutMs: 12e4 });
576
+ },
577
+ async stop(h) {
578
+ const ctx = await ctxFor(h);
579
+ await dockerOnRemoteOrThrow(ctx.target, ["stop", ctx.container], { timeoutMs: 12e4 });
580
+ },
581
+ /**
582
+ * A true freeze (SIGSTOP-equivalent via the freezer cgroup), not cold storage:
583
+ * the container keeps its memory and its published ports, so resume is instant
584
+ * and the forwarded ports stay valid.
585
+ */
586
+ async pause(h) {
587
+ const ctx = await ctxFor(h);
588
+ const state = await currentState(ctx);
589
+ if (state !== "running") return;
590
+ await dockerOnRemoteOrThrow(ctx.target, ["pause", ctx.container]);
591
+ },
592
+ async resume(h) {
593
+ const ctx = await ctxFor(h);
594
+ const state = await currentState(ctx);
595
+ if (state === "paused") {
596
+ await dockerOnRemoteOrThrow(ctx.target, ["unpause", ctx.container]);
597
+ return;
598
+ }
599
+ if (state !== "running") {
600
+ await dockerOnRemoteOrThrow(ctx.target, ["start", ctx.container], { timeoutMs: 12e4 });
601
+ }
602
+ },
603
+ async destroy(h) {
604
+ const ctx = await ctxFor(h);
605
+ await dockerOnRemote(ctx.target, ["rm", "-f", ctx.container], { timeoutMs: 12e4 });
606
+ await dockerOnRemote(ctx.target, ["volume", "rm", "-f", `agentbox-docker-${ctx.container}`]);
607
+ await tunnels.close(h.sandboxId);
608
+ },
609
+ async state(h) {
610
+ let ctx;
611
+ try {
612
+ ctx = await ctxFor(h);
613
+ } catch {
614
+ return "missing";
615
+ }
616
+ return currentState(ctx);
617
+ },
618
+ async exec(h, cmd, opts = {}) {
619
+ const ctx = await ctxFor(h);
620
+ const argv = dockerExecArgv(ctx.container, cmd, {
621
+ user: opts.user ?? CONTAINER_USER,
622
+ ...opts.cwd ? { cwd: opts.cwd } : {},
623
+ ...opts.env ? { env: opts.env } : {}
624
+ });
625
+ const res = await dockerOnRemote(ctx.target, argv, {
626
+ timeoutMs: opts.attemptTimeoutMs ?? 3e5
627
+ });
628
+ return { exitCode: res.exitCode, stdout: res.stdout, stderr: res.stderr };
629
+ },
630
+ async uploadFile(h, localPath, remotePath) {
631
+ const ctx = await ctxFor(h);
632
+ await dockerOnRemote(
633
+ ctx.target,
634
+ dockerExecArgv(ctx.container, bashScript(`mkdir -p ${shellDir(remotePath)}`), {
635
+ user: "root"
636
+ })
637
+ );
638
+ await pipeFileIntoContainer(ctx.target, ctx.container, createReadStream2(localPath), remotePath);
639
+ },
640
+ async downloadFile(h, remotePath, localPath) {
641
+ const ctx = await ctxFor(h);
642
+ await mkdir(dirname(localPath), { recursive: true });
643
+ await pipeFileFromContainer(
644
+ ctx.target,
645
+ ctx.container,
646
+ remotePath,
647
+ createWriteStream(localPath)
648
+ );
649
+ },
650
+ async listFiles(h, remoteDir) {
651
+ const ctx = await ctxFor(h);
652
+ const res = await dockerOnRemote(
653
+ ctx.target,
654
+ dockerExecArgv(
655
+ ctx.container,
656
+ `find ${quote(remoteDir)} -mindepth 1 -maxdepth 1 -printf '%f\\t%y\\n'`
657
+ )
658
+ );
659
+ if (res.exitCode !== 0) return [];
660
+ const out = [];
661
+ for (const line of res.stdout.split(/\r?\n/)) {
662
+ const [name, kind] = line.split(" ");
663
+ if (name) out.push({ name, isDir: kind === "d" });
664
+ }
665
+ return out;
666
+ },
667
+ /**
668
+ * The container's port is published on the REMOTE's loopback; we forward that
669
+ * to a free local port over the box's ControlMaster. So the URL is always
670
+ * `http://127.0.0.1:<local>` — reachable from the host browser and from the
671
+ * host relay's poller alike.
672
+ */
673
+ async previewUrl(h, port) {
674
+ const ctx = await ctxFor(h);
675
+ const remotePort = await publishedPort(ctx, port);
676
+ const localPort = await tunnels.forward(h.sandboxId, remotePort);
677
+ return { url: `http://127.0.0.1:${String(localPort)}` };
678
+ },
679
+ /** SSH is already the auth gate, so a "signed" URL is just the tunneled one. */
680
+ async signedPreviewUrl(h, port) {
681
+ return remoteDockerBackend.previewUrl(h, port);
682
+ },
683
+ /**
684
+ * The poller calls this when the local port stops answering — typically a
685
+ * ControlMaster that died across a host sleep/wake. Re-open the master AND
686
+ * re-read `docker port`: a container restart reassigns the remote's ephemeral
687
+ * port, so a forward to the old one would connect to nothing.
688
+ */
689
+ async refreshPreviewUrl(h, port) {
690
+ const { target: remote } = parseSandboxId(h.sandboxId);
691
+ await refreshTunnel(h.sandboxId, remote);
692
+ return remoteDockerBackend.previewUrl(h, port);
693
+ },
694
+ async createSnapshot(h, snapshotName) {
695
+ const ctx = await ctxFor(h);
696
+ const snap = parseSnapshotName(snapshotName);
697
+ await dockerOnRemoteOrThrow(ctx.target, ["commit", ctx.container, snap.imageRef], {
698
+ timeoutMs: 6e5
699
+ });
700
+ },
701
+ async deleteSnapshot(snapshotName) {
702
+ const snap = parseSnapshotName(snapshotName);
703
+ try {
704
+ const target = await ensureTunnel(snapshotTunnelId(snap.host), parseRemoteTarget(snap.host));
705
+ await dockerOnRemote(target, ["image", "rm", "-f", snap.imageRef]);
706
+ } catch {
707
+ }
708
+ },
709
+ async snapshotExists(snapshotName) {
710
+ let snap;
711
+ try {
712
+ snap = parseSnapshotName(snapshotName);
713
+ } catch {
714
+ return false;
715
+ }
716
+ try {
717
+ const target = await ensureTunnel(snapshotTunnelId(snap.host), parseRemoteTarget(snap.host));
718
+ const res = await dockerOnRemote(target, ["image", "inspect", snap.imageRef]);
719
+ return res.exitCode === 0;
720
+ } catch {
721
+ return false;
722
+ }
723
+ }
724
+ };
725
+ async function knownHosts() {
726
+ const hosts = /* @__PURE__ */ new Set();
727
+ try {
728
+ const state = await readState();
729
+ for (const box of state.boxes) {
730
+ if (box.provider !== BACKEND_NAME || !box.cloud?.sandboxId) continue;
731
+ try {
732
+ hosts.add(parseSandboxId(box.cloud.sandboxId).target.spec);
733
+ } catch {
734
+ }
735
+ }
736
+ } catch {
737
+ }
738
+ try {
739
+ const cfg = await loadEffectiveConfig(process.cwd());
740
+ const dflt = (cfg.effective.box.remoteDockerHost || "").trim();
741
+ if (dflt) hosts.add(dflt);
742
+ } catch {
743
+ }
744
+ return [...hosts];
745
+ }
746
+ async function listOnHost(spec) {
747
+ const remote = parseRemoteTarget(spec);
748
+ const target = await ensureTunnel(`list:${remote.spec}`, remote);
749
+ const res = await dockerOnRemote(target, [
750
+ "ps",
751
+ "-a",
752
+ "--filter",
753
+ "name=agentbox-",
754
+ "--format",
755
+ "{{.Names}} {{.State}} {{.CreatedAt}}"
756
+ ]);
757
+ if (res.exitCode !== 0) return [];
758
+ const out = [];
759
+ for (const line of res.stdout.split(/\r?\n/)) {
760
+ const [name, state, createdAt] = line.split(" ");
761
+ if (!name) continue;
762
+ out.push({
763
+ sandboxId: makeSandboxId(remote.spec, name),
764
+ name,
765
+ ...createdAt ? { createdAt } : {},
766
+ state: mapDockerState(state ?? "")
767
+ });
768
+ }
769
+ return out;
770
+ }
771
+ async function currentState(ctx) {
772
+ const res = await dockerOnRemote(ctx.target, [
773
+ "inspect",
774
+ "-f",
775
+ "{{.State.Status}}",
776
+ ctx.container
777
+ ]);
778
+ if (res.exitCode !== 0) return "missing";
779
+ return mapDockerState(res.stdout);
780
+ }
781
+ async function publishedPort(ctx, containerPort) {
782
+ const res = await dockerOnRemote(ctx.target, ["port", ctx.container, String(containerPort)]);
783
+ const port = res.exitCode === 0 ? parseDockerPort(res.stdout) : null;
784
+ if (port === null) {
785
+ throw new Error(
786
+ `remote-docker: container port ${String(containerPort)} is not published on ${ctx.container}. Docker port mappings are fixed at create \u2014 a service exposed after the box was made is only reachable through the :80 WebProxy until the box is recreated.`
787
+ );
788
+ }
789
+ return port;
790
+ }
791
+ function shellDir(path) {
792
+ const slash = path.lastIndexOf("/");
793
+ return quote(slash > 0 ? path.slice(0, slash) : "/");
794
+ }
795
+ function quote(s) {
796
+ return `'${s.replace(/'/g, "'\\''")}'`;
797
+ }
798
+ var CONTAINER_USER2 = "vscode";
799
+ async function buildRemoteDockerAttach(box, kind, opts = {}) {
800
+ const sandboxId = box.cloud?.sandboxId;
801
+ if (!sandboxId) {
802
+ throw new Error(`remote-docker box ${box.name} has no sandboxId \u2014 record is malformed`);
803
+ }
804
+ const { target: remote, container } = parseSandboxId(sandboxId);
805
+ const target = await ensureTunnel(sandboxId, remote);
806
+ const inner = renderInnerCommand(kind, opts);
807
+ const dockerArgv = [
808
+ "exec",
809
+ // `detached` only creates the session, so it needs no TTY — and asking for
810
+ // one would make docker fail when the CLI runs it without a terminal.
811
+ ...opts.detached ? ["-i"] : ["-it"],
812
+ "-u",
813
+ opts.user ?? CONTAINER_USER2,
814
+ "-e",
815
+ `TERM=${hostTermForCloud()}`,
816
+ container,
817
+ "bash",
818
+ "-lc",
819
+ inner
820
+ ];
821
+ const remoteCommand = `docker ${quoteShellArgv(dockerArgv)}`;
822
+ const argv = [
823
+ "ssh",
824
+ ...sshOptArgs(target),
825
+ // -t forces TTY allocation through ssh; without it tmux and readline break.
826
+ ...opts.detached ? [] : ["-t"],
827
+ sshDestination(target),
828
+ // One argv element: ssh hands the string to the remote login shell, which
829
+ // re-parses it — so the docker argv is quoted, not concatenated.
830
+ remoteCommand
831
+ ];
832
+ return { argv };
833
+ }
834
+ var SSH_CONTAINER_PORT = 22;
835
+ async function resolveBoxSshTarget(box) {
836
+ const sandboxId = box.cloud?.sandboxId;
837
+ if (!sandboxId) return null;
838
+ const { target: remote, container } = parseSandboxId(sandboxId);
839
+ const conn = await ensureTunnel(sandboxId, remote);
840
+ const key = await mintSshKey(
841
+ defaultBoxSshDir(sandboxId, "remote-docker"),
842
+ `agentbox-${box.name}`
843
+ );
844
+ const install = [
845
+ `install -d -m 700 -o ${CONTAINER_USER} -g ${CONTAINER_USER} /home/${CONTAINER_USER}/.ssh`,
846
+ `touch /home/${CONTAINER_USER}/.ssh/authorized_keys`,
847
+ `grep -qF ${quoteShellArg(key.publicKey)} /home/${CONTAINER_USER}/.ssh/authorized_keys || echo ${quoteShellArg(key.publicKey)} >> /home/${CONTAINER_USER}/.ssh/authorized_keys`,
848
+ `chown -R ${CONTAINER_USER}:${CONTAINER_USER} /home/${CONTAINER_USER}/.ssh`,
849
+ `chmod 600 /home/${CONTAINER_USER}/.ssh/authorized_keys`
850
+ ].join(" && ");
851
+ const installRes = await dockerOnRemote(
852
+ conn,
853
+ dockerExecArgv(container, bashScript(install), { user: "root" })
854
+ );
855
+ if (installRes.exitCode !== 0) return null;
856
+ await dockerOnRemote(
857
+ conn,
858
+ dockerExecArgv(container, bashScript("/usr/local/bin/agentbox-sshd-start"), {
859
+ user: "root"
860
+ }),
861
+ { timeoutMs: 6e4 }
862
+ );
863
+ const portRes = await dockerOnRemote(conn, ["port", container, String(SSH_CONTAINER_PORT)]);
864
+ const port = portRes.exitCode === 0 ? parseDockerPort(portRes.stdout) : null;
865
+ if (port === null) return null;
866
+ return {
867
+ // Resolved on the jump host, not here.
868
+ host: "127.0.0.1",
869
+ port,
870
+ user: CONTAINER_USER,
871
+ identityFile: key.privatePath,
872
+ proxyJump: remote.spec
873
+ };
874
+ }
875
+ async function prepareRemoteDocker(opts) {
876
+ const log = opts.onLog ?? (() => {
877
+ });
878
+ const spec = (opts.host ?? "").trim();
879
+ if (!spec) {
880
+ throw new Error(
881
+ "remote-docker: prepare needs an SSH destination \u2014 `agentbox prepare --provider docker:<host>`, or set `box.remoteDockerHost`."
882
+ );
883
+ }
884
+ const remote = parseRemoteTarget(spec);
885
+ const target = await ensureTunnel(`engine:${remote.spec}`, remote);
886
+ log(`[prepare] ensuring the box image on ${remote.spec}`);
887
+ const res = await ensureRemoteImage(target, {
888
+ ...opts.claudeInstall ? { claudeInstall: opts.claudeInstall } : {},
889
+ ...opts.registry !== void 0 ? { registry: opts.registry } : {},
890
+ ...opts.allowPull !== void 0 ? { allowPull: opts.allowPull } : {},
891
+ ...opts.force ? { force: true } : {},
892
+ onLog: log
893
+ });
894
+ if (res.contextSha256) {
895
+ recordPreparedHost(remote.spec, { imageRef: res.ref, contextSha256: res.contextSha256 });
896
+ }
897
+ log(`[prepare] ${remote.spec} ready \u2014 ${res.ref} (${res.source})`);
898
+ return {};
899
+ }
900
+ async function doctorChecks() {
901
+ try {
902
+ const cfg = await loadEffectiveConfig(process.cwd());
903
+ const host = (cfg.effective.box.remoteDockerHost || "").trim();
904
+ if (!host) {
905
+ return [
906
+ {
907
+ label: "remote engine",
908
+ status: "warn",
909
+ detail: "no default SSH destination set",
910
+ hint: "`agentbox config set box.remoteDockerHost <user@host>` (or use `agentbox docker:<host> \u2026`)"
911
+ }
912
+ ];
913
+ }
914
+ const probe = await probeRemoteEngine(host);
915
+ const engineRes = probe.ok ? {
916
+ label: "remote engine",
917
+ status: "ok",
918
+ detail: `${host} \u2014 docker ${probe.version} (${probe.os}/${probe.arch})`
919
+ } : {
920
+ label: "remote engine",
921
+ status: "fail",
922
+ detail: probe.error,
923
+ hint: `check that \`ssh ${host} true\` works and docker is installed there`
924
+ };
925
+ const prepared = readPreparedState();
926
+ const baked = prepared?.hosts[host];
927
+ const imageRes = baked ? {
928
+ label: "box image",
929
+ status: "ok",
930
+ detail: `${baked.imageRef} (${baked.cliVersion ?? "\u2014"})`
931
+ } : {
932
+ label: "box image",
933
+ status: "warn",
934
+ detail: "not baked on this host yet",
935
+ hint: `\`agentbox prepare --provider docker:${host}\` (otherwise the first create bakes it)`
936
+ };
937
+ const portlessRes = portlessDoctorRow(await detectPortless());
938
+ return [engineRes, imageRes, portlessRes];
939
+ } catch (err) {
940
+ return [{ label: "remote engine", status: "warn", detail: errSummary(err) }];
941
+ }
942
+ }
943
+ var cloudProvider = createCloudProvider(remoteDockerBackend, {
944
+ // Empty on purpose. The cloud default (2 cpu / 4 GB) would silently cap a box
945
+ // on a 32-core workstation; a remote engine is the user's own machine, so a
946
+ // box is unlimited unless `--size` says otherwise — the same deal the local
947
+ // docker provider offers.
948
+ defaultResources: {},
949
+ launchDockerd: true
950
+ });
951
+ function checkpointImageRef(projectRoot, name) {
952
+ const mnemonic = sanitizeMnemonic(basename(projectRoot));
953
+ return `agentbox-ckpt-${hashProjectPath(projectRoot)}_${mnemonic}:${name}`;
954
+ }
955
+ var remoteDockerCheckpoint = {
956
+ async create(box, name) {
957
+ if (!box.projectRoot) {
958
+ throw new Error(
959
+ "checkpoint requires the box to have a project root (run `agentbox checkpoint` from inside the project)"
960
+ );
961
+ }
962
+ const sandboxId = box.cloud?.sandboxId;
963
+ if (!sandboxId) {
964
+ throw new Error(`remote-docker box ${box.name} has no sandboxId \u2014 record is malformed`);
965
+ }
966
+ const { target } = parseSandboxId(sandboxId);
967
+ const snapshotName = makeSnapshotName(target.spec, checkpointImageRef(box.projectRoot, name));
968
+ await remoteDockerBackend.createSnapshot?.({ sandboxId }, snapshotName);
969
+ const info = await writeCloudCheckpointManifest(box.projectRoot, BACKEND_NAME, name, {
970
+ snapshotName,
971
+ sourceBoxId: box.id,
972
+ sourceBoxName: box.name,
973
+ baseProvider: BACKEND_NAME,
974
+ baseFingerprint: currentCloudBaseFingerprint(BACKEND_NAME),
975
+ cliVersion: readCliStamp().cliVersion
976
+ });
977
+ return { ref: info.name };
978
+ },
979
+ async list(projectRoot) {
980
+ const entries = await listCloudCheckpoints(projectRoot, BACKEND_NAME);
981
+ return entries.map((e) => ({ ref: e.name, createdAt: e.manifest.createdAt }));
982
+ },
983
+ async remove(projectRoot, ref) {
984
+ const entry = await resolveCloudCheckpoint(projectRoot, BACKEND_NAME, ref);
985
+ if (!entry) return;
986
+ await remoteDockerBackend.deleteSnapshot?.(entry.manifest.snapshotName);
987
+ await removeCloudCheckpointDir(projectRoot, BACKEND_NAME, ref);
988
+ }
989
+ };
990
+ var remoteDockerProvider = {
991
+ ...cloudProvider,
992
+ buildAttach: buildRemoteDockerAttach,
993
+ // The box's own sshd, reached by jumping through the engine — see box-ssh.ts.
994
+ // Supplying this is what lets `open` / `code` / `connect` treat a remote-docker
995
+ // box like any other SSH-capable box, without the scaffold having to guess a
996
+ // target out of an attach argv that points at the engine rather than the box.
997
+ sshTarget: resolveBoxSshTarget,
998
+ checkpoint: remoteDockerCheckpoint,
999
+ prepare: prepareRemoteDocker,
1000
+ baseFingerprint: async (claudeInstall) => await currentContextSha(claudeInstall) ?? void 0
1001
+ };
1002
+ var providerModule = {
1003
+ provider: remoteDockerProvider,
1004
+ backend: remoteDockerBackend,
1005
+ currentBaseFingerprintLive: async (claudeInstall) => await currentContextSha(claudeInstall) ?? void 0,
1006
+ doctorChecks
1007
+ };
1008
+ export {
1009
+ BACKEND_NAME,
1010
+ listOnHost,
1011
+ parseRemoteTarget,
1012
+ parseSandboxId,
1013
+ probeRemoteEngine,
1014
+ providerModule,
1015
+ remoteDockerBackend,
1016
+ remoteDockerProvider
1017
+ };