@madarco/agentbox 0.23.4 → 0.24.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 +79 -0
- package/LICENSE +21 -0
- package/README.md +3 -2
- package/dist/{_cloud-attach-BQRWX3J2.js → _cloud-attach-T6GPR6LJ.js} +5 -5
- package/dist/{chunk-GGRZ3GZO.js → chunk-5KHEH47T.js} +91 -79
- package/dist/chunk-5KHEH47T.js.map +1 -0
- package/dist/{chunk-I6ZRWTPR.js → chunk-6U2S6QWD.js} +219 -18
- package/dist/chunk-6U2S6QWD.js.map +1 -0
- package/dist/{chunk-LK2JT2OO.js → chunk-DEDTPG2D.js} +880 -146
- package/dist/chunk-DEDTPG2D.js.map +1 -0
- package/dist/chunk-G3H2L3O2.js +0 -0
- package/dist/{chunk-LA4JMS27.js → chunk-I654PBHA.js} +290 -330
- package/dist/chunk-I654PBHA.js.map +1 -0
- package/dist/{chunk-W3FQPFP7.js → chunk-K2EDQGZP.js} +18 -4
- package/dist/chunk-K2EDQGZP.js.map +1 -0
- package/dist/{chunk-LSQXT5WZ.js → chunk-LC4E2EIZ.js} +3 -3
- package/dist/{chunk-LSQXT5WZ.js.map → chunk-LC4E2EIZ.js.map} +1 -1
- package/dist/{chunk-SFA57TGX.js → chunk-NACA6AM7.js} +183 -49
- package/dist/chunk-NACA6AM7.js.map +1 -0
- package/dist/{chunk-QEQFZLYR.js → chunk-RYQLFKCP.js} +20 -10
- package/dist/chunk-RYQLFKCP.js.map +1 -0
- package/dist/{chunk-QT3SHMLY.js → chunk-UIRBYL4G.js} +43 -12
- package/dist/chunk-UIRBYL4G.js.map +1 -0
- package/dist/chunk-WJFZJZIM.js +0 -0
- package/dist/chunk-WLHJZPFJ.js +845 -0
- package/dist/chunk-WLHJZPFJ.js.map +1 -0
- package/dist/cloud-poller-SUNA6ZQC-7M5LJHHE.js +0 -0
- package/dist/dist-3KIJ2KQ2.js +1437 -0
- package/dist/dist-3KIJ2KQ2.js.map +1 -0
- package/dist/{dist-V235KVEX.js → dist-7OUOHQPA.js} +196 -151
- package/dist/dist-7OUOHQPA.js.map +1 -0
- package/dist/{dist-Z2NEVV55.js → dist-B7TNWGVG.js} +8 -4
- package/dist/{dist-CUKBKS3N.js → dist-KYV3LEHG.js} +10 -6
- package/dist/{dist-FXQFTT75.js → dist-PHYCFYKH.js} +37 -17
- package/dist/dist-PHYCFYKH.js.map +1 -0
- package/dist/{dist-2BTJQUJS.js → dist-T5MXBZGP.js} +2 -2
- package/dist/{dist-QO4CTLAX.js → dist-Z7KEPQC7.js} +6 -6
- package/dist/index.js +2560 -1108
- package/dist/index.js.map +1 -1
- package/dist/{prepared-state-BUO75YLZ-CDTISC2C.js → prepared-state-BUO75YLZ-RQRFFBJW.js} +2 -2
- package/package.json +28 -28
- package/runtime/_shared/agentbox-checkpoint-cleanup +0 -0
- package/runtime/_shared/agentbox-codex-hooks.json +1 -1
- package/runtime/_shared/agentbox-dockerd-start +0 -0
- package/runtime/_shared/agentbox-open +0 -0
- package/runtime/_shared/agentbox-portless-trust +0 -0
- package/runtime/_shared/agentbox-vnc-start +0 -0
- package/runtime/_shared/ctl.cjs +468 -97
- package/runtime/_shared/gh-shim +0 -0
- package/runtime/_shared/git-shim +53 -3
- package/runtime/_shared/linear-shim +0 -0
- package/runtime/_shared/ntn-shim +0 -0
- package/runtime/daytona/custom-system-CLAUDE.md +1 -1
- package/runtime/digitalocean/agentbox-checkpoint-cleanup +55 -0
- package/runtime/digitalocean/agentbox-codex-hooks.json +68 -0
- package/runtime/digitalocean/agentbox-dockerd-start +145 -0
- package/runtime/digitalocean/agentbox-open +28 -0
- package/runtime/digitalocean/agentbox-portless-trust +82 -0
- package/runtime/digitalocean/agentbox-setup-skill.md +317 -0
- package/runtime/digitalocean/agentbox-vnc-start +102 -0
- package/runtime/digitalocean/claude-managed-settings.json +116 -0
- package/runtime/digitalocean/ctl.cjs +27852 -0
- package/runtime/digitalocean/custom-system-CLAUDE.md +39 -0
- package/runtime/digitalocean/gh-shim +344 -0
- package/runtime/digitalocean/git-shim +181 -0
- package/runtime/digitalocean/linear-shim +181 -0
- package/runtime/digitalocean/ntn-shim +95 -0
- package/runtime/digitalocean/opencode-agentbox-plugin.js +76 -0
- package/runtime/digitalocean/scripts/install-box.sh +462 -0
- package/runtime/docker/Dockerfile.box +5 -0
- package/runtime/docker/packages/ctl/dist/bin.cjs +468 -97
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-codex-hooks.json +1 -1
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-dockerd-start +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-open +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-portless-trust +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-sshd-start +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-vnc-start +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/chromium-resolver +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/custom-system-CLAUDE.md +2 -1
- package/runtime/docker/packages/sandbox-docker/scripts/gh-shim +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/git-shim +53 -3
- package/runtime/docker/packages/sandbox-docker/scripts/linear-shim +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/ntn-shim +0 -0
- package/runtime/e2b/agentbox-checkpoint-cleanup +0 -0
- package/runtime/e2b/agentbox-codex-hooks.json +1 -1
- package/runtime/e2b/agentbox-dockerd-start +0 -0
- package/runtime/e2b/agentbox-open +0 -0
- package/runtime/e2b/agentbox-vnc-start +0 -0
- package/runtime/e2b/ctl.cjs +468 -97
- package/runtime/e2b/custom-system-CLAUDE.md +6 -3
- package/runtime/e2b/gh-shim +0 -0
- package/runtime/e2b/git-shim +53 -3
- package/runtime/e2b/linear-shim +0 -0
- package/runtime/e2b/ntn-shim +0 -0
- package/runtime/e2b/scripts/build-template.sh +16 -0
- package/runtime/hetzner/agentbox-checkpoint-cleanup +0 -0
- package/runtime/hetzner/agentbox-codex-hooks.json +1 -1
- package/runtime/hetzner/agentbox-dockerd-start +0 -0
- package/runtime/hetzner/agentbox-open +0 -0
- package/runtime/hetzner/agentbox-portless-trust +0 -0
- package/runtime/hetzner/agentbox-vnc-start +0 -0
- package/runtime/hetzner/ctl.cjs +468 -97
- package/runtime/hetzner/custom-system-CLAUDE.md +1 -1
- package/runtime/hetzner/gh-shim +0 -0
- package/runtime/hetzner/git-shim +53 -3
- package/runtime/hetzner/linear-shim +0 -0
- package/runtime/hetzner/ntn-shim +0 -0
- package/runtime/hetzner/scripts/install-box.sh +5 -0
- package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
- package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +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_client-reference-manifest.js +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/chunks/[root-of-the-server]__0d1lmiq._.js +12 -12
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bqbkd5._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qa4a0v._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_06f2faq._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0760z6y._.js +8 -8
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_09gdzmo._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0ro6vh6._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0tgpglr._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_1laion6._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_0b_hsjl._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
- package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
- package/runtime/hub/apps/hub/.next/static/chunks/1c5w3kqosumog.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/1o3ot_9-8jgzc.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/380qcmusmigzz.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/3uq9hf-roasav.js +1 -0
- package/runtime/hub/apps/hub/{auth-675P3LQS.js → auth-Q447765C.js} +2 -2
- package/runtime/hub/apps/hub/{auth-config-AOBEKRZQ.js → auth-config-SIL635ZD.js} +2 -2
- package/runtime/hub/apps/hub/{chunk-H22XP3NY.js → chunk-3VE7AYVK.js} +600 -145
- package/runtime/hub/apps/hub/{chunk-EXQCBM5Q.js → chunk-64WEKO34.js} +42 -11
- package/runtime/hub/apps/hub/{chunk-56YQBVN2.js → chunk-DZPQB2JZ.js} +1 -1
- package/runtime/hub/apps/hub/{chunk-2Z74R6ZT.js → chunk-FGBXEXUV.js} +351 -292
- package/runtime/hub/apps/hub/{chunk-AR7CEZ2G.js → chunk-YVELHPNY.js} +218 -17
- package/runtime/hub/apps/hub/{dist-LZNRLUYY.js → dist-33ZNVTC6.js} +183 -49
- package/runtime/hub/apps/hub/{dist-Q6G66Z57.js → dist-4SXAJBOC.js} +195 -150
- package/runtime/hub/apps/hub/{dist-SD4G36EP.js → dist-EPJFN2J3.js} +116 -86
- package/runtime/hub/apps/hub/{dist-STQK5XM6.js → dist-GF5EBRNG.js} +1 -1
- package/runtime/hub/apps/hub/{dist-LNHEG5P4.js → dist-UJVIROA4.js} +19 -5
- package/runtime/hub/apps/hub/dist-XULFTIMT.js +2212 -0
- package/runtime/hub/apps/hub/{dist-VV6Z2CQX.js → dist-YM5J25H6.js} +7 -3
- package/runtime/hub/apps/hub/{hub-token-2BZFBBW3.js → hub-token-UITZEWVP.js} +2 -2
- package/runtime/hub/apps/hub/package.json +1 -0
- package/runtime/hub/apps/hub/{prepared-state-BUO75YLZ-CAXQS5Y3.js → prepared-state-BUO75YLZ-O4GZMDRF.js} +1 -1
- package/runtime/hub/apps/hub/server.js +38 -19
- package/runtime/relay/bin.cjs +275 -59
- package/runtime/vercel/agentbox-checkpoint-cleanup +0 -0
- package/runtime/vercel/agentbox-codex-hooks.json +1 -1
- package/runtime/vercel/agentbox-dockerd-start +0 -0
- package/runtime/vercel/agentbox-open +0 -0
- package/runtime/vercel/agentbox-vnc-start +0 -0
- package/runtime/vercel/ctl.cjs +468 -97
- package/runtime/vercel/custom-system-CLAUDE.md +3 -2
- package/runtime/vercel/gh-shim +0 -0
- package/runtime/vercel/git-shim +53 -3
- package/runtime/vercel/linear-shim +0 -0
- package/runtime/vercel/ntn-shim +0 -0
- package/runtime/vercel/scripts/provision.sh +16 -0
- package/dist/chunk-GGRZ3GZO.js.map +0 -1
- package/dist/chunk-I6ZRWTPR.js.map +0 -1
- package/dist/chunk-LA4JMS27.js.map +0 -1
- package/dist/chunk-LK2JT2OO.js.map +0 -1
- package/dist/chunk-QEQFZLYR.js.map +0 -1
- package/dist/chunk-QT3SHMLY.js.map +0 -1
- package/dist/chunk-SFA57TGX.js.map +0 -1
- package/dist/chunk-W3FQPFP7.js.map +0 -1
- package/dist/dist-FXQFTT75.js.map +0 -1
- package/dist/dist-V235KVEX.js.map +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/0joh_xsiowfc4.js +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/20hq7-0depjid.js +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/3p86ecqhr_7yy.js +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/3qof5hg87qf5n.js +0 -1
- /package/dist/{_cloud-attach-BQRWX3J2.js.map → _cloud-attach-T6GPR6LJ.js.map} +0 -0
- /package/dist/{dist-2BTJQUJS.js.map → dist-B7TNWGVG.js.map} +0 -0
- /package/dist/{dist-CUKBKS3N.js.map → dist-KYV3LEHG.js.map} +0 -0
- /package/dist/{dist-QO4CTLAX.js.map → dist-T5MXBZGP.js.map} +0 -0
- /package/dist/{dist-Z2NEVV55.js.map → dist-Z7KEPQC7.js.map} +0 -0
- /package/dist/{prepared-state-BUO75YLZ-CDTISC2C.js.map → prepared-state-BUO75YLZ-RQRFFBJW.js.map} +0 -0
- /package/runtime/hub/apps/hub/.next/static/{eVq-z4zld_8DGQudbYogV → XtIjHGqvY4mQsOY2-m1Jy}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{eVq-z4zld_8DGQudbYogV → XtIjHGqvY4mQsOY2-m1Jy}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{eVq-z4zld_8DGQudbYogV → XtIjHGqvY4mQsOY2-m1Jy}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,2212 @@
|
|
|
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
|
+
$e,
|
|
4
|
+
BD,
|
|
5
|
+
L,
|
|
6
|
+
fe,
|
|
7
|
+
me,
|
|
8
|
+
v,
|
|
9
|
+
ve,
|
|
10
|
+
we,
|
|
11
|
+
ye
|
|
12
|
+
} from "./chunk-OF242BLD.js";
|
|
13
|
+
import {
|
|
14
|
+
createCloudProvider
|
|
15
|
+
} from "./chunk-YVELHPNY.js";
|
|
16
|
+
import {
|
|
17
|
+
detectPortless,
|
|
18
|
+
portlessDoctorRow
|
|
19
|
+
} from "./chunk-FGBXEXUV.js";
|
|
20
|
+
import "./chunk-3LAHFDJF.js";
|
|
21
|
+
import {
|
|
22
|
+
UserFacingError,
|
|
23
|
+
claudeInstallFingerprint,
|
|
24
|
+
computeContextSha256,
|
|
25
|
+
describeInbound,
|
|
26
|
+
errSummary,
|
|
27
|
+
hostOpenCommand,
|
|
28
|
+
mintSshKey,
|
|
29
|
+
parseInboundSpec,
|
|
30
|
+
preparedStatePathFor,
|
|
31
|
+
readCliStamp,
|
|
32
|
+
readPreparedStateRaw,
|
|
33
|
+
resolveInboundSources,
|
|
34
|
+
stageAgentsStaticForUpload,
|
|
35
|
+
stageClaudeStaticForUpload,
|
|
36
|
+
stageCodexStaticForUpload,
|
|
37
|
+
stageOpencodeStaticForUpload,
|
|
38
|
+
writePreparedStateRaw
|
|
39
|
+
} from "./chunk-3VE7AYVK.js";
|
|
40
|
+
import {
|
|
41
|
+
execa
|
|
42
|
+
} from "./chunk-EFW34I43.js";
|
|
43
|
+
import "./chunk-64WEKO34.js";
|
|
44
|
+
import "./chunk-TZFWAJVB.js";
|
|
45
|
+
|
|
46
|
+
// ../../packages/sandbox-digitalocean/dist/chunk-NIR5EL3O.js
|
|
47
|
+
import { existsSync, readFileSync } from "fs";
|
|
48
|
+
import { homedir } from "os";
|
|
49
|
+
import { resolve } from "path";
|
|
50
|
+
import { spawnSync } from "child_process";
|
|
51
|
+
import {
|
|
52
|
+
chmodSync,
|
|
53
|
+
existsSync as existsSync2,
|
|
54
|
+
mkdirSync,
|
|
55
|
+
readFileSync as readFileSync2,
|
|
56
|
+
renameSync,
|
|
57
|
+
writeFileSync
|
|
58
|
+
} from "fs";
|
|
59
|
+
import { homedir as homedir2 } from "os";
|
|
60
|
+
import { dirname, resolve as resolve2 } from "path";
|
|
61
|
+
import { existsSync as existsSync3 } from "fs";
|
|
62
|
+
import { dirname as dirname2, resolve as resolve3 } from "path";
|
|
63
|
+
import { fileURLToPath } from "url";
|
|
64
|
+
var DIGITALOCEAN_KEYS = ["DIGITALOCEAN_TOKEN", "DIGITALOCEAN_API_URL"];
|
|
65
|
+
var loaded = false;
|
|
66
|
+
function ensureDigitalOceanEnvLoaded() {
|
|
67
|
+
if (loaded) return;
|
|
68
|
+
loaded = true;
|
|
69
|
+
importDigitalOceanFromFile(resolve(homedir(), ".agentbox", "secrets.env"));
|
|
70
|
+
}
|
|
71
|
+
function importDigitalOceanFromFile(path) {
|
|
72
|
+
if (!existsSync(path)) return;
|
|
73
|
+
let body;
|
|
74
|
+
try {
|
|
75
|
+
body = readFileSync(path, "utf8");
|
|
76
|
+
} catch {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const parsed = parseEnvFile(body);
|
|
80
|
+
for (const key of DIGITALOCEAN_KEYS) {
|
|
81
|
+
if (process.env[key] !== void 0) continue;
|
|
82
|
+
const value = parsed[key];
|
|
83
|
+
if (typeof value === "string") {
|
|
84
|
+
process.env[key] = value;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function parseEnvFile(body) {
|
|
89
|
+
const out = {};
|
|
90
|
+
for (const rawLine of body.split(/\r?\n/)) {
|
|
91
|
+
const line = rawLine.trim();
|
|
92
|
+
if (line.length === 0 || line.startsWith("#")) continue;
|
|
93
|
+
const stripped = line.startsWith("export ") ? line.slice("export ".length) : line;
|
|
94
|
+
const eq = stripped.indexOf("=");
|
|
95
|
+
if (eq <= 0) continue;
|
|
96
|
+
const key = stripped.slice(0, eq).trim();
|
|
97
|
+
let value = stripped.slice(eq + 1).trim();
|
|
98
|
+
if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
|
|
99
|
+
value = value.slice(1, -1);
|
|
100
|
+
}
|
|
101
|
+
out[key] = value;
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
var DEFAULT_DO_ENDPOINT = "https://api.digitalocean.com/v2";
|
|
106
|
+
var DigitalOceanApiError = class extends Error {
|
|
107
|
+
statusCode;
|
|
108
|
+
code;
|
|
109
|
+
requestId;
|
|
110
|
+
constructor(statusCode, code, message, requestId) {
|
|
111
|
+
super(`digitalocean ${String(statusCode)} ${code}: ${message}`);
|
|
112
|
+
this.name = "DigitalOceanApiError";
|
|
113
|
+
this.statusCode = statusCode;
|
|
114
|
+
this.code = code;
|
|
115
|
+
this.requestId = requestId;
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
function makeDigitalOceanClient(opts = {}) {
|
|
119
|
+
ensureDigitalOceanEnvLoaded();
|
|
120
|
+
const rawToken = opts.token ?? process.env.DIGITALOCEAN_TOKEN;
|
|
121
|
+
if (!rawToken || rawToken.trim().length === 0) {
|
|
122
|
+
throw new Error(
|
|
123
|
+
"DigitalOcean credentials not configured: DIGITALOCEAN_TOKEN is empty.\nRun `agentbox digitalocean login` interactively, or set DIGITALOCEAN_TOKEN in the environment."
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
const token = rawToken.trim();
|
|
127
|
+
const endpoint = (opts.endpoint ?? process.env.DIGITALOCEAN_API_URL ?? DEFAULT_DO_ENDPOINT).replace(/\/$/, "");
|
|
128
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
129
|
+
async function req(method, path, body) {
|
|
130
|
+
const url = path.startsWith("http") ? path : `${endpoint}${path}`;
|
|
131
|
+
const init = {
|
|
132
|
+
method,
|
|
133
|
+
headers: {
|
|
134
|
+
Authorization: `Bearer ${token}`,
|
|
135
|
+
...body !== void 0 ? { "Content-Type": "application/json" } : {}
|
|
136
|
+
},
|
|
137
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {}
|
|
138
|
+
};
|
|
139
|
+
const res = await fetchImpl(url, init);
|
|
140
|
+
if (res.status === 204) return null;
|
|
141
|
+
if (res.status === 404) return null;
|
|
142
|
+
if (!res.ok) {
|
|
143
|
+
let parsed = {};
|
|
144
|
+
try {
|
|
145
|
+
parsed = await res.json();
|
|
146
|
+
} catch {
|
|
147
|
+
}
|
|
148
|
+
const code = parsed.id ?? `http_${String(res.status)}`;
|
|
149
|
+
const msg = parsed.message ?? res.statusText ?? "unknown error";
|
|
150
|
+
throw new DigitalOceanApiError(res.status, code, msg, parsed.request_id);
|
|
151
|
+
}
|
|
152
|
+
const text = await res.text();
|
|
153
|
+
if (text.length === 0) return null;
|
|
154
|
+
return JSON.parse(text);
|
|
155
|
+
}
|
|
156
|
+
async function reqExpect(method, path, body) {
|
|
157
|
+
const out = await req(method, path, body);
|
|
158
|
+
if (out === null) {
|
|
159
|
+
throw new DigitalOceanApiError(0, "empty_response", `expected a body from ${method} ${path}`);
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
async function paginate(firstPath, key) {
|
|
164
|
+
const all = [];
|
|
165
|
+
let next = firstPath;
|
|
166
|
+
while (next) {
|
|
167
|
+
const r = await reqExpect("GET", next);
|
|
168
|
+
const page = r[key] ?? [];
|
|
169
|
+
all.push(...page);
|
|
170
|
+
const links = r.links;
|
|
171
|
+
next = links?.pages?.next;
|
|
172
|
+
}
|
|
173
|
+
return all;
|
|
174
|
+
}
|
|
175
|
+
function withPerPage(path) {
|
|
176
|
+
return path.includes("?") ? `${path}&per_page=200` : `${path}?per_page=200`;
|
|
177
|
+
}
|
|
178
|
+
async function dropletAction(id, payload) {
|
|
179
|
+
const r = await reqExpect(
|
|
180
|
+
"POST",
|
|
181
|
+
`/droplets/${String(id)}/actions`,
|
|
182
|
+
payload
|
|
183
|
+
);
|
|
184
|
+
return r.action;
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
async getAccount() {
|
|
188
|
+
const r = await reqExpect("GET", "/account");
|
|
189
|
+
return r.account;
|
|
190
|
+
},
|
|
191
|
+
async getDroplet(id) {
|
|
192
|
+
const r = await req("GET", `/droplets/${String(id)}`);
|
|
193
|
+
return r?.droplet ?? null;
|
|
194
|
+
},
|
|
195
|
+
async createDroplet(reqBody) {
|
|
196
|
+
const r = await reqExpect("POST", "/droplets", reqBody);
|
|
197
|
+
const createAction = r.links?.actions?.find((a) => a.rel === "create") ?? r.links?.actions?.[0];
|
|
198
|
+
return { droplet: r.droplet, actionId: createAction?.id ?? null };
|
|
199
|
+
},
|
|
200
|
+
async listDroplets(opts2) {
|
|
201
|
+
const base = opts2?.tag_name ? `/droplets?tag_name=${encodeURIComponent(opts2.tag_name)}` : "/droplets";
|
|
202
|
+
return paginate(withPerPage(base), "droplets");
|
|
203
|
+
},
|
|
204
|
+
async deleteDroplet(id) {
|
|
205
|
+
await req("DELETE", `/droplets/${String(id)}`);
|
|
206
|
+
},
|
|
207
|
+
async powerOn(id) {
|
|
208
|
+
return dropletAction(id, { type: "power_on" });
|
|
209
|
+
},
|
|
210
|
+
async powerOff(id) {
|
|
211
|
+
return dropletAction(id, { type: "power_off" });
|
|
212
|
+
},
|
|
213
|
+
async shutdown(id) {
|
|
214
|
+
return dropletAction(id, { type: "shutdown" });
|
|
215
|
+
},
|
|
216
|
+
async snapshotDroplet(id, name) {
|
|
217
|
+
return dropletAction(id, { type: "snapshot", name });
|
|
218
|
+
},
|
|
219
|
+
async getAction(id) {
|
|
220
|
+
const r = await req("GET", `/actions/${String(id)}`);
|
|
221
|
+
return r?.action ?? null;
|
|
222
|
+
},
|
|
223
|
+
async listSnapshots() {
|
|
224
|
+
return paginate(
|
|
225
|
+
withPerPage("/snapshots?resource_type=droplet"),
|
|
226
|
+
"snapshots"
|
|
227
|
+
);
|
|
228
|
+
},
|
|
229
|
+
async getSnapshot(id) {
|
|
230
|
+
const r = await req("GET", `/snapshots/${encodeURIComponent(id)}`);
|
|
231
|
+
return r?.snapshot ?? null;
|
|
232
|
+
},
|
|
233
|
+
async deleteSnapshot(id) {
|
|
234
|
+
await req("DELETE", `/snapshots/${encodeURIComponent(id)}`);
|
|
235
|
+
},
|
|
236
|
+
async listSizes() {
|
|
237
|
+
return paginate(withPerPage("/sizes"), "sizes");
|
|
238
|
+
},
|
|
239
|
+
async createFirewall(reqBody) {
|
|
240
|
+
const r = await reqExpect("POST", "/firewalls", reqBody);
|
|
241
|
+
return r.firewall;
|
|
242
|
+
},
|
|
243
|
+
async getFirewall(id) {
|
|
244
|
+
const r = await req("GET", `/firewalls/${encodeURIComponent(id)}`);
|
|
245
|
+
return r?.firewall ?? null;
|
|
246
|
+
},
|
|
247
|
+
async listFirewalls() {
|
|
248
|
+
return paginate(withPerPage("/firewalls"), "firewalls");
|
|
249
|
+
},
|
|
250
|
+
async updateFirewall(id, reqBody) {
|
|
251
|
+
const r = await reqExpect(
|
|
252
|
+
"PUT",
|
|
253
|
+
`/firewalls/${encodeURIComponent(id)}`,
|
|
254
|
+
reqBody
|
|
255
|
+
);
|
|
256
|
+
return r.firewall;
|
|
257
|
+
},
|
|
258
|
+
async deleteFirewall(id) {
|
|
259
|
+
await req("DELETE", `/firewalls/${encodeURIComponent(id)}`);
|
|
260
|
+
},
|
|
261
|
+
async createTag(name) {
|
|
262
|
+
try {
|
|
263
|
+
await req("POST", "/tags", { name });
|
|
264
|
+
} catch (err) {
|
|
265
|
+
if (err instanceof DigitalOceanApiError && err.statusCode === 422) return;
|
|
266
|
+
throw err;
|
|
267
|
+
}
|
|
268
|
+
},
|
|
269
|
+
async deleteTag(name) {
|
|
270
|
+
await req("DELETE", `/tags/${encodeURIComponent(name)}`);
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
function exitOnCancel(v2) {
|
|
275
|
+
if (BD(v2)) {
|
|
276
|
+
ve("Cancelled.");
|
|
277
|
+
process.exit(130);
|
|
278
|
+
}
|
|
279
|
+
return v2;
|
|
280
|
+
}
|
|
281
|
+
var DASHBOARD_KEYS_URL = "https://cloud.digitalocean.com/account/api/tokens";
|
|
282
|
+
var MANAGED_KEYS = ["DIGITALOCEAN_TOKEN", "DIGITALOCEAN_API_URL"];
|
|
283
|
+
async function ensureDigitalOceanCredentials(opts = {}) {
|
|
284
|
+
ensureDigitalOceanEnvLoaded();
|
|
285
|
+
if (!opts.force && hasUsableCredentials()) return;
|
|
286
|
+
if (!process.stdin.isTTY) return;
|
|
287
|
+
we("DigitalOcean setup");
|
|
288
|
+
ye(
|
|
289
|
+
`AgentBox needs a DigitalOcean Personal Access Token to provision Droplets.
|
|
290
|
+
|
|
291
|
+
1. Open ${DASHBOARD_KEYS_URL}
|
|
292
|
+
2. Click "Generate New Token".
|
|
293
|
+
3. Give it Read + Write scopes, then copy the token.`,
|
|
294
|
+
"API token required"
|
|
295
|
+
);
|
|
296
|
+
const open = exitOnCancel(
|
|
297
|
+
await me({
|
|
298
|
+
message: `Open ${DASHBOARD_KEYS_URL} in your browser?`,
|
|
299
|
+
initialValue: true
|
|
300
|
+
})
|
|
301
|
+
);
|
|
302
|
+
if (open) openDashboard();
|
|
303
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
304
|
+
const creds = await promptForCredentials();
|
|
305
|
+
const result = await validateCredentials(creds);
|
|
306
|
+
if (result.ok) {
|
|
307
|
+
persistCredentials(creds);
|
|
308
|
+
v.success(`DigitalOcean credentials saved to ${secretsPath()}`);
|
|
309
|
+
fe("Setup complete.");
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
if (result.kind === "auth" && attempt === 0) {
|
|
313
|
+
v.error(`That token was rejected by DigitalOcean: ${result.message}`);
|
|
314
|
+
v.info("Try again, or press Ctrl-C to cancel.");
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (result.kind === "network") {
|
|
318
|
+
v.warn(`Could not reach DigitalOcean to validate (${result.message}) \u2014 saving anyway.`);
|
|
319
|
+
persistCredentials(creds);
|
|
320
|
+
v.success(`DigitalOcean credentials saved to ${secretsPath()}`);
|
|
321
|
+
fe("Setup complete (unvalidated).");
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
throw new Error(`DigitalOcean credentials rejected: ${result.message}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function hasUsableCredentials() {
|
|
328
|
+
return typeof process.env.DIGITALOCEAN_TOKEN === "string" && process.env.DIGITALOCEAN_TOKEN.length > 0;
|
|
329
|
+
}
|
|
330
|
+
async function promptForCredentials() {
|
|
331
|
+
const token = exitOnCancel(
|
|
332
|
+
await $e({
|
|
333
|
+
message: "Paste your DigitalOcean Cloud API token",
|
|
334
|
+
validate(v2) {
|
|
335
|
+
if (!v2 || v2.trim().length === 0) return "Cannot be empty";
|
|
336
|
+
return void 0;
|
|
337
|
+
}
|
|
338
|
+
})
|
|
339
|
+
);
|
|
340
|
+
return { token: token.trim() };
|
|
341
|
+
}
|
|
342
|
+
async function validateCredentials(creds) {
|
|
343
|
+
const s = L();
|
|
344
|
+
s.start("Validating credentials with DigitalOcean");
|
|
345
|
+
try {
|
|
346
|
+
const client2 = makeDigitalOceanClient({ token: creds.token, endpoint: creds.endpoint });
|
|
347
|
+
await client2.getAccount();
|
|
348
|
+
s.stop("DigitalOcean credentials accepted");
|
|
349
|
+
return { ok: true };
|
|
350
|
+
} catch (err) {
|
|
351
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
352
|
+
s.stop("DigitalOcean credentials check failed");
|
|
353
|
+
if (/401|403|unauthor|forbidden|invalid|token/i.test(message)) {
|
|
354
|
+
return { ok: false, kind: "auth", message };
|
|
355
|
+
}
|
|
356
|
+
return { ok: false, kind: "network", message };
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
function persistCredentials(creds) {
|
|
360
|
+
process.env.DIGITALOCEAN_TOKEN = creds.token;
|
|
361
|
+
if (creds.endpoint) process.env.DIGITALOCEAN_API_URL = creds.endpoint;
|
|
362
|
+
const path = secretsPath();
|
|
363
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
364
|
+
let existing = "";
|
|
365
|
+
if (existsSync2(path)) {
|
|
366
|
+
try {
|
|
367
|
+
existing = readFileSync2(path, "utf8");
|
|
368
|
+
} catch {
|
|
369
|
+
existing = "";
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const kept = existing.split(/\r?\n/).filter((line) => {
|
|
373
|
+
const stripped = line.startsWith("export ") ? line.slice("export ".length) : line;
|
|
374
|
+
const eq = stripped.indexOf("=");
|
|
375
|
+
if (eq <= 0) return true;
|
|
376
|
+
const key = stripped.slice(0, eq).trim();
|
|
377
|
+
return !MANAGED_KEYS.includes(key);
|
|
378
|
+
}).join("\n").replace(/\s+$/u, "");
|
|
379
|
+
const lines = [`DIGITALOCEAN_TOKEN=${creds.token}`];
|
|
380
|
+
if (creds.endpoint) lines.push(`DIGITALOCEAN_API_URL=${creds.endpoint}`);
|
|
381
|
+
const body = (kept ? `${kept}
|
|
382
|
+
` : "") + lines.join("\n") + "\n";
|
|
383
|
+
const tmp = `${path}.tmp`;
|
|
384
|
+
writeFileSync(tmp, body, { mode: 384 });
|
|
385
|
+
try {
|
|
386
|
+
chmodSync(tmp, 384);
|
|
387
|
+
} catch {
|
|
388
|
+
}
|
|
389
|
+
renameSync(tmp, path);
|
|
390
|
+
try {
|
|
391
|
+
chmodSync(path, 384);
|
|
392
|
+
} catch {
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
async function setDigitalOceanCredentials(fields) {
|
|
396
|
+
const token = (fields.token ?? "").trim();
|
|
397
|
+
const endpoint = (fields.endpoint ?? "").trim() || void 0;
|
|
398
|
+
if (!token) {
|
|
399
|
+
return { ok: false, error: "token is required", status: { configured: false } };
|
|
400
|
+
}
|
|
401
|
+
const creds = { token, endpoint };
|
|
402
|
+
const result = await validateCredentials(creds);
|
|
403
|
+
if (!result.ok && result.kind === "auth") {
|
|
404
|
+
return {
|
|
405
|
+
ok: false,
|
|
406
|
+
error: `token rejected by DigitalOcean: ${result.message}`,
|
|
407
|
+
status: { configured: false }
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
persistCredentials(creds);
|
|
411
|
+
const label = result.ok ? "token" : "token (unvalidated)";
|
|
412
|
+
return { ok: true, status: { configured: true, label } };
|
|
413
|
+
}
|
|
414
|
+
function openDashboard() {
|
|
415
|
+
try {
|
|
416
|
+
const r = spawnSync(hostOpenCommand(), [DASHBOARD_KEYS_URL], { stdio: "ignore" });
|
|
417
|
+
if (r.status !== 0) {
|
|
418
|
+
v.warn(`Could not auto-open the browser \u2014 visit ${DASHBOARD_KEYS_URL} manually.`);
|
|
419
|
+
}
|
|
420
|
+
} catch {
|
|
421
|
+
v.warn(`Could not auto-open the browser \u2014 visit ${DASHBOARD_KEYS_URL} manually.`);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
function secretsPath() {
|
|
425
|
+
return resolve2(homedir2(), ".agentbox", "secrets.env");
|
|
426
|
+
}
|
|
427
|
+
function readDigitalOceanCredStatus() {
|
|
428
|
+
const shellHadToken = !!process.env.DIGITALOCEAN_TOKEN;
|
|
429
|
+
ensureDigitalOceanEnvLoaded();
|
|
430
|
+
const token = process.env.DIGITALOCEAN_TOKEN;
|
|
431
|
+
const endpoint = process.env.DIGITALOCEAN_API_URL;
|
|
432
|
+
if (!token) return { source: "none" };
|
|
433
|
+
return {
|
|
434
|
+
token,
|
|
435
|
+
endpoint,
|
|
436
|
+
source: shellHadToken ? "env" : "secrets.env"
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
function maskKey(value) {
|
|
440
|
+
if (value.length <= 8) return "*".repeat(value.length);
|
|
441
|
+
return `${value.slice(0, 4)}\u2026${"*".repeat(8)}${value.slice(-4)}`;
|
|
442
|
+
}
|
|
443
|
+
var PROBES = [
|
|
444
|
+
"https://api.ipify.org",
|
|
445
|
+
"https://ifconfig.io/ip",
|
|
446
|
+
"https://icanhazip.com"
|
|
447
|
+
];
|
|
448
|
+
var TIMEOUT_MS = 3e3;
|
|
449
|
+
var IPV4_RE = /^(?:\d{1,3}\.){3}\d{1,3}$/;
|
|
450
|
+
var IPV6_RE = /^[0-9a-fA-F:]+$/;
|
|
451
|
+
async function detectEgressIp(opts = {}) {
|
|
452
|
+
const probes = opts.probes ?? PROBES;
|
|
453
|
+
const timeout = opts.timeoutMs ?? TIMEOUT_MS;
|
|
454
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
455
|
+
const errors = [];
|
|
456
|
+
for (const url of probes) {
|
|
457
|
+
try {
|
|
458
|
+
const ip = await raceTimeout(probe(url, fetchImpl), timeout);
|
|
459
|
+
if (ip) {
|
|
460
|
+
opts.onLog?.(`egress-ip: detected ${ip} via ${url}`);
|
|
461
|
+
return ip;
|
|
462
|
+
}
|
|
463
|
+
errors.push(`${url}: empty/invalid response`);
|
|
464
|
+
} catch (err) {
|
|
465
|
+
errors.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
throw new Error(
|
|
469
|
+
`could not auto-detect the host's egress IP \u2014 all ${String(probes.length)} probes failed:
|
|
470
|
+
` + errors.map((e) => ` - ${e}`).join("\n") + `
|
|
471
|
+
Override with --firewall-source <cidr> (e.g. --firewall-source 0.0.0.0/0 for the explicit-open opt-in).`
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
async function probe(url, fetchImpl) {
|
|
475
|
+
const res = await fetchImpl(url, { method: "GET" });
|
|
476
|
+
if (!res.ok) return null;
|
|
477
|
+
const body = (await res.text()).trim();
|
|
478
|
+
if (IPV4_RE.test(body)) {
|
|
479
|
+
const parts = body.split(".").map((p) => Number.parseInt(p, 10));
|
|
480
|
+
if (parts.every((p) => p >= 0 && p <= 255)) return body;
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
if (IPV6_RE.test(body) && body.includes(":")) return body;
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
async function raceTimeout(p, ms) {
|
|
487
|
+
let timer;
|
|
488
|
+
try {
|
|
489
|
+
return await Promise.race([
|
|
490
|
+
p,
|
|
491
|
+
new Promise((_resolve, reject) => {
|
|
492
|
+
timer = setTimeout(() => reject(new Error(`probe timed out after ${String(ms)}ms`)), ms);
|
|
493
|
+
})
|
|
494
|
+
]);
|
|
495
|
+
} finally {
|
|
496
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
var DEFAULT_BACKOFF = [1e3, 2e3, 4e3];
|
|
500
|
+
var DEFAULT_ATTEMPT_TIMEOUT_MS = 3e4;
|
|
501
|
+
var AttemptTimeoutError = class extends Error {
|
|
502
|
+
constructor(method, ms) {
|
|
503
|
+
super(`digitalocean ${method}: per-attempt timeout after ${String(ms)}ms`);
|
|
504
|
+
this.name = "AttemptTimeoutError";
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
function isAttemptTimeout(err) {
|
|
508
|
+
return err instanceof AttemptTimeoutError;
|
|
509
|
+
}
|
|
510
|
+
function isRetriable(err, allowAmbiguous) {
|
|
511
|
+
if (err instanceof DigitalOceanApiError) {
|
|
512
|
+
if (err.statusCode === 429 || err.code === "rate_limit_exceeded") return true;
|
|
513
|
+
if (err.statusCode >= 500 && err.statusCode <= 599) return allowAmbiguous;
|
|
514
|
+
if (err.code === "locked" || err.code === "conflict") return true;
|
|
515
|
+
return false;
|
|
516
|
+
}
|
|
517
|
+
if (err instanceof AttemptTimeoutError) return allowAmbiguous;
|
|
518
|
+
if (err && typeof err === "object") {
|
|
519
|
+
const candidates = [err, err.cause];
|
|
520
|
+
for (const c of candidates) {
|
|
521
|
+
if (!c || typeof c !== "object") continue;
|
|
522
|
+
const code = c.code;
|
|
523
|
+
if (code === "ECONNRESET" || code === "ETIMEDOUT" || code === "ECONNABORTED" || code === "EAI_AGAIN" || code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "UND_ERR_SOCKET" || code === "UND_ERR_CONNECT_TIMEOUT") {
|
|
524
|
+
return allowAmbiguous;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return false;
|
|
529
|
+
}
|
|
530
|
+
async function withDigitalOceanRetry(opts, fn) {
|
|
531
|
+
const backoff = opts.backoffMs ?? DEFAULT_BACKOFF;
|
|
532
|
+
const maxAttempts = backoff.length + 1;
|
|
533
|
+
const timeoutMs = opts.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS;
|
|
534
|
+
const log2 = opts.onRetry ?? defaultRetryLog;
|
|
535
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
536
|
+
try {
|
|
537
|
+
return await raceTimeout2(fn(), timeoutMs, opts.method);
|
|
538
|
+
} catch (err) {
|
|
539
|
+
const last = attempt === maxAttempts;
|
|
540
|
+
if (last || !isRetriable(err, opts.retryOnAmbiguous)) throw err;
|
|
541
|
+
const delay = backoff[attempt - 1] ?? backoff[backoff.length - 1] ?? 4e3;
|
|
542
|
+
log2(
|
|
543
|
+
`digitalocean ${opts.method}: attempt ${String(attempt)} failed (${errorSummary(err)}); retrying in ${String(delay)}ms`
|
|
544
|
+
);
|
|
545
|
+
await sleep(delay);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
throw new Error(`withDigitalOceanRetry: exhausted attempts for ${opts.method}`);
|
|
549
|
+
}
|
|
550
|
+
function defaultRetryLog(line) {
|
|
551
|
+
process.stderr.write(`
|
|
552
|
+
[digitalocean-retry] ${line}
|
|
553
|
+
`);
|
|
554
|
+
}
|
|
555
|
+
function sleep(ms) {
|
|
556
|
+
return new Promise((resolve42) => setTimeout(resolve42, ms));
|
|
557
|
+
}
|
|
558
|
+
async function raceTimeout2(p, ms, method) {
|
|
559
|
+
let timer;
|
|
560
|
+
try {
|
|
561
|
+
return await Promise.race([
|
|
562
|
+
p,
|
|
563
|
+
new Promise((_resolve, reject) => {
|
|
564
|
+
timer = setTimeout(() => reject(new AttemptTimeoutError(method, ms)), ms);
|
|
565
|
+
})
|
|
566
|
+
]);
|
|
567
|
+
} finally {
|
|
568
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
function errorSummary(err) {
|
|
572
|
+
if (err instanceof DigitalOceanApiError) {
|
|
573
|
+
return `DigitalOceanApiError ${String(err.statusCode)} ${err.code}: ${truncate(err.message)}`;
|
|
574
|
+
}
|
|
575
|
+
if (err instanceof Error) {
|
|
576
|
+
const code = err.code;
|
|
577
|
+
return code !== void 0 ? `${err.name}(${String(code)}): ${truncate(err.message)}` : `${err.name}: ${truncate(err.message)}`;
|
|
578
|
+
}
|
|
579
|
+
return truncate(String(err));
|
|
580
|
+
}
|
|
581
|
+
function truncate(s, max = 160) {
|
|
582
|
+
return s.length > max ? `${s.slice(0, max)}\u2026` : s;
|
|
583
|
+
}
|
|
584
|
+
function sshInboundRules(sources) {
|
|
585
|
+
const addresses = Array.isArray(sources) ? sources : [sources];
|
|
586
|
+
return [
|
|
587
|
+
{
|
|
588
|
+
protocol: "tcp",
|
|
589
|
+
ports: "22",
|
|
590
|
+
sources: { addresses }
|
|
591
|
+
}
|
|
592
|
+
];
|
|
593
|
+
}
|
|
594
|
+
function allowAllOutboundRules() {
|
|
595
|
+
const everywhere = { addresses: ["0.0.0.0/0", "::/0"] };
|
|
596
|
+
return [
|
|
597
|
+
{ protocol: "tcp", ports: "1-65535", destinations: everywhere },
|
|
598
|
+
{ protocol: "udp", ports: "1-65535", destinations: everywhere },
|
|
599
|
+
// icmp takes no ports in DigitalOcean's API.
|
|
600
|
+
{ protocol: "icmp", destinations: everywhere }
|
|
601
|
+
];
|
|
602
|
+
}
|
|
603
|
+
async function createPerBoxFirewall(client2, opts) {
|
|
604
|
+
await withDigitalOceanRetry(
|
|
605
|
+
{ method: "createTag", retryOnAmbiguous: true, attemptTimeoutMs: 6e4 },
|
|
606
|
+
() => client2.createTag(opts.tag)
|
|
607
|
+
);
|
|
608
|
+
const body = {
|
|
609
|
+
name: opts.name,
|
|
610
|
+
inbound_rules: sshInboundRules(opts.sources),
|
|
611
|
+
outbound_rules: allowAllOutboundRules(),
|
|
612
|
+
tags: [opts.tag]
|
|
613
|
+
};
|
|
614
|
+
return withDigitalOceanRetry(
|
|
615
|
+
{ method: "createFirewall", retryOnAmbiguous: false, attemptTimeoutMs: 6e4 },
|
|
616
|
+
() => client2.createFirewall(body)
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
async function syncFirewallSource(client2, firewall, sources) {
|
|
620
|
+
const body = {
|
|
621
|
+
name: firewall.name,
|
|
622
|
+
inbound_rules: sshInboundRules(sources),
|
|
623
|
+
outbound_rules: allowAllOutboundRules(),
|
|
624
|
+
droplet_ids: firewall.droplet_ids,
|
|
625
|
+
tags: firewall.tags
|
|
626
|
+
};
|
|
627
|
+
await withDigitalOceanRetry(
|
|
628
|
+
{ method: "updateFirewall", retryOnAmbiguous: true, attemptTimeoutMs: 6e4 },
|
|
629
|
+
() => client2.updateFirewall(firewall.id, body)
|
|
630
|
+
);
|
|
631
|
+
}
|
|
632
|
+
async function findFirewallForDroplet(client2, dropletId, dropletTags) {
|
|
633
|
+
const tagSet = new Set(dropletTags);
|
|
634
|
+
const all = await client2.listFirewalls();
|
|
635
|
+
return all.find(
|
|
636
|
+
(fw) => fw.droplet_ids.includes(dropletId) || fw.tags.some((t) => tagSet.has(t))
|
|
637
|
+
) ?? null;
|
|
638
|
+
}
|
|
639
|
+
async function deletePerBoxFirewall(client2, firewallId, opts = {}) {
|
|
640
|
+
const deadline = Date.now() + (opts.detachWaitMs ?? 6e4);
|
|
641
|
+
let interval = 1e3;
|
|
642
|
+
const cleanupTags = async () => {
|
|
643
|
+
for (const t of opts.tags ?? []) {
|
|
644
|
+
try {
|
|
645
|
+
await client2.deleteTag(t);
|
|
646
|
+
} catch {
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
while (true) {
|
|
651
|
+
try {
|
|
652
|
+
await withDigitalOceanRetry(
|
|
653
|
+
{ method: "deleteFirewall", retryOnAmbiguous: true, attemptTimeoutMs: 3e4 },
|
|
654
|
+
() => client2.deleteFirewall(firewallId)
|
|
655
|
+
);
|
|
656
|
+
await cleanupTags();
|
|
657
|
+
return;
|
|
658
|
+
} catch (err) {
|
|
659
|
+
if (err instanceof DigitalOceanApiError && (err.statusCode === 404 || err.code === "not_found")) {
|
|
660
|
+
await cleanupTags();
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
const stillAttached = err instanceof DigitalOceanApiError && (err.statusCode === 409 || err.code === "conflict" || err.code === "resource_in_use");
|
|
664
|
+
if (stillAttached && Date.now() < deadline) {
|
|
665
|
+
await new Promise((r) => setTimeout(r, interval));
|
|
666
|
+
interval = Math.min(interval * 2, 8e3);
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
throw err;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
function normalizeSourceCidr(raw) {
|
|
674
|
+
const trimmed = raw.trim();
|
|
675
|
+
if (trimmed.includes("/")) return trimmed;
|
|
676
|
+
if (trimmed.includes(":")) return `${trimmed}/128`;
|
|
677
|
+
return `${trimmed}/32`;
|
|
678
|
+
}
|
|
679
|
+
var SELF = dirname2(fileURLToPath(import.meta.url));
|
|
680
|
+
function findStagedCliRuntimeRoot() {
|
|
681
|
+
const candidates = [
|
|
682
|
+
resolve3(SELF, "..", "runtime"),
|
|
683
|
+
// <cliRoot>/dist/.. → <cliRoot> then /runtime
|
|
684
|
+
resolve3(SELF, "..", "..", "runtime")
|
|
685
|
+
// chunk-NNNN.js at <cliRoot>/dist/<sub>/.. → <cliRoot>/runtime
|
|
686
|
+
];
|
|
687
|
+
for (const c of candidates) {
|
|
688
|
+
if (existsSync3(resolve3(c, "digitalocean", "scripts", "install-box.sh"))) return c;
|
|
689
|
+
}
|
|
690
|
+
return void 0;
|
|
691
|
+
}
|
|
692
|
+
var RUNTIME_ASSETS = [
|
|
693
|
+
{ name: "install-box.sh", remoteBasename: "agentbox-install.sh", remoteMode: 493 },
|
|
694
|
+
{ name: "agentbox-ctl", remoteBasename: "agentbox-ctl", remoteMode: 493 },
|
|
695
|
+
{ name: "agentbox-vnc-start", remoteBasename: "agentbox-vnc-start", remoteMode: 493 },
|
|
696
|
+
{ name: "agentbox-dockerd-start", remoteBasename: "agentbox-dockerd-start", remoteMode: 493 },
|
|
697
|
+
{ name: "agentbox-portless-trust", remoteBasename: "agentbox-portless-trust", remoteMode: 493 },
|
|
698
|
+
{ name: "agentbox-checkpoint-cleanup", remoteBasename: "agentbox-checkpoint-cleanup", remoteMode: 493 },
|
|
699
|
+
{ name: "agentbox-open", remoteBasename: "agentbox-open", remoteMode: 493 },
|
|
700
|
+
{ name: "gh-shim", remoteBasename: "agentbox-gh-shim", remoteMode: 493 },
|
|
701
|
+
{ name: "git-shim", remoteBasename: "agentbox-git-shim", remoteMode: 493 },
|
|
702
|
+
{ name: "ntn-shim", remoteBasename: "agentbox-ntn-shim", remoteMode: 493 },
|
|
703
|
+
{ name: "linear-shim", remoteBasename: "agentbox-linear-shim", remoteMode: 493 },
|
|
704
|
+
{ name: "custom-system-CLAUDE.md", remoteBasename: "agentbox-custom-CLAUDE.md", remoteMode: 420 },
|
|
705
|
+
{ name: "claude-managed-settings.json", remoteBasename: "agentbox-managed-settings.json", remoteMode: 420 },
|
|
706
|
+
{ name: "agentbox-codex-hooks.json", remoteBasename: "agentbox-codex-hooks.json", remoteMode: 420 },
|
|
707
|
+
{ name: "agentbox-setup-skill.md", remoteBasename: "agentbox-setup-skill.md", remoteMode: 420 }
|
|
708
|
+
];
|
|
709
|
+
function candidatesFor(name, opts = {}) {
|
|
710
|
+
const cliRoot = opts.cliRuntimeRoot;
|
|
711
|
+
const monorepo = opts.repoRoot ?? guessRepoRoot();
|
|
712
|
+
const monorepoRelative = {
|
|
713
|
+
"install-box.sh": ["packages/sandbox-digitalocean/scripts/install-box.sh"],
|
|
714
|
+
"agentbox-ctl": ["packages/ctl/dist/bin.cjs"],
|
|
715
|
+
"agentbox-vnc-start": ["packages/sandbox-docker/scripts/agentbox-vnc-start"],
|
|
716
|
+
"agentbox-dockerd-start": ["packages/sandbox-docker/scripts/agentbox-dockerd-start"],
|
|
717
|
+
"agentbox-portless-trust": ["packages/sandbox-docker/scripts/agentbox-portless-trust"],
|
|
718
|
+
"agentbox-checkpoint-cleanup": ["packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup"],
|
|
719
|
+
"agentbox-open": ["packages/sandbox-docker/scripts/agentbox-open"],
|
|
720
|
+
"gh-shim": ["packages/sandbox-docker/scripts/gh-shim"],
|
|
721
|
+
"git-shim": ["packages/sandbox-docker/scripts/git-shim"],
|
|
722
|
+
"ntn-shim": ["packages/sandbox-docker/scripts/ntn-shim"],
|
|
723
|
+
"linear-shim": ["packages/sandbox-docker/scripts/linear-shim"],
|
|
724
|
+
"custom-system-CLAUDE.md": ["packages/sandbox-digitalocean/scripts/custom-system-CLAUDE.md"],
|
|
725
|
+
"claude-managed-settings.json": ["packages/sandbox-docker/scripts/claude-managed-settings.json"],
|
|
726
|
+
"agentbox-codex-hooks.json": ["packages/sandbox-docker/scripts/agentbox-codex-hooks.json"],
|
|
727
|
+
"agentbox-setup-skill.md": ["apps/cli/share/agentbox-setup/SKILL.md"]
|
|
728
|
+
};
|
|
729
|
+
const cliRelative = {
|
|
730
|
+
"install-box.sh": ["digitalocean/scripts/install-box.sh"],
|
|
731
|
+
"agentbox-ctl": ["digitalocean/ctl.cjs"],
|
|
732
|
+
"agentbox-vnc-start": ["digitalocean/agentbox-vnc-start", "docker/packages/sandbox-docker/scripts/agentbox-vnc-start"],
|
|
733
|
+
"agentbox-dockerd-start": ["digitalocean/agentbox-dockerd-start", "docker/packages/sandbox-docker/scripts/agentbox-dockerd-start"],
|
|
734
|
+
"agentbox-portless-trust": ["digitalocean/agentbox-portless-trust", "docker/packages/sandbox-docker/scripts/agentbox-portless-trust"],
|
|
735
|
+
"agentbox-checkpoint-cleanup": ["digitalocean/agentbox-checkpoint-cleanup", "docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup"],
|
|
736
|
+
"agentbox-open": ["digitalocean/agentbox-open", "docker/packages/sandbox-docker/scripts/agentbox-open"],
|
|
737
|
+
"gh-shim": ["digitalocean/gh-shim", "docker/packages/sandbox-docker/scripts/gh-shim"],
|
|
738
|
+
"git-shim": ["digitalocean/git-shim", "docker/packages/sandbox-docker/scripts/git-shim"],
|
|
739
|
+
"ntn-shim": ["digitalocean/ntn-shim", "docker/packages/sandbox-docker/scripts/ntn-shim"],
|
|
740
|
+
"linear-shim": ["digitalocean/linear-shim", "docker/packages/sandbox-docker/scripts/linear-shim"],
|
|
741
|
+
"custom-system-CLAUDE.md": ["digitalocean/custom-system-CLAUDE.md"],
|
|
742
|
+
"claude-managed-settings.json": ["digitalocean/claude-managed-settings.json", "docker/packages/sandbox-docker/scripts/claude-managed-settings.json"],
|
|
743
|
+
"agentbox-codex-hooks.json": ["digitalocean/agentbox-codex-hooks.json", "docker/packages/sandbox-docker/scripts/agentbox-codex-hooks.json"],
|
|
744
|
+
"agentbox-setup-skill.md": ["digitalocean/agentbox-setup-skill.md", "docker/apps/cli/share/agentbox-setup/SKILL.md"]
|
|
745
|
+
};
|
|
746
|
+
const out = [];
|
|
747
|
+
if (cliRoot) {
|
|
748
|
+
for (const rel of cliRelative[name] ?? []) out.push(resolve3(cliRoot, rel));
|
|
749
|
+
}
|
|
750
|
+
for (const rel of monorepoRelative[name] ?? []) out.push(resolve3(monorepo, rel));
|
|
751
|
+
return out;
|
|
752
|
+
}
|
|
753
|
+
function resolveRuntimeAssets(opts = {}) {
|
|
754
|
+
const out = [];
|
|
755
|
+
const missing = [];
|
|
756
|
+
for (const asset of RUNTIME_ASSETS) {
|
|
757
|
+
const cands = candidatesFor(asset.name, opts);
|
|
758
|
+
const hit = cands.find((p) => existsSync3(p));
|
|
759
|
+
if (!hit) {
|
|
760
|
+
missing.push({ name: asset.name, tried: cands });
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
out.push({ ...asset, localPath: hit });
|
|
764
|
+
}
|
|
765
|
+
if (missing.length > 0) {
|
|
766
|
+
const lines = missing.flatMap((m) => [` - ${m.name}: tried`, ...m.tried.map((p) => ` ${p}`)]);
|
|
767
|
+
throw new Error(
|
|
768
|
+
`digitalocean: could not resolve runtime assets \u2014 these files are needed to install on the prepare VPS:
|
|
769
|
+
` + lines.join("\n") + `
|
|
770
|
+
|
|
771
|
+
If you are running from the monorepo, ensure \`pnpm -w build\` has run so packages/ctl/dist/bin.cjs exists. If you are running from a published CLI bundle, the runtime/digitalocean tree should be staged automatically.`
|
|
772
|
+
);
|
|
773
|
+
}
|
|
774
|
+
return out;
|
|
775
|
+
}
|
|
776
|
+
function guessRepoRoot() {
|
|
777
|
+
let cur = SELF;
|
|
778
|
+
for (let i = 0; i < 8; i++) {
|
|
779
|
+
if (existsSync3(resolve3(cur, "pnpm-workspace.yaml"))) return cur;
|
|
780
|
+
const parent = dirname2(cur);
|
|
781
|
+
if (parent === cur) break;
|
|
782
|
+
cur = parent;
|
|
783
|
+
}
|
|
784
|
+
return SELF;
|
|
785
|
+
}
|
|
786
|
+
var SCHEMA = 2;
|
|
787
|
+
function preparedStatePath() {
|
|
788
|
+
return preparedStatePathFor("digitalocean");
|
|
789
|
+
}
|
|
790
|
+
function readPreparedState() {
|
|
791
|
+
const raw = readPreparedStateRaw("digitalocean");
|
|
792
|
+
if (raw === null || typeof raw !== "object") return { schema: SCHEMA };
|
|
793
|
+
const parsed = raw;
|
|
794
|
+
if (parsed.schema === 1) {
|
|
795
|
+
const v1 = parsed;
|
|
796
|
+
return migrateFromV1(v1);
|
|
797
|
+
}
|
|
798
|
+
if (parsed.schema !== SCHEMA) {
|
|
799
|
+
return { schema: SCHEMA };
|
|
800
|
+
}
|
|
801
|
+
return {
|
|
802
|
+
schema: SCHEMA,
|
|
803
|
+
base: parsed.base
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
function migrateFromV1(v1) {
|
|
807
|
+
const base = v1.base ? {
|
|
808
|
+
imageId: v1.base.imageId,
|
|
809
|
+
description: v1.base.description,
|
|
810
|
+
createdAt: v1.base.createdAt,
|
|
811
|
+
contextSha256: v1.base.installScriptSha256
|
|
812
|
+
} : void 0;
|
|
813
|
+
return {
|
|
814
|
+
schema: SCHEMA,
|
|
815
|
+
base
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
function writePreparedState(state) {
|
|
819
|
+
writePreparedStateRaw("digitalocean", state);
|
|
820
|
+
}
|
|
821
|
+
function updatePreparedState(mutate) {
|
|
822
|
+
const s = readPreparedState();
|
|
823
|
+
mutate(s);
|
|
824
|
+
writePreparedState(s);
|
|
825
|
+
}
|
|
826
|
+
async function currentDigitalOceanBaseFingerprintLive(claudeInstall = "native") {
|
|
827
|
+
try {
|
|
828
|
+
const assets = resolveRuntimeAssets({ cliRuntimeRoot: findStagedCliRuntimeRoot() });
|
|
829
|
+
return claudeInstallFingerprint(
|
|
830
|
+
await computeContextSha256(assets.map((a) => ({ rel: a.name, abs: a.localPath }))),
|
|
831
|
+
claudeInstall
|
|
832
|
+
);
|
|
833
|
+
} catch {
|
|
834
|
+
return void 0;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// ../../packages/sandbox-digitalocean/dist/index.js
|
|
839
|
+
import { existsSync as existsSync22 } from "fs";
|
|
840
|
+
import { rm as rm2, rename, mkdir as mkdir2 } from "fs/promises";
|
|
841
|
+
import { join as join3 } from "path";
|
|
842
|
+
import { resolve as resolvePath } from "path";
|
|
843
|
+
import { join } from "path";
|
|
844
|
+
import { dirname as dirname3, resolve as resolve4 } from "path";
|
|
845
|
+
import { existsSync as existsSync4 } from "fs";
|
|
846
|
+
import { mkdir, rm } from "fs/promises";
|
|
847
|
+
import { createServer } from "net";
|
|
848
|
+
import { homedir as homedir3 } from "os";
|
|
849
|
+
import { dirname as dirname22, join as join2, resolve as resolve22 } from "path";
|
|
850
|
+
function generatePrepareCloudInit(opts) {
|
|
851
|
+
const pubkey = opts.sshPubkey.trim();
|
|
852
|
+
return [
|
|
853
|
+
"#cloud-config",
|
|
854
|
+
// IMPORTANT: keep every emitted line ASCII-only. DigitalOcean's user-data
|
|
855
|
+
// delivery truncates the cloud-config at the first non-ASCII byte (an em-dash
|
|
856
|
+
// here silently dropped the whole doc -> no key injected -> ssh publickey
|
|
857
|
+
// denied). See generateBoxCloudInit for the same constraint.
|
|
858
|
+
"# AgentBox temporary prepare VPS - used by `agentbox prepare --provider digitalocean`",
|
|
859
|
+
"# to bake the base snapshot. SSH key is single-use and discarded on VPS destroy.",
|
|
860
|
+
"disable_root: false",
|
|
861
|
+
"ssh_pwauth: false",
|
|
862
|
+
// Inject the single-use key as a TOP-LEVEL `ssh_authorized_keys` (applies to
|
|
863
|
+
// the default user, which is `root` on DigitalOcean images). The `users:`
|
|
864
|
+
// block form does NOT inject a key for root on DO's Ubuntu 24.04 (cloud-init
|
|
865
|
+
// special-cases root under `disable_root`), so key auth failed with
|
|
866
|
+
// "Permission denied (publickey)". The top-level form is reliable.
|
|
867
|
+
"ssh_authorized_keys:",
|
|
868
|
+
` - ${yamlScalar(pubkey)}`,
|
|
869
|
+
// DigitalOcean's Ubuntu 24.04 stock image ships root's password force-expired
|
|
870
|
+
// (last-change date = 0), so PAM demands a change on first login — which
|
|
871
|
+
// blocks even key-authed non-TTY commands ("Password change required but no
|
|
872
|
+
// TTY available"). `chpasswd.expire:false` covers cloud-init's own run; the
|
|
873
|
+
// runcmd resets root's last-change date to TODAY (clearing the forced-change
|
|
874
|
+
// that `chage -E/-I/-M` alone does NOT touch) and disables all expiry.
|
|
875
|
+
"chpasswd:",
|
|
876
|
+
" expire: false",
|
|
877
|
+
"runcmd:",
|
|
878
|
+
" - [ passwd, -d, root ]",
|
|
879
|
+
' - [ bash, -lc, "chage -d $(date +%Y-%m-%d) -E -1 -I -1 -M 99999 -m 0 root" ]',
|
|
880
|
+
' - [ bash, -lc, "echo agentbox-prepare-ready" ]',
|
|
881
|
+
""
|
|
882
|
+
].join("\n");
|
|
883
|
+
}
|
|
884
|
+
function generateBoxCloudInit(opts) {
|
|
885
|
+
const pubkey = opts.sshPubkey.trim();
|
|
886
|
+
const lines = [
|
|
887
|
+
"#cloud-config",
|
|
888
|
+
// ASCII-only (see generatePrepareCloudInit): DO truncates user-data at the
|
|
889
|
+
// first non-ASCII byte, which would drop the whole cloud-config.
|
|
890
|
+
`# AgentBox per-box VPS - box '${opts.boxName}'`,
|
|
891
|
+
"disable_root: true",
|
|
892
|
+
"ssh_pwauth: false",
|
|
893
|
+
// Same first-login expiry guard as the prepare cloud-init — keeps
|
|
894
|
+
// DigitalOcean's Ubuntu hardening from blocking our key-based vscode login.
|
|
895
|
+
"chpasswd:",
|
|
896
|
+
" expire: false",
|
|
897
|
+
"users:",
|
|
898
|
+
" - name: vscode",
|
|
899
|
+
" lock_passwd: false",
|
|
900
|
+
" sudo: ALL=(ALL) NOPASSWD:ALL",
|
|
901
|
+
" ssh_authorized_keys:",
|
|
902
|
+
` - ${yamlScalar(pubkey)}`
|
|
903
|
+
];
|
|
904
|
+
const writeFiles = [
|
|
905
|
+
" path: /etc/hosts",
|
|
906
|
+
" append: true",
|
|
907
|
+
` content: "127.0.0.1 ${opts.boxName}.localhost\\n"`
|
|
908
|
+
];
|
|
909
|
+
lines.push("write_files:");
|
|
910
|
+
lines.push(" - " + writeFiles[0]);
|
|
911
|
+
for (let i = 1; i < writeFiles.length; i++) {
|
|
912
|
+
lines.push(" " + writeFiles[i]);
|
|
913
|
+
}
|
|
914
|
+
if (opts.boxEnv && Object.keys(opts.boxEnv).length > 0) {
|
|
915
|
+
const envContent = Object.entries(opts.boxEnv).map(([k, v2]) => `${k}=${v2}`).join("\\n") + "\\n";
|
|
916
|
+
lines.push(" - path: /etc/agentbox/box.env");
|
|
917
|
+
lines.push(' permissions: "0644"');
|
|
918
|
+
lines.push(` content: "${envContent}"`);
|
|
919
|
+
}
|
|
920
|
+
lines.push("");
|
|
921
|
+
return lines.join("\n");
|
|
922
|
+
}
|
|
923
|
+
function yamlScalar(value) {
|
|
924
|
+
if (/["\\]/.test(value)) {
|
|
925
|
+
return JSON.stringify(value);
|
|
926
|
+
}
|
|
927
|
+
return `"${value}"`;
|
|
928
|
+
}
|
|
929
|
+
async function pollUntil(label, check, opts = {}) {
|
|
930
|
+
const deadline = Date.now() + (opts.deadlineMs ?? 5 * 6e4);
|
|
931
|
+
const max = opts.maxIntervalMs ?? 1e4;
|
|
932
|
+
let interval = opts.intervalMs ?? 1e3;
|
|
933
|
+
let attempt = 0;
|
|
934
|
+
while (true) {
|
|
935
|
+
attempt += 1;
|
|
936
|
+
const out = await check();
|
|
937
|
+
if (out !== null && out !== void 0) return out;
|
|
938
|
+
if (Date.now() >= deadline) {
|
|
939
|
+
throw new Error(`digitalocean: timed out waiting for ${label} after ${String(attempt)} attempts`);
|
|
940
|
+
}
|
|
941
|
+
opts.onPoll?.(`${label}: not ready yet (attempt ${String(attempt)}); polling again in ${String(interval)}ms`);
|
|
942
|
+
await new Promise((r) => setTimeout(r, interval));
|
|
943
|
+
interval = Math.min(interval * 2, max);
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
function suggestSizes(catalog, limit = 6) {
|
|
947
|
+
return catalog.filter((s) => s.available).map((s) => s.slug).slice(0, limit);
|
|
948
|
+
}
|
|
949
|
+
function validateSizeChoice(choice, catalog, snapshot) {
|
|
950
|
+
const { size, region } = choice;
|
|
951
|
+
const plan = catalog.find((s) => s.slug === size);
|
|
952
|
+
if (!plan) {
|
|
953
|
+
const suggestions = suggestSizes(catalog);
|
|
954
|
+
const hint = suggestions.length > 0 ? ` Valid sizes include: ${suggestions.join(", ")}.` : "";
|
|
955
|
+
throw new UserFacingError(
|
|
956
|
+
`DigitalOcean size "${size}" does not exist.${hint}
|
|
957
|
+
Set one with \`--size <slug>\` or \`agentbox config set box.sizeDigitalocean <slug>\`.`
|
|
958
|
+
);
|
|
959
|
+
}
|
|
960
|
+
if (!plan.available) {
|
|
961
|
+
throw new UserFacingError(
|
|
962
|
+
`DigitalOcean size "${size}" is not currently available for new Droplets.
|
|
963
|
+
Pick an available size instead: ${suggestSizes(catalog).join(", ")}.`
|
|
964
|
+
);
|
|
965
|
+
}
|
|
966
|
+
if (snapshot && typeof snapshot.min_disk_size === "number" && plan.disk < snapshot.min_disk_size) {
|
|
967
|
+
throw new UserFacingError(
|
|
968
|
+
`DigitalOcean size "${size}" has a ${String(plan.disk)} GB disk, but the base snapshot needs at least ${String(snapshot.min_disk_size)} GB.
|
|
969
|
+
Choose a larger size (bigger plans have bigger disks).`
|
|
970
|
+
);
|
|
971
|
+
}
|
|
972
|
+
if (plan.regions.length > 0 && !plan.regions.includes(region)) {
|
|
973
|
+
throw new UserFacingError(
|
|
974
|
+
`DigitalOcean size "${size}" is not offered in region "${region}".
|
|
975
|
+
It is available in: ${plan.regions.join(", ")}.
|
|
976
|
+
Pick one with \`--location <slug>\` or \`agentbox config set box.digitaloceanRegion <slug>\`.`
|
|
977
|
+
);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
function mapDigitalOceanProvisionError(err, choice) {
|
|
981
|
+
if (!(err instanceof DigitalOceanApiError)) return err;
|
|
982
|
+
const { size, region } = choice;
|
|
983
|
+
const msg = err.message.toLowerCase();
|
|
984
|
+
if (msg.includes("droplet limit") || msg.includes("exceeded your droplet limit")) {
|
|
985
|
+
return new UserFacingError(
|
|
986
|
+
`DigitalOcean refused to create the Droplet: your account Droplet limit was exceeded (${err.message}).
|
|
987
|
+
New accounts start with a low Droplet limit. Request an increase in the DigitalOcean Console (Account \u2192 your team \u2192 Droplet limit), then retry.`
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
if (msg.includes("not available") || msg.includes("capacity") || msg.includes("sold out")) {
|
|
991
|
+
return new UserFacingError(
|
|
992
|
+
`DigitalOcean has no capacity for "${size}" in "${region}" right now (${err.message}).
|
|
993
|
+
Retry, or pick another region with \`--location <slug>\` (e.g. \`nyc1\`, \`sfo3\`, \`ams3\`, \`fra1\`) or \`agentbox config set box.digitaloceanRegion <slug>\`.`
|
|
994
|
+
);
|
|
995
|
+
}
|
|
996
|
+
return err;
|
|
997
|
+
}
|
|
998
|
+
async function mintPrepareKey() {
|
|
999
|
+
const root = resolve4(homedirOrCwd(), ".agentbox", "digitalocean", `prepare-${Date.now().toString(36)}`);
|
|
1000
|
+
const key = await mintSshKey(root, `agentbox-prepare-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`);
|
|
1001
|
+
return {
|
|
1002
|
+
...key,
|
|
1003
|
+
cleanup: async () => {
|
|
1004
|
+
try {
|
|
1005
|
+
const { rm: rm3 } = await import("fs/promises");
|
|
1006
|
+
await rm3(dirname3(key.privatePath), { recursive: true, force: true });
|
|
1007
|
+
} catch {
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
function homedirOrCwd() {
|
|
1013
|
+
try {
|
|
1014
|
+
return process.env.HOME ?? process.cwd();
|
|
1015
|
+
} catch {
|
|
1016
|
+
return process.cwd();
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
function sshOptArgs(target) {
|
|
1020
|
+
const out = [
|
|
1021
|
+
"-i",
|
|
1022
|
+
target.identity,
|
|
1023
|
+
"-o",
|
|
1024
|
+
"StrictHostKeyChecking=accept-new",
|
|
1025
|
+
"-o",
|
|
1026
|
+
`UserKnownHostsFile=${target.knownHosts}`,
|
|
1027
|
+
"-o",
|
|
1028
|
+
"GlobalKnownHostsFile=/dev/null",
|
|
1029
|
+
"-o",
|
|
1030
|
+
"BatchMode=yes",
|
|
1031
|
+
"-o",
|
|
1032
|
+
"LogLevel=ERROR",
|
|
1033
|
+
// Detect a dead/stalled peer and drop the connection instead of hanging
|
|
1034
|
+
// forever. The per-box firewall is locked to the host's egress IP, so if
|
|
1035
|
+
// that IP flaps mid-command (roaming Wi-Fi, VPN toggle) the return traffic
|
|
1036
|
+
// is silently dropped and the ssh channel would otherwise block with no
|
|
1037
|
+
// EOF — seen as a `prepare`/`exec` that never returns. 15s * 4 = a ~60s
|
|
1038
|
+
// fail-fast so callers (retry wrappers, prepare cleanup) can react.
|
|
1039
|
+
"-o",
|
|
1040
|
+
"ServerAliveInterval=15",
|
|
1041
|
+
"-o",
|
|
1042
|
+
"ServerAliveCountMax=4"
|
|
1043
|
+
];
|
|
1044
|
+
if (target.controlPath) {
|
|
1045
|
+
out.push("-o", `ControlPath=${target.controlPath}`);
|
|
1046
|
+
}
|
|
1047
|
+
for (const [k, v2] of Object.entries(target.options ?? {})) {
|
|
1048
|
+
out.push("-o", `${k}=${v2}`);
|
|
1049
|
+
}
|
|
1050
|
+
return out;
|
|
1051
|
+
}
|
|
1052
|
+
async function sshExec(target, remoteCmd, opts = {}) {
|
|
1053
|
+
const argv = [
|
|
1054
|
+
...sshOptArgs(target),
|
|
1055
|
+
`${target.user}@${target.host}`,
|
|
1056
|
+
remoteCmd
|
|
1057
|
+
];
|
|
1058
|
+
const child = execa("ssh", argv, {
|
|
1059
|
+
reject: false,
|
|
1060
|
+
timeout: opts.timeoutMs,
|
|
1061
|
+
env: { ...process.env, ...opts.env },
|
|
1062
|
+
stdio: opts.onLine ? ["ignore", "pipe", "pipe"] : ["ignore", "pipe", "pipe"]
|
|
1063
|
+
});
|
|
1064
|
+
if (opts.onLine) {
|
|
1065
|
+
const handle = (chunk) => {
|
|
1066
|
+
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
1067
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1068
|
+
if (line.length > 0) opts.onLine?.(line);
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
child.stdout?.on("data", handle);
|
|
1072
|
+
child.stderr?.on("data", handle);
|
|
1073
|
+
}
|
|
1074
|
+
const res = await child;
|
|
1075
|
+
return {
|
|
1076
|
+
exitCode: typeof res.exitCode === "number" ? res.exitCode : 1,
|
|
1077
|
+
stdout: typeof res.stdout === "string" ? res.stdout : "",
|
|
1078
|
+
stderr: typeof res.stderr === "string" ? res.stderr : ""
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
async function scpUpload(target, localPath, remotePath, opts = {}) {
|
|
1082
|
+
const argv = [
|
|
1083
|
+
...sshOptArgs(target),
|
|
1084
|
+
localPath,
|
|
1085
|
+
`${target.user}@${target.host}:${remotePath}`
|
|
1086
|
+
];
|
|
1087
|
+
const res = await execa("scp", argv, {
|
|
1088
|
+
reject: false,
|
|
1089
|
+
timeout: opts.timeoutMs
|
|
1090
|
+
});
|
|
1091
|
+
if (res.exitCode !== 0) {
|
|
1092
|
+
throw new Error(
|
|
1093
|
+
`scp upload failed (exit ${String(res.exitCode)}): ${localPath} \u2192 ${remotePath}
|
|
1094
|
+
${res.stderr ?? ""}`
|
|
1095
|
+
);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
async function scpDownload(target, remotePath, localPath, opts = {}) {
|
|
1099
|
+
const argv = [
|
|
1100
|
+
...sshOptArgs(target),
|
|
1101
|
+
`${target.user}@${target.host}:${remotePath}`,
|
|
1102
|
+
localPath
|
|
1103
|
+
];
|
|
1104
|
+
const res = await execa("scp", argv, {
|
|
1105
|
+
reject: false,
|
|
1106
|
+
timeout: opts.timeoutMs
|
|
1107
|
+
});
|
|
1108
|
+
if (res.exitCode !== 0) {
|
|
1109
|
+
throw new Error(
|
|
1110
|
+
`scp download failed (exit ${String(res.exitCode)}): ${remotePath} \u2192 ${localPath}
|
|
1111
|
+
${res.stderr ?? ""}`
|
|
1112
|
+
);
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
async function waitForSsh(target, deadlineMs, intervalMs = 5e3) {
|
|
1116
|
+
const stop = Date.now() + deadlineMs;
|
|
1117
|
+
while (Date.now() < stop) {
|
|
1118
|
+
const res = await sshExec(
|
|
1119
|
+
{ ...target, options: { ...target.options, ConnectTimeout: "5" } },
|
|
1120
|
+
"true",
|
|
1121
|
+
{ timeoutMs: 1e4 }
|
|
1122
|
+
);
|
|
1123
|
+
if (res.exitCode === 0) return true;
|
|
1124
|
+
await new Promise((r) => setTimeout(r, intervalMs));
|
|
1125
|
+
}
|
|
1126
|
+
return false;
|
|
1127
|
+
}
|
|
1128
|
+
var TEMP_SIZE_DEFAULT = "s-2vcpu-4gb";
|
|
1129
|
+
var TEMP_REGION_DEFAULT = "nyc3";
|
|
1130
|
+
var STOCK_IMAGE_SLUG = "ubuntu-24-04-x64";
|
|
1131
|
+
var PREPARE_SSH_DEADLINE_MS = 5 * 6e4;
|
|
1132
|
+
var PROVISION_DROPLET_DEADLINE_MS = 5 * 6e4;
|
|
1133
|
+
var INSTALL_SCRIPT_TIMEOUT_MS = 30 * 6e4;
|
|
1134
|
+
var SNAPSHOT_DEADLINE_MS = 30 * 6e4;
|
|
1135
|
+
async function snapshotStillExists(client2, imageId) {
|
|
1136
|
+
try {
|
|
1137
|
+
const snaps = await client2.listSnapshots();
|
|
1138
|
+
return snaps.some((s) => s.id === String(imageId));
|
|
1139
|
+
} catch {
|
|
1140
|
+
return true;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
async function prepareDigitalOcean(opts = {}) {
|
|
1144
|
+
await ensureDigitalOceanCredentials();
|
|
1145
|
+
const client2 = makeDigitalOceanClient();
|
|
1146
|
+
const log = opts.onLog ?? (() => {
|
|
1147
|
+
});
|
|
1148
|
+
const progress = (step) => log(`prepare-digitalocean: ${step}`);
|
|
1149
|
+
const existingState = readPreparedState();
|
|
1150
|
+
const assets = resolveRuntimeAssets({
|
|
1151
|
+
cliRuntimeRoot: opts.cliRuntimeRoot ?? findStagedCliRuntimeRoot(),
|
|
1152
|
+
repoRoot: opts.repoRoot
|
|
1153
|
+
});
|
|
1154
|
+
const claudeInstall = opts.claudeInstall ?? "native";
|
|
1155
|
+
const contextSha = claudeInstallFingerprint(
|
|
1156
|
+
await computeContextSha256(assets.map((a) => ({ rel: a.name, abs: a.localPath }))),
|
|
1157
|
+
claudeInstall
|
|
1158
|
+
);
|
|
1159
|
+
if (!opts.force && existingState.base) {
|
|
1160
|
+
const remote = await snapshotStillExists(client2, existingState.base.imageId);
|
|
1161
|
+
if (remote && existingState.base.contextSha256 === contextSha) {
|
|
1162
|
+
progress(
|
|
1163
|
+
`base snapshot ${String(existingState.base.imageId)} already exists (fingerprint ${contextSha.slice(0, 12)} matches); skipping rebuild (pass --force to override)`
|
|
1164
|
+
);
|
|
1165
|
+
return {
|
|
1166
|
+
snapshotName: existingState.base.description,
|
|
1167
|
+
imageId: existingState.base.imageId
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
if (!remote) {
|
|
1171
|
+
progress(`recorded base snapshot ${String(existingState.base.imageId)} is gone on DigitalOcean; rebuilding`);
|
|
1172
|
+
} else {
|
|
1173
|
+
progress(
|
|
1174
|
+
`build context changed (was ${existingState.base.contextSha256?.slice(0, 12) ?? "<none>"}, now ${contextSha.slice(0, 12)}); rebuilding base snapshot`
|
|
1175
|
+
);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
progress("minting ephemeral ssh key");
|
|
1179
|
+
const key = await mintPrepareKey();
|
|
1180
|
+
let firewallId = null;
|
|
1181
|
+
let dropletId = null;
|
|
1182
|
+
const stamp = Date.now().toString(36);
|
|
1183
|
+
const prepareTag = `agentbox-prepare-${stamp}`;
|
|
1184
|
+
try {
|
|
1185
|
+
progress("detecting host egress IP");
|
|
1186
|
+
const source = opts.firewallSource ? normalizeSourceCidr(opts.firewallSource) : `${await detectEgressIp({ onLog: log })}/32`;
|
|
1187
|
+
const firewallName = `agentbox-prepare-${stamp}`;
|
|
1188
|
+
progress(`creating firewall ${firewallName} (source ${source})`);
|
|
1189
|
+
const firewall = await createPerBoxFirewall(client2, {
|
|
1190
|
+
name: firewallName,
|
|
1191
|
+
sources: [source],
|
|
1192
|
+
tag: prepareTag
|
|
1193
|
+
});
|
|
1194
|
+
firewallId = firewall.id;
|
|
1195
|
+
const dropletName = `agentbox-prepare-${stamp}`;
|
|
1196
|
+
const cloudInit = generatePrepareCloudInit({ sshPubkey: key.publicKey });
|
|
1197
|
+
const size = opts.size ?? TEMP_SIZE_DEFAULT;
|
|
1198
|
+
const region = opts.region ?? TEMP_REGION_DEFAULT;
|
|
1199
|
+
progress(`creating temp Droplet ${dropletName} (${size} / ${region})`);
|
|
1200
|
+
const created = await client2.createDroplet({
|
|
1201
|
+
name: dropletName,
|
|
1202
|
+
region,
|
|
1203
|
+
size,
|
|
1204
|
+
image: STOCK_IMAGE_SLUG,
|
|
1205
|
+
user_data: cloudInit,
|
|
1206
|
+
tags: [prepareTag, "agentbox", "agentbox-prepare"],
|
|
1207
|
+
ipv6: false
|
|
1208
|
+
});
|
|
1209
|
+
dropletId = created.droplet.id;
|
|
1210
|
+
progress(`droplet ${String(dropletId)} created; waiting for it to boot`);
|
|
1211
|
+
const droplet = await pollUntil(
|
|
1212
|
+
`droplet ${String(dropletId)} active`,
|
|
1213
|
+
async () => {
|
|
1214
|
+
const d = await client2.getDroplet(dropletId);
|
|
1215
|
+
const ip2 = d?.networks.v4.find((n) => n.type === "public")?.ip_address;
|
|
1216
|
+
return d && d.status === "active" && ip2 ? { d, ip: ip2 } : null;
|
|
1217
|
+
},
|
|
1218
|
+
{ deadlineMs: PROVISION_DROPLET_DEADLINE_MS, intervalMs: 3e3, maxIntervalMs: 1e4, onPoll: (l) => log(`prepare-digitalocean: ${l}`) }
|
|
1219
|
+
);
|
|
1220
|
+
const ip = droplet.ip;
|
|
1221
|
+
progress(`waiting for ssh on ${ip} (deadline ${String(PREPARE_SSH_DEADLINE_MS / 1e3)}s)`);
|
|
1222
|
+
const sshTarget = {
|
|
1223
|
+
host: ip,
|
|
1224
|
+
user: "root",
|
|
1225
|
+
identity: key.privatePath,
|
|
1226
|
+
knownHosts: join(key.dir, "known_hosts")
|
|
1227
|
+
};
|
|
1228
|
+
const up = await waitForSsh(sshTarget, PREPARE_SSH_DEADLINE_MS);
|
|
1229
|
+
if (!up) {
|
|
1230
|
+
throw new Error(`digitalocean: ssh on ${ip} did not come up within ${String(PREPARE_SSH_DEADLINE_MS / 1e3)}s`);
|
|
1231
|
+
}
|
|
1232
|
+
progress("ssh up \u2014 scp'ing runtime assets");
|
|
1233
|
+
for (const asset of assets) {
|
|
1234
|
+
const remote = `/tmp/${asset.remoteBasename}`;
|
|
1235
|
+
log(`prepare-digitalocean: scp ${asset.name} -> ${remote}`);
|
|
1236
|
+
await scpUpload(sshTarget, asset.localPath, remote);
|
|
1237
|
+
if (asset.remoteMode !== void 0) {
|
|
1238
|
+
const modeOctal = asset.remoteMode.toString(8);
|
|
1239
|
+
await sshExec(sshTarget, `chmod ${modeOctal} ${remote}`);
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
progress("running install-box.sh on temp Droplet (this takes ~5-15 min)");
|
|
1243
|
+
const installRes = await sshExec(
|
|
1244
|
+
sshTarget,
|
|
1245
|
+
`sudo mkdir -p /var/log/agentbox && set -o pipefail && AGENTBOX_CLAUDE_INSTALL=${claudeInstall} bash -x /tmp/agentbox-install.sh 2>&1 | sudo tee /var/log/agentbox/install.log`,
|
|
1246
|
+
{
|
|
1247
|
+
timeoutMs: INSTALL_SCRIPT_TIMEOUT_MS,
|
|
1248
|
+
onLine: (line) => log(`[install] ${line}`)
|
|
1249
|
+
}
|
|
1250
|
+
);
|
|
1251
|
+
if (installRes.exitCode !== 0) {
|
|
1252
|
+
throw new Error(
|
|
1253
|
+
`install-box.sh failed on temp Droplet (exit ${String(installRes.exitCode)})
|
|
1254
|
+
Last stderr: ${installRes.stderr.slice(-500) || "(empty)"}
|
|
1255
|
+
The full install trace was streamed to the prepare log above (the '[install] \u2026' lines; also in ~/.agentbox/logs/latest.log). No snapshot was created and the temp Droplet is being deleted, so the in-box /var/log/agentbox/install.log does not survive this failure.`
|
|
1256
|
+
);
|
|
1257
|
+
}
|
|
1258
|
+
progress("install script complete");
|
|
1259
|
+
progress("staging host agent static config");
|
|
1260
|
+
const stagings = [];
|
|
1261
|
+
try {
|
|
1262
|
+
const claudeTar = await stageClaudeStaticForUpload({ hostWorkspace: opts.hostWorkspace });
|
|
1263
|
+
for (const w of claudeTar.warnings) log(`prepare-digitalocean: ${w}`);
|
|
1264
|
+
if (claudeTar.tarballPath) stagings.push({ kind: "claude", tar: claudeTar, dest: "/home/vscode/.claude" });
|
|
1265
|
+
else await claudeTar.cleanup();
|
|
1266
|
+
const codexTar = await stageCodexStaticForUpload();
|
|
1267
|
+
for (const w of codexTar.warnings) log(`prepare-digitalocean: ${w}`);
|
|
1268
|
+
if (codexTar.tarballPath) stagings.push({ kind: "codex", tar: codexTar, dest: "/home/vscode/.codex" });
|
|
1269
|
+
else await codexTar.cleanup();
|
|
1270
|
+
const opencodeTar = await stageOpencodeStaticForUpload();
|
|
1271
|
+
for (const w of opencodeTar.warnings) log(`prepare-digitalocean: ${w}`);
|
|
1272
|
+
if (opencodeTar.tarballPath) stagings.push({ kind: "opencode", tar: opencodeTar, dest: "/home/vscode/.local/share/opencode" });
|
|
1273
|
+
else await opencodeTar.cleanup();
|
|
1274
|
+
const agentsTar = await stageAgentsStaticForUpload();
|
|
1275
|
+
for (const w of agentsTar.warnings) log(`prepare-digitalocean: ${w}`);
|
|
1276
|
+
if (agentsTar.tarballPath) stagings.push({ kind: "agents", tar: agentsTar, dest: "/home/vscode/.agents" });
|
|
1277
|
+
else await agentsTar.cleanup();
|
|
1278
|
+
for (const s of stagings) {
|
|
1279
|
+
const remote = `/tmp/agentbox-${s.kind}-static.tar.gz`;
|
|
1280
|
+
log(`prepare-digitalocean: scp ${s.kind} static (${s.tar.tarballPath}) -> ${remote}`);
|
|
1281
|
+
await scpUpload(sshTarget, s.tar.tarballPath, remote);
|
|
1282
|
+
const extractCmd = `sudo -u vscode mkdir -p ${s.dest} && sudo -u vscode tar -xzf ${remote} -C ${s.dest} --no-same-permissions --no-same-owner -m && rm -f ${remote}`;
|
|
1283
|
+
const r = await sshExec(sshTarget, extractCmd, { onLine: (line) => log(`[stage:${s.kind}] ${line}`) });
|
|
1284
|
+
if (r.exitCode !== 0) {
|
|
1285
|
+
throw new Error(
|
|
1286
|
+
`prepare-digitalocean: ${s.kind} static extract failed (exit ${String(r.exitCode)}): ${r.stderr.slice(-300)}`
|
|
1287
|
+
);
|
|
1288
|
+
}
|
|
1289
|
+
progress(`baked ${s.kind} static config into snapshot`);
|
|
1290
|
+
}
|
|
1291
|
+
} finally {
|
|
1292
|
+
for (const s of stagings) await s.tar.cleanup();
|
|
1293
|
+
}
|
|
1294
|
+
const description = opts.name ?? `agentbox-base-${stamp}`;
|
|
1295
|
+
progress(`creating snapshot '${description}' from droplet ${String(dropletId)}`);
|
|
1296
|
+
const action = await client2.snapshotDroplet(dropletId, description);
|
|
1297
|
+
progress(`snapshot action ${String(action.id)} requested; polling until complete`);
|
|
1298
|
+
await pollUntil(
|
|
1299
|
+
`snapshot action ${String(action.id)}`,
|
|
1300
|
+
async () => {
|
|
1301
|
+
const a = await client2.getAction(action.id);
|
|
1302
|
+
if (!a) return null;
|
|
1303
|
+
if (a.status === "errored") {
|
|
1304
|
+
throw new Error(`digitalocean: snapshot action ${String(action.id)} errored`);
|
|
1305
|
+
}
|
|
1306
|
+
return a.status === "completed" ? a : null;
|
|
1307
|
+
},
|
|
1308
|
+
{ deadlineMs: SNAPSHOT_DEADLINE_MS, intervalMs: 3e3, maxIntervalMs: 1e4, onPoll: (l) => log(`prepare-digitalocean: ${l}`) }
|
|
1309
|
+
);
|
|
1310
|
+
const snap = (await client2.listSnapshots()).find((s) => s.name === description);
|
|
1311
|
+
if (!snap) {
|
|
1312
|
+
throw new Error(`digitalocean: snapshot '${description}' completed but was not found in the snapshot list`);
|
|
1313
|
+
}
|
|
1314
|
+
const snapshotId = Number.parseInt(snap.id, 10);
|
|
1315
|
+
progress("persisting digitalocean-prepared.json");
|
|
1316
|
+
const state = readPreparedState();
|
|
1317
|
+
const cliStamp = readCliStamp();
|
|
1318
|
+
state.base = {
|
|
1319
|
+
imageId: snapshotId,
|
|
1320
|
+
description,
|
|
1321
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1322
|
+
contextSha256: contextSha,
|
|
1323
|
+
cliVersion: cliStamp.cliVersion,
|
|
1324
|
+
cliCommit: cliStamp.cliCommit
|
|
1325
|
+
};
|
|
1326
|
+
writePreparedState(state);
|
|
1327
|
+
log(`prepare-digitalocean: wrote ${preparedStatePath()}`);
|
|
1328
|
+
progress(`deleting temp Droplet ${String(dropletId)}`);
|
|
1329
|
+
await client2.deleteDroplet(dropletId);
|
|
1330
|
+
dropletId = null;
|
|
1331
|
+
progress(`deleting per-prepare firewall ${firewallId}`);
|
|
1332
|
+
await deletePerBoxFirewall(client2, firewallId, { tags: [prepareTag] });
|
|
1333
|
+
firewallId = null;
|
|
1334
|
+
progress(`prepare complete \u2014 base snapshot ${String(snapshotId)} (${description})`);
|
|
1335
|
+
return { snapshotName: description, imageId: snapshotId };
|
|
1336
|
+
} catch (err) {
|
|
1337
|
+
if (dropletId !== null) {
|
|
1338
|
+
log(`prepare-digitalocean: cleanup \u2014 deleting temp Droplet ${String(dropletId)} after failure`);
|
|
1339
|
+
try {
|
|
1340
|
+
await client2.deleteDroplet(dropletId);
|
|
1341
|
+
} catch (cleanupErr) {
|
|
1342
|
+
log(
|
|
1343
|
+
`prepare-digitalocean: WARN \u2014 failed to delete temp Droplet ${String(dropletId)}; check the DigitalOcean dashboard manually. ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`
|
|
1344
|
+
);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
if (firewallId !== null) {
|
|
1348
|
+
log(`prepare-digitalocean: cleanup \u2014 deleting per-prepare firewall ${firewallId} after failure`);
|
|
1349
|
+
try {
|
|
1350
|
+
await deletePerBoxFirewall(client2, firewallId, { tags: [prepareTag] });
|
|
1351
|
+
} catch (cleanupErr) {
|
|
1352
|
+
log(
|
|
1353
|
+
`prepare-digitalocean: WARN \u2014 failed to delete firewall ${firewallId}; check the DigitalOcean dashboard manually. ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`
|
|
1354
|
+
);
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
throw err;
|
|
1358
|
+
} finally {
|
|
1359
|
+
await key.cleanup();
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
var prepareDigitalOceanProvider = (req) => prepareDigitalOcean({
|
|
1363
|
+
name: req.name,
|
|
1364
|
+
hostWorkspace: req.hostWorkspace ?? process.cwd(),
|
|
1365
|
+
force: req.force,
|
|
1366
|
+
// Region for the temp bake Droplet (defaults to nyc3 when unset). Resolved
|
|
1367
|
+
// by the CLI from `--location` / `box.digitaloceanRegion`.
|
|
1368
|
+
region: req.location,
|
|
1369
|
+
// Droplet size for the temp bake VPS (CLI `--size` / `box.sizeDigitalocean`).
|
|
1370
|
+
size: req.size,
|
|
1371
|
+
// Forward the Claude install mode (native | npm) so the `npm` escape hatch
|
|
1372
|
+
// (box.claudeInstall / --claude-install npm) reaches the bake — the native
|
|
1373
|
+
// installer's CDN 403s some datacenter egress IPs. (matches Hetzner.)
|
|
1374
|
+
claudeInstall: req.claudeInstall,
|
|
1375
|
+
onLog: req.onLog
|
|
1376
|
+
});
|
|
1377
|
+
async function ensureDigitalOceanBaseSnapshot() {
|
|
1378
|
+
const state = readPreparedState();
|
|
1379
|
+
if (state.base !== void 0) return;
|
|
1380
|
+
throw new UserFacingError(
|
|
1381
|
+
"no DigitalOcean base snapshot found.\nRun `agentbox prepare --provider digitalocean` first (DigitalOcean cannot build images from a Dockerfile,\nso the base snapshot is a one-time prerequisite for cloud boxes on this backend)."
|
|
1382
|
+
);
|
|
1383
|
+
}
|
|
1384
|
+
var HOST = "127.0.0.1";
|
|
1385
|
+
var EPHEMERAL_MIN = 49152;
|
|
1386
|
+
var EPHEMERAL_MAX = 65535;
|
|
1387
|
+
var SshTunnelManager = class {
|
|
1388
|
+
boxes = /* @__PURE__ */ new Map();
|
|
1389
|
+
/**
|
|
1390
|
+
* Open the ControlMaster for `boxId`. Idempotent: if a master is already
|
|
1391
|
+
* up for this box (socket exists + responsive), no-op. Otherwise spawn a
|
|
1392
|
+
* fresh `ssh -fNT -M` and wait for the socket to appear.
|
|
1393
|
+
*/
|
|
1394
|
+
async open(opts) {
|
|
1395
|
+
const boxSshDir = opts.boxSshDir ?? defaultBoxSshDir(opts.boxId);
|
|
1396
|
+
await mkdir(boxSshDir, { recursive: true, mode: 448 });
|
|
1397
|
+
const controlPath = join2(boxSshDir, "control.sock");
|
|
1398
|
+
const knownHosts = join2(boxSshDir, "known_hosts");
|
|
1399
|
+
const user = opts.vpsUser ?? "vscode";
|
|
1400
|
+
const tunnel = {
|
|
1401
|
+
controlPath,
|
|
1402
|
+
vpsHost: opts.vpsHost,
|
|
1403
|
+
vpsUser: user,
|
|
1404
|
+
identity: opts.identity,
|
|
1405
|
+
boxSshDir,
|
|
1406
|
+
forwards: /* @__PURE__ */ new Map()
|
|
1407
|
+
};
|
|
1408
|
+
if (existsSync4(controlPath) && await this.isAlive(controlPath)) {
|
|
1409
|
+
this.boxes.set(opts.boxId, tunnel);
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
if (existsSync4(controlPath)) {
|
|
1413
|
+
await rm(controlPath, { force: true });
|
|
1414
|
+
}
|
|
1415
|
+
const connectTimeout = opts.connectTimeoutSeconds ?? 10;
|
|
1416
|
+
const argv = [
|
|
1417
|
+
"-fNT",
|
|
1418
|
+
"-M",
|
|
1419
|
+
"-S",
|
|
1420
|
+
controlPath,
|
|
1421
|
+
"-i",
|
|
1422
|
+
opts.identity,
|
|
1423
|
+
"-o",
|
|
1424
|
+
"StrictHostKeyChecking=accept-new",
|
|
1425
|
+
"-o",
|
|
1426
|
+
`UserKnownHostsFile=${knownHosts}`,
|
|
1427
|
+
"-o",
|
|
1428
|
+
"GlobalKnownHostsFile=/dev/null",
|
|
1429
|
+
"-o",
|
|
1430
|
+
"BatchMode=yes",
|
|
1431
|
+
"-o",
|
|
1432
|
+
"LogLevel=ERROR",
|
|
1433
|
+
"-o",
|
|
1434
|
+
"ExitOnForwardFailure=yes",
|
|
1435
|
+
"-o",
|
|
1436
|
+
"ServerAliveInterval=30",
|
|
1437
|
+
"-o",
|
|
1438
|
+
"ServerAliveCountMax=3",
|
|
1439
|
+
"-o",
|
|
1440
|
+
`ConnectTimeout=${String(connectTimeout)}`,
|
|
1441
|
+
`${user}@${opts.vpsHost}`
|
|
1442
|
+
];
|
|
1443
|
+
const res = await execa("ssh", argv, { reject: false });
|
|
1444
|
+
if (res.exitCode !== 0 || !existsSync4(controlPath)) {
|
|
1445
|
+
throw new Error(
|
|
1446
|
+
`ssh ControlMaster failed for ${opts.boxId} (exit ${String(res.exitCode)}): ${res.stderr || res.stdout || "(no output)"}`
|
|
1447
|
+
);
|
|
1448
|
+
}
|
|
1449
|
+
this.boxes.set(opts.boxId, tunnel);
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* Mint (or fetch the cached) `127.0.0.1:<localPort> → vps:127.0.0.1:<remotePort>`
|
|
1453
|
+
* forward. Returns the local port. Idempotent per (boxId, remotePort).
|
|
1454
|
+
*
|
|
1455
|
+
* The cached entry is only returned when the underlying ControlMaster is
|
|
1456
|
+
* still alive — without that check we'd happily hand back a localPort that
|
|
1457
|
+
* stopped listening when the master died (e.g. transient network blip,
|
|
1458
|
+
* host sleep/wake). When the master is dead we drop ALL cached forwards
|
|
1459
|
+
* for this box (they all share one tunnel) and re-mint from scratch.
|
|
1460
|
+
*/
|
|
1461
|
+
async forward(boxId, remotePort) {
|
|
1462
|
+
const tunnel = this.getTunnelOrThrow(boxId);
|
|
1463
|
+
const cached = tunnel.forwards.get(remotePort);
|
|
1464
|
+
if (cached !== void 0 && await this.isAlive(tunnel.controlPath)) {
|
|
1465
|
+
return cached;
|
|
1466
|
+
}
|
|
1467
|
+
if (cached !== void 0) {
|
|
1468
|
+
tunnel.forwards.clear();
|
|
1469
|
+
}
|
|
1470
|
+
const localPort = await pickFreePort();
|
|
1471
|
+
const argv = [
|
|
1472
|
+
"-O",
|
|
1473
|
+
"forward",
|
|
1474
|
+
"-L",
|
|
1475
|
+
`${HOST}:${String(localPort)}:${HOST}:${String(remotePort)}`,
|
|
1476
|
+
"-S",
|
|
1477
|
+
tunnel.controlPath,
|
|
1478
|
+
"dummy"
|
|
1479
|
+
// the target host is ignored when -O is used, but argv needs one
|
|
1480
|
+
];
|
|
1481
|
+
const res = await execa("ssh", argv, { reject: false });
|
|
1482
|
+
if (res.exitCode !== 0) {
|
|
1483
|
+
throw new Error(
|
|
1484
|
+
`ssh -O forward failed for ${boxId} (exit ${String(res.exitCode)}): ${res.stderr || res.stdout || "(no output)"}`
|
|
1485
|
+
);
|
|
1486
|
+
}
|
|
1487
|
+
tunnel.forwards.set(remotePort, localPort);
|
|
1488
|
+
return localPort;
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* Tear down a dead ControlMaster + every cached forward for this box,
|
|
1492
|
+
* then re-open from scratch. Idempotent — if the master is already alive
|
|
1493
|
+
* the master open() is a no-op, but the cached forwards still get
|
|
1494
|
+
* cleared so the next forward() call re-mints them. Returns when the
|
|
1495
|
+
* master is open and the box's forwards map is empty (ready for fresh
|
|
1496
|
+
* forward() calls).
|
|
1497
|
+
*
|
|
1498
|
+
* Use case: the cloud-poller observes ECONNREFUSED on the local port and
|
|
1499
|
+
* asks the backend to refresh the preview URL — that path calls into
|
|
1500
|
+
* here so the master + forward both come back fresh.
|
|
1501
|
+
*/
|
|
1502
|
+
async refresh(opts) {
|
|
1503
|
+
const existing = this.boxes.get(opts.boxId);
|
|
1504
|
+
if (existing) {
|
|
1505
|
+
const alive = await this.isAlive(existing.controlPath);
|
|
1506
|
+
if (!alive && existsSync4(existing.controlPath)) {
|
|
1507
|
+
try {
|
|
1508
|
+
await execa(
|
|
1509
|
+
"ssh",
|
|
1510
|
+
["-O", "exit", "-S", existing.controlPath, "dummy"],
|
|
1511
|
+
{ reject: false }
|
|
1512
|
+
);
|
|
1513
|
+
} catch {
|
|
1514
|
+
}
|
|
1515
|
+
await rm(existing.controlPath, { force: true });
|
|
1516
|
+
}
|
|
1517
|
+
existing.forwards.clear();
|
|
1518
|
+
}
|
|
1519
|
+
await this.open(opts);
|
|
1520
|
+
}
|
|
1521
|
+
/** Tear down a single forward. Idempotent — unknown ports are no-ops. */
|
|
1522
|
+
async unforward(boxId, remotePort) {
|
|
1523
|
+
const tunnel = this.getTunnelOrThrow(boxId);
|
|
1524
|
+
const localPort = tunnel.forwards.get(remotePort);
|
|
1525
|
+
if (localPort === void 0) return;
|
|
1526
|
+
const argv = [
|
|
1527
|
+
"-O",
|
|
1528
|
+
"cancel",
|
|
1529
|
+
"-L",
|
|
1530
|
+
`${HOST}:${String(localPort)}:${HOST}:${String(remotePort)}`,
|
|
1531
|
+
"-S",
|
|
1532
|
+
tunnel.controlPath,
|
|
1533
|
+
"dummy"
|
|
1534
|
+
];
|
|
1535
|
+
await execa("ssh", argv, { reject: false });
|
|
1536
|
+
tunnel.forwards.delete(remotePort);
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* Close the ControlMaster (and all its forwards). Idempotent — if no
|
|
1540
|
+
* master is recorded, no-op. Removes the socket file.
|
|
1541
|
+
*/
|
|
1542
|
+
async close(boxId) {
|
|
1543
|
+
const tunnel = this.boxes.get(boxId);
|
|
1544
|
+
if (!tunnel) return;
|
|
1545
|
+
if (existsSync4(tunnel.controlPath)) {
|
|
1546
|
+
await execa("ssh", ["-O", "exit", "-S", tunnel.controlPath, "dummy"], { reject: false });
|
|
1547
|
+
await rm(tunnel.controlPath, { force: true });
|
|
1548
|
+
}
|
|
1549
|
+
this.boxes.delete(boxId);
|
|
1550
|
+
}
|
|
1551
|
+
/** Tear down every open box. */
|
|
1552
|
+
async closeAll() {
|
|
1553
|
+
const ids = Array.from(this.boxes.keys());
|
|
1554
|
+
await Promise.all(ids.map((id) => this.close(id)));
|
|
1555
|
+
}
|
|
1556
|
+
/** Path to the ControlMaster socket for `boxId`, if open. */
|
|
1557
|
+
controlPath(boxId) {
|
|
1558
|
+
return this.boxes.get(boxId)?.controlPath;
|
|
1559
|
+
}
|
|
1560
|
+
/** True if a ControlMaster is registered for `boxId` (regardless of liveness). */
|
|
1561
|
+
has(boxId) {
|
|
1562
|
+
return this.boxes.has(boxId);
|
|
1563
|
+
}
|
|
1564
|
+
/** Per-box ssh dir (tests use this to verify the layout). */
|
|
1565
|
+
boxSshDir(boxId) {
|
|
1566
|
+
return this.boxes.get(boxId)?.boxSshDir;
|
|
1567
|
+
}
|
|
1568
|
+
/** Re-open the manager record for an existing-on-disk control socket. */
|
|
1569
|
+
registerExisting(boxId, opts) {
|
|
1570
|
+
const boxSshDir = opts.boxSshDir ?? defaultBoxSshDir(opts.boxId);
|
|
1571
|
+
this.boxes.set(boxId, {
|
|
1572
|
+
controlPath: join2(boxSshDir, "control.sock"),
|
|
1573
|
+
vpsHost: opts.vpsHost,
|
|
1574
|
+
vpsUser: opts.vpsUser ?? "vscode",
|
|
1575
|
+
identity: opts.identity,
|
|
1576
|
+
boxSshDir,
|
|
1577
|
+
forwards: /* @__PURE__ */ new Map()
|
|
1578
|
+
});
|
|
1579
|
+
}
|
|
1580
|
+
async isAlive(controlPath) {
|
|
1581
|
+
const res = await execa("ssh", ["-O", "check", "-S", controlPath, "dummy"], { reject: false });
|
|
1582
|
+
return res.exitCode === 0;
|
|
1583
|
+
}
|
|
1584
|
+
getTunnelOrThrow(boxId) {
|
|
1585
|
+
const t = this.boxes.get(boxId);
|
|
1586
|
+
if (!t) throw new Error(`no SSH ControlMaster registered for box ${boxId}; call open() first`);
|
|
1587
|
+
return t;
|
|
1588
|
+
}
|
|
1589
|
+
};
|
|
1590
|
+
function defaultBoxSshDir(boxId) {
|
|
1591
|
+
return resolve22(homedir3(), ".agentbox", "digitalocean", "boxes", boxId, "ssh");
|
|
1592
|
+
}
|
|
1593
|
+
async function pickFreePort() {
|
|
1594
|
+
return new Promise((resolveOk, reject) => {
|
|
1595
|
+
const srv = createServer();
|
|
1596
|
+
srv.unref();
|
|
1597
|
+
srv.on("error", reject);
|
|
1598
|
+
srv.listen(0, HOST, () => {
|
|
1599
|
+
const addr = srv.address();
|
|
1600
|
+
if (!addr || typeof addr === "string") {
|
|
1601
|
+
srv.close();
|
|
1602
|
+
reject(new Error("could not get a free local port"));
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
const port = addr.port;
|
|
1606
|
+
srv.close(() => {
|
|
1607
|
+
if (port < EPHEMERAL_MIN || port > EPHEMERAL_MAX) {
|
|
1608
|
+
resolveOk(port);
|
|
1609
|
+
} else {
|
|
1610
|
+
resolveOk(port);
|
|
1611
|
+
}
|
|
1612
|
+
});
|
|
1613
|
+
});
|
|
1614
|
+
});
|
|
1615
|
+
}
|
|
1616
|
+
var DIGITALOCEAN_DEFAULT_BOX_IMAGE_REF = "agentbox-base";
|
|
1617
|
+
var SCAFFOLDING_FALLBACK_IMAGE = "agentbox/box:dev";
|
|
1618
|
+
var VPS_USER = "vscode";
|
|
1619
|
+
var PROVISION_SSH_DEADLINE_MS = 10 * 6e4;
|
|
1620
|
+
var PROVISION_DROPLET_DEADLINE_MS2 = 5 * 6e4;
|
|
1621
|
+
var ACTION_DEADLINE_MS = 5 * 6e4;
|
|
1622
|
+
var SNAPSHOT_DEADLINE_MS2 = 30 * 6e4;
|
|
1623
|
+
var DIGITALOCEAN_DEFAULT_SIZE = "s-2vcpu-4gb";
|
|
1624
|
+
var DIGITALOCEAN_DEFAULT_REGION = "nyc3";
|
|
1625
|
+
var CLOUD_INIT_BOX_ENV_EXCLUDE = /* @__PURE__ */ new Set([
|
|
1626
|
+
"AGENTBOX_RELAY_URL",
|
|
1627
|
+
"AGENTBOX_RELAY_TOKEN",
|
|
1628
|
+
"AGENTBOX_BRIDGE_TOKEN"
|
|
1629
|
+
]);
|
|
1630
|
+
function cloudInitBoxEnv(env = {}) {
|
|
1631
|
+
const out = {};
|
|
1632
|
+
for (const [k, v2] of Object.entries(env)) {
|
|
1633
|
+
if (v2 !== void 0 && k.startsWith("AGENTBOX_") && !CLOUD_INIT_BOX_ENV_EXCLUDE.has(k)) {
|
|
1634
|
+
out[k] = v2;
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
return out;
|
|
1638
|
+
}
|
|
1639
|
+
var tunnels = new SshTunnelManager();
|
|
1640
|
+
function mapState(s) {
|
|
1641
|
+
switch (s) {
|
|
1642
|
+
case "active":
|
|
1643
|
+
case "new":
|
|
1644
|
+
return "running";
|
|
1645
|
+
case "off":
|
|
1646
|
+
case "archive":
|
|
1647
|
+
return "paused";
|
|
1648
|
+
default:
|
|
1649
|
+
return "missing";
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
function client() {
|
|
1653
|
+
return makeDigitalOceanClient();
|
|
1654
|
+
}
|
|
1655
|
+
function publicIpv4(droplet) {
|
|
1656
|
+
return droplet.networks.v4.find((n) => n.type === "public")?.ip_address;
|
|
1657
|
+
}
|
|
1658
|
+
async function getDropletStrict(id) {
|
|
1659
|
+
const d = await client().getDroplet(id);
|
|
1660
|
+
if (!d) {
|
|
1661
|
+
throw new Error(`digitalocean: droplet ${String(id)} not found (already destroyed?)`);
|
|
1662
|
+
}
|
|
1663
|
+
return d;
|
|
1664
|
+
}
|
|
1665
|
+
function sanitizeTag(name) {
|
|
1666
|
+
return name.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 200);
|
|
1667
|
+
}
|
|
1668
|
+
async function waitAction(c, actionId, label, deadlineMs) {
|
|
1669
|
+
await pollUntil(
|
|
1670
|
+
label,
|
|
1671
|
+
async () => {
|
|
1672
|
+
const a = await c.getAction(actionId);
|
|
1673
|
+
if (!a) return null;
|
|
1674
|
+
if (a.status === "errored") {
|
|
1675
|
+
throw new Error(`digitalocean: action ${String(actionId)} (${label}) errored`);
|
|
1676
|
+
}
|
|
1677
|
+
return a.status === "completed" ? a : null;
|
|
1678
|
+
},
|
|
1679
|
+
{ deadlineMs, intervalMs: 2e3, maxIntervalMs: 8e3 }
|
|
1680
|
+
);
|
|
1681
|
+
}
|
|
1682
|
+
async function resolveImageRef(c, req) {
|
|
1683
|
+
const ref = req.snapshot ?? req.image;
|
|
1684
|
+
if (!ref || ref === DIGITALOCEAN_DEFAULT_BOX_IMAGE_REF || ref === SCAFFOLDING_FALLBACK_IMAGE) {
|
|
1685
|
+
await ensureDigitalOceanBaseSnapshot();
|
|
1686
|
+
const state = readPreparedState();
|
|
1687
|
+
if (!state.base) {
|
|
1688
|
+
throw new Error(
|
|
1689
|
+
"no DigitalOcean base snapshot found \u2014 run `agentbox prepare --provider digitalocean` to bake one."
|
|
1690
|
+
);
|
|
1691
|
+
}
|
|
1692
|
+
return state.base.imageId;
|
|
1693
|
+
}
|
|
1694
|
+
if (/^\d+$/.test(ref)) {
|
|
1695
|
+
return Number.parseInt(ref, 10);
|
|
1696
|
+
}
|
|
1697
|
+
const snap = (await c.listSnapshots()).find((s) => s.name === ref);
|
|
1698
|
+
if (snap) return Number.parseInt(snap.id, 10);
|
|
1699
|
+
return ref;
|
|
1700
|
+
}
|
|
1701
|
+
function perBoxDir(sandboxId) {
|
|
1702
|
+
return resolvePath(defaultBoxSshDir(sandboxId), "..");
|
|
1703
|
+
}
|
|
1704
|
+
async function ensurePerBoxState(sandboxId) {
|
|
1705
|
+
const dir = perBoxDir(sandboxId);
|
|
1706
|
+
const sshDir = join3(dir, "ssh");
|
|
1707
|
+
await mkdir2(sshDir, { recursive: true, mode: 448 });
|
|
1708
|
+
return {
|
|
1709
|
+
dir,
|
|
1710
|
+
identity: join3(sshDir, "id_ed25519"),
|
|
1711
|
+
knownHosts: join3(sshDir, "known_hosts")
|
|
1712
|
+
};
|
|
1713
|
+
}
|
|
1714
|
+
function bashScript(s) {
|
|
1715
|
+
return `bash -lc ${shellQuote(s)}`;
|
|
1716
|
+
}
|
|
1717
|
+
function shellQuote(s) {
|
|
1718
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
1719
|
+
}
|
|
1720
|
+
function buildSshTarget(state, vpsIp, controlPath) {
|
|
1721
|
+
return {
|
|
1722
|
+
host: vpsIp,
|
|
1723
|
+
user: VPS_USER,
|
|
1724
|
+
identity: state.identity,
|
|
1725
|
+
knownHosts: state.knownHosts,
|
|
1726
|
+
controlPath
|
|
1727
|
+
};
|
|
1728
|
+
}
|
|
1729
|
+
async function ensureTunnel(sandboxId, state, vpsIp) {
|
|
1730
|
+
if (tunnels.has(sandboxId)) return;
|
|
1731
|
+
await tunnels.open({
|
|
1732
|
+
boxId: sandboxId,
|
|
1733
|
+
vpsHost: vpsIp,
|
|
1734
|
+
identity: state.identity
|
|
1735
|
+
});
|
|
1736
|
+
}
|
|
1737
|
+
async function ensureLiveTarget(sandboxId) {
|
|
1738
|
+
const id = Number.parseInt(sandboxId, 10);
|
|
1739
|
+
if (!Number.isFinite(id)) {
|
|
1740
|
+
throw new Error(`digitalocean: invalid sandboxId ${sandboxId}`);
|
|
1741
|
+
}
|
|
1742
|
+
const droplet = await getDropletStrict(id);
|
|
1743
|
+
const vpsIp = publicIpv4(droplet);
|
|
1744
|
+
if (!vpsIp) {
|
|
1745
|
+
throw new Error(`digitalocean: droplet ${String(id)} has no public IPv4 address`);
|
|
1746
|
+
}
|
|
1747
|
+
const state = await ensurePerBoxState(sandboxId);
|
|
1748
|
+
if (!existsSync22(state.identity)) {
|
|
1749
|
+
throw new Error(
|
|
1750
|
+
`digitalocean: per-box SSH key missing for sandbox ${sandboxId} (expected at ${state.identity}). If this box was created by a different host, you'll need to re-create it on this host.`
|
|
1751
|
+
);
|
|
1752
|
+
}
|
|
1753
|
+
await ensureTunnel(sandboxId, state, vpsIp);
|
|
1754
|
+
const controlPath = tunnels.controlPath(sandboxId);
|
|
1755
|
+
return { target: buildSshTarget(state, vpsIp, controlPath), state, vpsIp };
|
|
1756
|
+
}
|
|
1757
|
+
var digitaloceanBackend = {
|
|
1758
|
+
name: "digitalocean",
|
|
1759
|
+
async provision(req) {
|
|
1760
|
+
const c = client();
|
|
1761
|
+
const onLog = req.onLog ?? (() => {
|
|
1762
|
+
});
|
|
1763
|
+
const progress = (s) => onLog(`digitalocean: ${s}`);
|
|
1764
|
+
await ensureDigitalOceanBaseSnapshot();
|
|
1765
|
+
const imageRef = await resolveImageRef(c, req);
|
|
1766
|
+
const size = req.size && req.size.trim() || DIGITALOCEAN_DEFAULT_SIZE;
|
|
1767
|
+
const region = req.location && req.location.trim() || req.env?.AGENTBOX_DIGITALOCEAN_REGION || process.env.AGENTBOX_DIGITALOCEAN_REGION || DIGITALOCEAN_DEFAULT_REGION;
|
|
1768
|
+
const choice = { size, region };
|
|
1769
|
+
const snapshotMeta = typeof imageRef === "number" ? await c.getSnapshot(String(imageRef)) : null;
|
|
1770
|
+
const sizeCatalog = await c.listSizes();
|
|
1771
|
+
validateSizeChoice(choice, sizeCatalog, snapshotMeta);
|
|
1772
|
+
const plan = sizeCatalog.find((s) => s.slug === size);
|
|
1773
|
+
const inboundPolicy = parseInboundSpec(req.inbound);
|
|
1774
|
+
const egressOverride = req.env?.AGENTBOX_DIGITALOCEAN_FIREWALL_SOURCE ?? process.env.AGENTBOX_DIGITALOCEAN_FIREWALL_SOURCE;
|
|
1775
|
+
const hostEgress = inboundPolicy.mode === "open" ? null : egressOverride ? normalizeSourceCidr(egressOverride) : `${await detectEgressIp({ onLog })}/32`;
|
|
1776
|
+
const sources = resolveInboundSources(inboundPolicy, hostEgress);
|
|
1777
|
+
progress(`firewall inbound: ${describeInbound(inboundPolicy)} -> ${sources.join(", ")}`);
|
|
1778
|
+
const stamp = Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8);
|
|
1779
|
+
const tempDir = resolvePath(
|
|
1780
|
+
process.env.HOME ?? process.cwd(),
|
|
1781
|
+
".agentbox",
|
|
1782
|
+
"digitalocean",
|
|
1783
|
+
`pending-${stamp}`,
|
|
1784
|
+
"ssh"
|
|
1785
|
+
);
|
|
1786
|
+
const key = await mintSshKey(tempDir, `agentbox-box-${req.name}-${stamp}`);
|
|
1787
|
+
const boxTag = `agentbox-${sanitizeTag(req.name)}-${stamp}`;
|
|
1788
|
+
let firewallId = null;
|
|
1789
|
+
let dropletId = null;
|
|
1790
|
+
try {
|
|
1791
|
+
const firewall = await createPerBoxFirewall(c, {
|
|
1792
|
+
name: `agentbox-${sanitizeTag(req.name)}-${stamp}`,
|
|
1793
|
+
sources,
|
|
1794
|
+
tag: boxTag
|
|
1795
|
+
});
|
|
1796
|
+
firewallId = firewall.id;
|
|
1797
|
+
const boxEnv = cloudInitBoxEnv(req.env);
|
|
1798
|
+
const cloudInit = generateBoxCloudInit({
|
|
1799
|
+
sshPubkey: key.publicKey,
|
|
1800
|
+
boxName: req.name,
|
|
1801
|
+
boxEnv: Object.keys(boxEnv).length > 0 ? boxEnv : void 0
|
|
1802
|
+
});
|
|
1803
|
+
progress(`creating droplet '${req.name}' from image ${String(imageRef)} (${size} / ${region})`);
|
|
1804
|
+
let created;
|
|
1805
|
+
try {
|
|
1806
|
+
created = await withDigitalOceanRetry(
|
|
1807
|
+
{ method: "createDroplet", retryOnAmbiguous: false, attemptTimeoutMs: 12e4 },
|
|
1808
|
+
() => c.createDroplet({
|
|
1809
|
+
name: `agentbox-${sanitizeTag(req.name)}-${stamp}`,
|
|
1810
|
+
region,
|
|
1811
|
+
size,
|
|
1812
|
+
image: imageRef,
|
|
1813
|
+
user_data: cloudInit,
|
|
1814
|
+
tags: [boxTag, "agentbox"],
|
|
1815
|
+
ipv6: false
|
|
1816
|
+
})
|
|
1817
|
+
);
|
|
1818
|
+
} catch (createErr) {
|
|
1819
|
+
throw mapDigitalOceanProvisionError(createErr, choice);
|
|
1820
|
+
}
|
|
1821
|
+
dropletId = created.droplet.id;
|
|
1822
|
+
progress(`droplet ${String(dropletId)} created; waiting for it to boot`);
|
|
1823
|
+
const droplet = await pollUntil(
|
|
1824
|
+
`droplet ${String(dropletId)} active`,
|
|
1825
|
+
async () => {
|
|
1826
|
+
const d = await c.getDroplet(dropletId);
|
|
1827
|
+
return d && d.status === "active" && publicIpv4(d) ? d : null;
|
|
1828
|
+
},
|
|
1829
|
+
{ deadlineMs: PROVISION_DROPLET_DEADLINE_MS2, intervalMs: 3e3, maxIntervalMs: 1e4 }
|
|
1830
|
+
);
|
|
1831
|
+
const vpsIp = publicIpv4(droplet);
|
|
1832
|
+
if (!vpsIp) {
|
|
1833
|
+
throw new Error(`digitalocean: droplet ${String(dropletId)} came up without a public IPv4`);
|
|
1834
|
+
}
|
|
1835
|
+
progress(`droplet ${String(dropletId)} at ${vpsIp}; waiting for ssh`);
|
|
1836
|
+
const sandboxId = String(dropletId);
|
|
1837
|
+
const state = await ensurePerBoxState(sandboxId);
|
|
1838
|
+
await rename(key.privatePath, state.identity);
|
|
1839
|
+
await rename(key.publicPath, `${state.identity}.pub`);
|
|
1840
|
+
await rm2(key.dir, { recursive: true, force: true });
|
|
1841
|
+
const pendingParent = resolvePath(key.dir, "..");
|
|
1842
|
+
await rm2(pendingParent, { recursive: true, force: true });
|
|
1843
|
+
const up = await waitForSsh(buildSshTarget(state, vpsIp), PROVISION_SSH_DEADLINE_MS);
|
|
1844
|
+
if (!up) {
|
|
1845
|
+
throw new Error(
|
|
1846
|
+
`digitalocean: ssh on ${vpsIp} did not come up within ${String(PROVISION_SSH_DEADLINE_MS / 1e3)}s; the droplet has been deleted. This is usually transient \u2014 just retry the create. If it keeps failing, check that your host's egress IP is stable (the box firewall is locked to it, so a mid-provision IP change blocks ssh).`
|
|
1847
|
+
);
|
|
1848
|
+
}
|
|
1849
|
+
await ensureTunnel(sandboxId, state, vpsIp);
|
|
1850
|
+
progress("ssh up; ControlMaster open");
|
|
1851
|
+
return plan ? {
|
|
1852
|
+
sandboxId,
|
|
1853
|
+
inbound: inboundPolicy,
|
|
1854
|
+
resources: {
|
|
1855
|
+
cpu: plan.vcpus,
|
|
1856
|
+
memory: Math.round(plan.memory / 1024),
|
|
1857
|
+
disk: plan.disk
|
|
1858
|
+
}
|
|
1859
|
+
} : { sandboxId, inbound: inboundPolicy };
|
|
1860
|
+
} catch (err) {
|
|
1861
|
+
if (dropletId !== null) {
|
|
1862
|
+
progress(`cleanup \u2014 deleting droplet ${String(dropletId)} after provision failure`);
|
|
1863
|
+
try {
|
|
1864
|
+
await c.deleteDroplet(dropletId);
|
|
1865
|
+
} catch (cleanupErr) {
|
|
1866
|
+
onLog(
|
|
1867
|
+
`digitalocean: WARN \u2014 failed to delete droplet ${String(dropletId)}; check the DigitalOcean dashboard. ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`
|
|
1868
|
+
);
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
if (firewallId !== null) {
|
|
1872
|
+
try {
|
|
1873
|
+
await deletePerBoxFirewall(c, firewallId, { tags: [boxTag] });
|
|
1874
|
+
} catch {
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
try {
|
|
1878
|
+
if (existsSync22(key.dir)) await rm2(key.dir, { recursive: true, force: true });
|
|
1879
|
+
if (dropletId !== null) {
|
|
1880
|
+
const finalDir = perBoxDir(String(dropletId));
|
|
1881
|
+
if (existsSync22(finalDir)) await rm2(finalDir, { recursive: true, force: true });
|
|
1882
|
+
}
|
|
1883
|
+
} catch {
|
|
1884
|
+
}
|
|
1885
|
+
throw err;
|
|
1886
|
+
}
|
|
1887
|
+
},
|
|
1888
|
+
async get(sandboxId) {
|
|
1889
|
+
const id = Number.parseInt(sandboxId, 10);
|
|
1890
|
+
if (!Number.isFinite(id)) return null;
|
|
1891
|
+
const droplet = await client().getDroplet(id);
|
|
1892
|
+
return droplet ? { sandboxId } : null;
|
|
1893
|
+
},
|
|
1894
|
+
async list() {
|
|
1895
|
+
const droplets = await client().listDroplets({ tag_name: "agentbox" });
|
|
1896
|
+
return droplets.map((d) => ({
|
|
1897
|
+
sandboxId: String(d.id),
|
|
1898
|
+
name: d.name,
|
|
1899
|
+
createdAt: d.created_at,
|
|
1900
|
+
state: mapState(d.status)
|
|
1901
|
+
}));
|
|
1902
|
+
},
|
|
1903
|
+
async start(h) {
|
|
1904
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1905
|
+
const c = client();
|
|
1906
|
+
const action = await c.powerOn(id);
|
|
1907
|
+
await waitAction(c, action.id, `droplet ${h.sandboxId} power_on`, ACTION_DEADLINE_MS);
|
|
1908
|
+
const droplet = await pollUntil(
|
|
1909
|
+
`droplet ${h.sandboxId} active`,
|
|
1910
|
+
async () => {
|
|
1911
|
+
const d = await c.getDroplet(id);
|
|
1912
|
+
return d && d.status === "active" && publicIpv4(d) ? d : null;
|
|
1913
|
+
},
|
|
1914
|
+
{ deadlineMs: ACTION_DEADLINE_MS, intervalMs: 2e3, maxIntervalMs: 8e3 }
|
|
1915
|
+
);
|
|
1916
|
+
const vpsIp = publicIpv4(droplet);
|
|
1917
|
+
if (!vpsIp) {
|
|
1918
|
+
throw new Error(`digitalocean: droplet ${h.sandboxId} has no public IPv4 after start`);
|
|
1919
|
+
}
|
|
1920
|
+
const state = await ensurePerBoxState(h.sandboxId);
|
|
1921
|
+
const up = await waitForSsh(buildSshTarget(state, vpsIp), PROVISION_SSH_DEADLINE_MS);
|
|
1922
|
+
if (!up) {
|
|
1923
|
+
throw new Error(
|
|
1924
|
+
`digitalocean: ssh on ${vpsIp} did not come up within ${String(PROVISION_SSH_DEADLINE_MS / 1e3)}s after start. This is usually transient \u2014 retry (\`agentbox start\` / \`agentbox recover\`). If it persists, check that your host's egress IP is stable (the box firewall is locked to it, so an IP change blocks ssh).`
|
|
1925
|
+
);
|
|
1926
|
+
}
|
|
1927
|
+
},
|
|
1928
|
+
async stop(h) {
|
|
1929
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1930
|
+
const c = client();
|
|
1931
|
+
try {
|
|
1932
|
+
const action = await c.shutdown(id);
|
|
1933
|
+
await waitAction(c, action.id, `droplet ${h.sandboxId} shutdown`, 9e4);
|
|
1934
|
+
} catch {
|
|
1935
|
+
const action = await c.powerOff(id);
|
|
1936
|
+
await waitAction(c, action.id, `droplet ${h.sandboxId} power_off`, ACTION_DEADLINE_MS);
|
|
1937
|
+
}
|
|
1938
|
+
await tunnels.close(h.sandboxId);
|
|
1939
|
+
},
|
|
1940
|
+
async pause(h) {
|
|
1941
|
+
await this.stop(h);
|
|
1942
|
+
},
|
|
1943
|
+
async resume(h) {
|
|
1944
|
+
await this.start(h);
|
|
1945
|
+
},
|
|
1946
|
+
async setInbound(h, policy) {
|
|
1947
|
+
const c = client();
|
|
1948
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1949
|
+
const droplet = await getDropletStrict(id);
|
|
1950
|
+
const fw = await findFirewallForDroplet(c, id, droplet.tags ?? []);
|
|
1951
|
+
if (!fw) {
|
|
1952
|
+
throw new Error(`digitalocean: no per-box firewall found for droplet ${h.sandboxId}`);
|
|
1953
|
+
}
|
|
1954
|
+
const hostEgress = policy.mode === "open" ? null : `${await detectEgressIp({})}/32`;
|
|
1955
|
+
const sources = resolveInboundSources(policy, hostEgress);
|
|
1956
|
+
await syncFirewallSource(c, fw, sources);
|
|
1957
|
+
return { sources };
|
|
1958
|
+
},
|
|
1959
|
+
async repairReachability(h) {
|
|
1960
|
+
const c = client();
|
|
1961
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1962
|
+
const droplet = await c.getDroplet(id).catch(() => null);
|
|
1963
|
+
if (!droplet) return { changed: false };
|
|
1964
|
+
const policy = h.inbound ?? { mode: "locked", sources: [] };
|
|
1965
|
+
if (policy.mode === "open") return { changed: false };
|
|
1966
|
+
const fw = await findFirewallForDroplet(c, id, droplet.tags ?? []).catch(() => null);
|
|
1967
|
+
if (!fw) return { changed: false };
|
|
1968
|
+
const allowed = fw.inbound_rules.find((r) => r.ports === "22")?.sources.addresses ?? [];
|
|
1969
|
+
if (allowed.includes("0.0.0.0/0")) return { changed: false };
|
|
1970
|
+
const currentEgress = `${await detectEgressIp({})}/32`;
|
|
1971
|
+
if (allowed.includes(currentEgress)) return { changed: false };
|
|
1972
|
+
const sources = resolveInboundSources(policy, currentEgress);
|
|
1973
|
+
await syncFirewallSource(c, fw, sources);
|
|
1974
|
+
return {
|
|
1975
|
+
changed: true,
|
|
1976
|
+
detail: `firewall updated: SSH now allowed from ${sources.join(", ")} (was ${allowed.join(", ") || "(no rule)"})`
|
|
1977
|
+
};
|
|
1978
|
+
},
|
|
1979
|
+
async destroy(h) {
|
|
1980
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1981
|
+
await tunnels.close(h.sandboxId);
|
|
1982
|
+
const c = client();
|
|
1983
|
+
let firewallId;
|
|
1984
|
+
let firewallTags;
|
|
1985
|
+
try {
|
|
1986
|
+
const droplet = await c.getDroplet(id);
|
|
1987
|
+
if (droplet) {
|
|
1988
|
+
const fw = await findFirewallForDroplet(c, id, droplet.tags);
|
|
1989
|
+
firewallId = fw?.id;
|
|
1990
|
+
firewallTags = fw?.tags;
|
|
1991
|
+
}
|
|
1992
|
+
} catch {
|
|
1993
|
+
}
|
|
1994
|
+
try {
|
|
1995
|
+
await c.deleteDroplet(id);
|
|
1996
|
+
} catch (err) {
|
|
1997
|
+
if (!(err instanceof DigitalOceanApiError && (err.statusCode === 404 || err.code === "not_found"))) {
|
|
1998
|
+
throw err;
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
if (firewallId) {
|
|
2002
|
+
await deletePerBoxFirewall(c, firewallId, { tags: firewallTags });
|
|
2003
|
+
}
|
|
2004
|
+
const dir = perBoxDir(h.sandboxId);
|
|
2005
|
+
try {
|
|
2006
|
+
await rm2(dir, { recursive: true, force: true });
|
|
2007
|
+
} catch {
|
|
2008
|
+
}
|
|
2009
|
+
},
|
|
2010
|
+
async state(h) {
|
|
2011
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
2012
|
+
const d = await client().getDroplet(id);
|
|
2013
|
+
return d ? mapState(d.status) : "missing";
|
|
2014
|
+
},
|
|
2015
|
+
async exec(h, cmd, opts) {
|
|
2016
|
+
const { target } = await ensureLiveTarget(h.sandboxId);
|
|
2017
|
+
const argv = [
|
|
2018
|
+
...sshOptArgs(target),
|
|
2019
|
+
`${target.user}@${target.host}`,
|
|
2020
|
+
bashScript(opts?.cwd ? `cd ${shellQuote(opts.cwd)} && ${cmd}` : cmd)
|
|
2021
|
+
];
|
|
2022
|
+
const res = await execa("ssh", argv, {
|
|
2023
|
+
reject: false,
|
|
2024
|
+
timeout: opts?.attemptTimeoutMs ?? 12e4,
|
|
2025
|
+
env: { ...process.env, ...opts?.env ?? {} }
|
|
2026
|
+
});
|
|
2027
|
+
return {
|
|
2028
|
+
exitCode: typeof res.exitCode === "number" ? res.exitCode : 1,
|
|
2029
|
+
stdout: typeof res.stdout === "string" ? res.stdout : "",
|
|
2030
|
+
stderr: typeof res.stderr === "string" ? res.stderr : ""
|
|
2031
|
+
};
|
|
2032
|
+
},
|
|
2033
|
+
async uploadFile(h, localPath, remotePath) {
|
|
2034
|
+
const { target } = await ensureLiveTarget(h.sandboxId);
|
|
2035
|
+
const argv = [...sshOptArgs(target), localPath, `${target.user}@${target.host}:${remotePath}`];
|
|
2036
|
+
const res = await execa("scp", argv, { reject: false, timeout: 3e5 });
|
|
2037
|
+
if (res.exitCode !== 0) {
|
|
2038
|
+
throw new Error(`digitalocean: scp upload failed (exit ${String(res.exitCode)}): ${res.stderr || ""}`);
|
|
2039
|
+
}
|
|
2040
|
+
},
|
|
2041
|
+
async downloadFile(h, remotePath, localPath) {
|
|
2042
|
+
const { target } = await ensureLiveTarget(h.sandboxId);
|
|
2043
|
+
const argv = [...sshOptArgs(target), `${target.user}@${target.host}:${remotePath}`, localPath];
|
|
2044
|
+
const res = await execa("scp", argv, { reject: false, timeout: 3e5 });
|
|
2045
|
+
if (res.exitCode !== 0) {
|
|
2046
|
+
throw new Error(`digitalocean: scp download failed (exit ${String(res.exitCode)}): ${res.stderr || ""}`);
|
|
2047
|
+
}
|
|
2048
|
+
},
|
|
2049
|
+
async listFiles(h, remoteDir) {
|
|
2050
|
+
const res = await this.exec(
|
|
2051
|
+
h,
|
|
2052
|
+
`find ${shellQuote(remoteDir)} -mindepth 1 -maxdepth 1 -printf '%f\\t%y\\n'`
|
|
2053
|
+
);
|
|
2054
|
+
if (res.exitCode !== 0) return [];
|
|
2055
|
+
return res.stdout.split(/\r?\n/).filter((line) => line.length > 0).map((line) => {
|
|
2056
|
+
const [name, kind] = line.split(" ");
|
|
2057
|
+
return { name: name ?? line, isDir: kind === "d" };
|
|
2058
|
+
});
|
|
2059
|
+
},
|
|
2060
|
+
async previewUrl(h, port) {
|
|
2061
|
+
await ensureLiveTarget(h.sandboxId);
|
|
2062
|
+
const localPort = await tunnels.forward(h.sandboxId, port);
|
|
2063
|
+
return { url: `http://127.0.0.1:${String(localPort)}` };
|
|
2064
|
+
},
|
|
2065
|
+
async signedPreviewUrl(h, port, _ttl) {
|
|
2066
|
+
void _ttl;
|
|
2067
|
+
return this.previewUrl(h, port);
|
|
2068
|
+
},
|
|
2069
|
+
async refreshPreviewUrl(h, port) {
|
|
2070
|
+
const { state, vpsIp } = await ensureLiveTarget(h.sandboxId);
|
|
2071
|
+
await tunnels.refresh({
|
|
2072
|
+
boxId: h.sandboxId,
|
|
2073
|
+
vpsHost: vpsIp,
|
|
2074
|
+
identity: state.identity
|
|
2075
|
+
});
|
|
2076
|
+
const localPort = await tunnels.forward(h.sandboxId, port);
|
|
2077
|
+
return { url: `http://127.0.0.1:${String(localPort)}` };
|
|
2078
|
+
},
|
|
2079
|
+
async startInBoxPortless(h, opts) {
|
|
2080
|
+
const tlsFlag = opts.tls ? "" : "--no-tls";
|
|
2081
|
+
const startCmd = `sudo portless proxy start ${tlsFlag} -p ${String(opts.proxyPort)}`.replace(/\s+/g, " ");
|
|
2082
|
+
const aliasCmd = `sudo portless alias ${shellQuote(opts.boxName)} ${String(opts.webPort)}`;
|
|
2083
|
+
const cmds = [startCmd, aliasCmd];
|
|
2084
|
+
if (opts.tls) {
|
|
2085
|
+
cmds.push(
|
|
2086
|
+
"sudo agentbox-portless-trust /root/.portless/ca.pem >/dev/null 2>&1 || true",
|
|
2087
|
+
`echo 'export NODE_EXTRA_CA_CERTS=/usr/local/share/ca-certificates/agentbox-portless-ca.crt' | sudo tee /etc/profile.d/agentbox-portless-ca.sh >/dev/null || true`
|
|
2088
|
+
);
|
|
2089
|
+
}
|
|
2090
|
+
await this.exec(h, cmds.join("; "));
|
|
2091
|
+
},
|
|
2092
|
+
async attachArgv(h) {
|
|
2093
|
+
const { target } = await ensureLiveTarget(h.sandboxId);
|
|
2094
|
+
return ["ssh", ...sshOptArgs(target), `${target.user}@${target.host}`];
|
|
2095
|
+
},
|
|
2096
|
+
async createSnapshot(h, name) {
|
|
2097
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
2098
|
+
const c = client();
|
|
2099
|
+
const action = await withDigitalOceanRetry(
|
|
2100
|
+
{ method: "snapshotDroplet", retryOnAmbiguous: false, attemptTimeoutMs: 12e4 },
|
|
2101
|
+
() => c.snapshotDroplet(id, name)
|
|
2102
|
+
);
|
|
2103
|
+
await waitAction(c, action.id, `droplet ${h.sandboxId} snapshot`, SNAPSHOT_DEADLINE_MS2);
|
|
2104
|
+
},
|
|
2105
|
+
async deleteSnapshot(name) {
|
|
2106
|
+
const c = client();
|
|
2107
|
+
const snap = (await c.listSnapshots()).find((s) => s.name === name);
|
|
2108
|
+
if (!snap) return;
|
|
2109
|
+
try {
|
|
2110
|
+
await c.deleteSnapshot(snap.id);
|
|
2111
|
+
} catch (err) {
|
|
2112
|
+
if (err instanceof DigitalOceanApiError && (err.statusCode === 404 || err.code === "not_found")) return;
|
|
2113
|
+
throw err;
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
};
|
|
2117
|
+
function readCredStatusSummary() {
|
|
2118
|
+
return { configured: readDigitalOceanCredStatus().source !== "none" };
|
|
2119
|
+
}
|
|
2120
|
+
async function doctorChecks() {
|
|
2121
|
+
try {
|
|
2122
|
+
const cred = readDigitalOceanCredStatus();
|
|
2123
|
+
const credRes = cred.source === "none" ? {
|
|
2124
|
+
label: "credentials",
|
|
2125
|
+
status: "warn",
|
|
2126
|
+
detail: "DIGITALOCEAN_TOKEN not set",
|
|
2127
|
+
hint: "`agentbox digitalocean login`"
|
|
2128
|
+
} : { label: "credentials", status: "ok", detail: `token from ${cred.source}` };
|
|
2129
|
+
const prepared = readPreparedState();
|
|
2130
|
+
const snapRes = prepared.base?.imageId ? {
|
|
2131
|
+
label: "base snapshot",
|
|
2132
|
+
status: "ok",
|
|
2133
|
+
detail: `snapshot ${String(prepared.base.imageId)} (${prepared.base.cliVersion ?? "\u2014"})`
|
|
2134
|
+
} : {
|
|
2135
|
+
label: "base snapshot",
|
|
2136
|
+
status: "warn",
|
|
2137
|
+
detail: "not baked",
|
|
2138
|
+
hint: "`agentbox prepare --provider digitalocean`"
|
|
2139
|
+
};
|
|
2140
|
+
const portlessRes = portlessDoctorRow(await detectPortless());
|
|
2141
|
+
return [credRes, snapRes, portlessRes];
|
|
2142
|
+
} catch (err) {
|
|
2143
|
+
return [{ label: "credentials", status: "warn", detail: errSummary(err) }];
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
var cloudProvider = createCloudProvider(digitaloceanBackend, {
|
|
2147
|
+
// s-2vcpu-4gb = 2 vCPU / 4 GB / 80 GB SSD.
|
|
2148
|
+
defaultResources: { cpu: 2, memory: 4, disk: 80 }
|
|
2149
|
+
});
|
|
2150
|
+
var digitaloceanProvider = {
|
|
2151
|
+
...cloudProvider,
|
|
2152
|
+
prepare: prepareDigitalOceanProvider,
|
|
2153
|
+
baseFingerprint: () => currentDigitalOceanBaseFingerprintLive()
|
|
2154
|
+
};
|
|
2155
|
+
var providerModule = {
|
|
2156
|
+
provider: digitaloceanProvider,
|
|
2157
|
+
backend: digitaloceanBackend,
|
|
2158
|
+
ensureCredentials: ensureDigitalOceanCredentials,
|
|
2159
|
+
readCredStatus: readCredStatusSummary,
|
|
2160
|
+
setCredentials: setDigitalOceanCredentials,
|
|
2161
|
+
currentBaseFingerprintLive: (claudeInstall) => currentDigitalOceanBaseFingerprintLive(claudeInstall),
|
|
2162
|
+
doctorChecks
|
|
2163
|
+
};
|
|
2164
|
+
export {
|
|
2165
|
+
DEFAULT_DO_ENDPOINT,
|
|
2166
|
+
DIGITALOCEAN_DEFAULT_BOX_IMAGE_REF,
|
|
2167
|
+
DigitalOceanApiError,
|
|
2168
|
+
RUNTIME_ASSETS,
|
|
2169
|
+
allowAllOutboundRules,
|
|
2170
|
+
candidatesFor,
|
|
2171
|
+
createPerBoxFirewall,
|
|
2172
|
+
currentDigitalOceanBaseFingerprintLive,
|
|
2173
|
+
deletePerBoxFirewall,
|
|
2174
|
+
detectEgressIp,
|
|
2175
|
+
digitaloceanBackend,
|
|
2176
|
+
digitaloceanProvider,
|
|
2177
|
+
ensureDigitalOceanBaseSnapshot,
|
|
2178
|
+
ensureDigitalOceanCredentials,
|
|
2179
|
+
ensureDigitalOceanEnvLoaded,
|
|
2180
|
+
findFirewallForDroplet,
|
|
2181
|
+
generateBoxCloudInit,
|
|
2182
|
+
generatePrepareCloudInit,
|
|
2183
|
+
isAttemptTimeout,
|
|
2184
|
+
isRetriable,
|
|
2185
|
+
makeDigitalOceanClient,
|
|
2186
|
+
mapDigitalOceanProvisionError,
|
|
2187
|
+
maskKey,
|
|
2188
|
+
mintPrepareKey,
|
|
2189
|
+
mintSshKey,
|
|
2190
|
+
normalizeSourceCidr,
|
|
2191
|
+
pollUntil,
|
|
2192
|
+
prepareDigitalOcean,
|
|
2193
|
+
prepareDigitalOceanProvider,
|
|
2194
|
+
preparedStatePath,
|
|
2195
|
+
providerModule,
|
|
2196
|
+
readDigitalOceanCredStatus,
|
|
2197
|
+
readPreparedState,
|
|
2198
|
+
resolveRuntimeAssets,
|
|
2199
|
+
scpDownload,
|
|
2200
|
+
scpUpload,
|
|
2201
|
+
secretsPath,
|
|
2202
|
+
setDigitalOceanCredentials,
|
|
2203
|
+
sshExec,
|
|
2204
|
+
sshInboundRules,
|
|
2205
|
+
sshOptArgs,
|
|
2206
|
+
syncFirewallSource,
|
|
2207
|
+
updatePreparedState,
|
|
2208
|
+
validateSizeChoice,
|
|
2209
|
+
waitForSsh,
|
|
2210
|
+
withDigitalOceanRetry,
|
|
2211
|
+
writePreparedState
|
|
2212
|
+
};
|