@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,1437 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_DO_ENDPOINT,
|
|
4
|
+
DigitalOceanApiError,
|
|
5
|
+
RUNTIME_ASSETS,
|
|
6
|
+
allowAllOutboundRules,
|
|
7
|
+
candidatesFor,
|
|
8
|
+
createPerBoxFirewall,
|
|
9
|
+
currentDigitalOceanBaseFingerprintLive,
|
|
10
|
+
deletePerBoxFirewall,
|
|
11
|
+
detectEgressIp,
|
|
12
|
+
ensureDigitalOceanCredentials,
|
|
13
|
+
ensureDigitalOceanEnvLoaded,
|
|
14
|
+
findFirewallForDroplet,
|
|
15
|
+
findStagedCliRuntimeRoot,
|
|
16
|
+
isAttemptTimeout,
|
|
17
|
+
isRetriable,
|
|
18
|
+
makeDigitalOceanClient,
|
|
19
|
+
maskKey,
|
|
20
|
+
normalizeSourceCidr,
|
|
21
|
+
preparedStatePath,
|
|
22
|
+
readDigitalOceanCredStatus,
|
|
23
|
+
readPreparedState,
|
|
24
|
+
resolveRuntimeAssets,
|
|
25
|
+
secretsPath,
|
|
26
|
+
setDigitalOceanCredentials,
|
|
27
|
+
sshInboundRules,
|
|
28
|
+
syncFirewallSource,
|
|
29
|
+
updatePreparedState,
|
|
30
|
+
withDigitalOceanRetry,
|
|
31
|
+
writePreparedState
|
|
32
|
+
} from "./chunk-WLHJZPFJ.js";
|
|
33
|
+
import {
|
|
34
|
+
createCloudProvider
|
|
35
|
+
} from "./chunk-6U2S6QWD.js";
|
|
36
|
+
import {
|
|
37
|
+
detectPortless,
|
|
38
|
+
portlessDoctorRow
|
|
39
|
+
} from "./chunk-I654PBHA.js";
|
|
40
|
+
import "./chunk-UIRBYL4G.js";
|
|
41
|
+
import {
|
|
42
|
+
UserFacingError,
|
|
43
|
+
claudeInstallFingerprint,
|
|
44
|
+
computeContextSha256,
|
|
45
|
+
describeInbound,
|
|
46
|
+
errSummary,
|
|
47
|
+
mintSshKey,
|
|
48
|
+
parseInboundSpec,
|
|
49
|
+
readCliStamp,
|
|
50
|
+
resolveInboundSources,
|
|
51
|
+
stageAgentsStaticForUpload,
|
|
52
|
+
stageClaudeStaticForUpload,
|
|
53
|
+
stageCodexStaticForUpload,
|
|
54
|
+
stageOpencodeStaticForUpload
|
|
55
|
+
} from "./chunk-DEDTPG2D.js";
|
|
56
|
+
import "./chunk-G3H2L3O2.js";
|
|
57
|
+
import "./chunk-WJFZJZIM.js";
|
|
58
|
+
|
|
59
|
+
// ../../packages/sandbox-digitalocean/dist/index.js
|
|
60
|
+
import { existsSync as existsSync2 } from "fs";
|
|
61
|
+
import { rm as rm2, rename, mkdir as mkdir2 } from "fs/promises";
|
|
62
|
+
import { join as join3 } from "path";
|
|
63
|
+
import { execa as execa3 } from "execa";
|
|
64
|
+
import { resolve as resolvePath } from "path";
|
|
65
|
+
import { join } from "path";
|
|
66
|
+
import { dirname, resolve } from "path";
|
|
67
|
+
import { execa } from "execa";
|
|
68
|
+
import { existsSync } from "fs";
|
|
69
|
+
import { mkdir, rm } from "fs/promises";
|
|
70
|
+
import { createServer } from "net";
|
|
71
|
+
import { homedir } from "os";
|
|
72
|
+
import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
|
|
73
|
+
import { execa as execa2 } from "execa";
|
|
74
|
+
function generatePrepareCloudInit(opts) {
|
|
75
|
+
const pubkey = opts.sshPubkey.trim();
|
|
76
|
+
return [
|
|
77
|
+
"#cloud-config",
|
|
78
|
+
// IMPORTANT: keep every emitted line ASCII-only. DigitalOcean's user-data
|
|
79
|
+
// delivery truncates the cloud-config at the first non-ASCII byte (an em-dash
|
|
80
|
+
// here silently dropped the whole doc -> no key injected -> ssh publickey
|
|
81
|
+
// denied). See generateBoxCloudInit for the same constraint.
|
|
82
|
+
"# AgentBox temporary prepare VPS - used by `agentbox prepare --provider digitalocean`",
|
|
83
|
+
"# to bake the base snapshot. SSH key is single-use and discarded on VPS destroy.",
|
|
84
|
+
"disable_root: false",
|
|
85
|
+
"ssh_pwauth: false",
|
|
86
|
+
// Inject the single-use key as a TOP-LEVEL `ssh_authorized_keys` (applies to
|
|
87
|
+
// the default user, which is `root` on DigitalOcean images). The `users:`
|
|
88
|
+
// block form does NOT inject a key for root on DO's Ubuntu 24.04 (cloud-init
|
|
89
|
+
// special-cases root under `disable_root`), so key auth failed with
|
|
90
|
+
// "Permission denied (publickey)". The top-level form is reliable.
|
|
91
|
+
"ssh_authorized_keys:",
|
|
92
|
+
` - ${yamlScalar(pubkey)}`,
|
|
93
|
+
// DigitalOcean's Ubuntu 24.04 stock image ships root's password force-expired
|
|
94
|
+
// (last-change date = 0), so PAM demands a change on first login — which
|
|
95
|
+
// blocks even key-authed non-TTY commands ("Password change required but no
|
|
96
|
+
// TTY available"). `chpasswd.expire:false` covers cloud-init's own run; the
|
|
97
|
+
// runcmd resets root's last-change date to TODAY (clearing the forced-change
|
|
98
|
+
// that `chage -E/-I/-M` alone does NOT touch) and disables all expiry.
|
|
99
|
+
"chpasswd:",
|
|
100
|
+
" expire: false",
|
|
101
|
+
"runcmd:",
|
|
102
|
+
" - [ passwd, -d, root ]",
|
|
103
|
+
' - [ bash, -lc, "chage -d $(date +%Y-%m-%d) -E -1 -I -1 -M 99999 -m 0 root" ]',
|
|
104
|
+
' - [ bash, -lc, "echo agentbox-prepare-ready" ]',
|
|
105
|
+
""
|
|
106
|
+
].join("\n");
|
|
107
|
+
}
|
|
108
|
+
function generateBoxCloudInit(opts) {
|
|
109
|
+
const pubkey = opts.sshPubkey.trim();
|
|
110
|
+
const lines = [
|
|
111
|
+
"#cloud-config",
|
|
112
|
+
// ASCII-only (see generatePrepareCloudInit): DO truncates user-data at the
|
|
113
|
+
// first non-ASCII byte, which would drop the whole cloud-config.
|
|
114
|
+
`# AgentBox per-box VPS - box '${opts.boxName}'`,
|
|
115
|
+
"disable_root: true",
|
|
116
|
+
"ssh_pwauth: false",
|
|
117
|
+
// Same first-login expiry guard as the prepare cloud-init — keeps
|
|
118
|
+
// DigitalOcean's Ubuntu hardening from blocking our key-based vscode login.
|
|
119
|
+
"chpasswd:",
|
|
120
|
+
" expire: false",
|
|
121
|
+
"users:",
|
|
122
|
+
" - name: vscode",
|
|
123
|
+
" lock_passwd: false",
|
|
124
|
+
" sudo: ALL=(ALL) NOPASSWD:ALL",
|
|
125
|
+
" ssh_authorized_keys:",
|
|
126
|
+
` - ${yamlScalar(pubkey)}`
|
|
127
|
+
];
|
|
128
|
+
const writeFiles = [
|
|
129
|
+
" path: /etc/hosts",
|
|
130
|
+
" append: true",
|
|
131
|
+
` content: "127.0.0.1 ${opts.boxName}.localhost\\n"`
|
|
132
|
+
];
|
|
133
|
+
lines.push("write_files:");
|
|
134
|
+
lines.push(" - " + writeFiles[0]);
|
|
135
|
+
for (let i = 1; i < writeFiles.length; i++) {
|
|
136
|
+
lines.push(" " + writeFiles[i]);
|
|
137
|
+
}
|
|
138
|
+
if (opts.boxEnv && Object.keys(opts.boxEnv).length > 0) {
|
|
139
|
+
const envContent = Object.entries(opts.boxEnv).map(([k, v]) => `${k}=${v}`).join("\\n") + "\\n";
|
|
140
|
+
lines.push(" - path: /etc/agentbox/box.env");
|
|
141
|
+
lines.push(' permissions: "0644"');
|
|
142
|
+
lines.push(` content: "${envContent}"`);
|
|
143
|
+
}
|
|
144
|
+
lines.push("");
|
|
145
|
+
return lines.join("\n");
|
|
146
|
+
}
|
|
147
|
+
function yamlScalar(value) {
|
|
148
|
+
if (/["\\]/.test(value)) {
|
|
149
|
+
return JSON.stringify(value);
|
|
150
|
+
}
|
|
151
|
+
return `"${value}"`;
|
|
152
|
+
}
|
|
153
|
+
async function pollUntil(label, check, opts = {}) {
|
|
154
|
+
const deadline = Date.now() + (opts.deadlineMs ?? 5 * 6e4);
|
|
155
|
+
const max = opts.maxIntervalMs ?? 1e4;
|
|
156
|
+
let interval = opts.intervalMs ?? 1e3;
|
|
157
|
+
let attempt = 0;
|
|
158
|
+
while (true) {
|
|
159
|
+
attempt += 1;
|
|
160
|
+
const out = await check();
|
|
161
|
+
if (out !== null && out !== void 0) return out;
|
|
162
|
+
if (Date.now() >= deadline) {
|
|
163
|
+
throw new Error(`digitalocean: timed out waiting for ${label} after ${String(attempt)} attempts`);
|
|
164
|
+
}
|
|
165
|
+
opts.onPoll?.(`${label}: not ready yet (attempt ${String(attempt)}); polling again in ${String(interval)}ms`);
|
|
166
|
+
await new Promise((r) => setTimeout(r, interval));
|
|
167
|
+
interval = Math.min(interval * 2, max);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function suggestSizes(catalog, limit = 6) {
|
|
171
|
+
return catalog.filter((s) => s.available).map((s) => s.slug).slice(0, limit);
|
|
172
|
+
}
|
|
173
|
+
function validateSizeChoice(choice, catalog, snapshot) {
|
|
174
|
+
const { size, region } = choice;
|
|
175
|
+
const plan = catalog.find((s) => s.slug === size);
|
|
176
|
+
if (!plan) {
|
|
177
|
+
const suggestions = suggestSizes(catalog);
|
|
178
|
+
const hint = suggestions.length > 0 ? ` Valid sizes include: ${suggestions.join(", ")}.` : "";
|
|
179
|
+
throw new UserFacingError(
|
|
180
|
+
`DigitalOcean size "${size}" does not exist.${hint}
|
|
181
|
+
Set one with \`--size <slug>\` or \`agentbox config set box.sizeDigitalocean <slug>\`.`
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
if (!plan.available) {
|
|
185
|
+
throw new UserFacingError(
|
|
186
|
+
`DigitalOcean size "${size}" is not currently available for new Droplets.
|
|
187
|
+
Pick an available size instead: ${suggestSizes(catalog).join(", ")}.`
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
if (snapshot && typeof snapshot.min_disk_size === "number" && plan.disk < snapshot.min_disk_size) {
|
|
191
|
+
throw new UserFacingError(
|
|
192
|
+
`DigitalOcean size "${size}" has a ${String(plan.disk)} GB disk, but the base snapshot needs at least ${String(snapshot.min_disk_size)} GB.
|
|
193
|
+
Choose a larger size (bigger plans have bigger disks).`
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
if (plan.regions.length > 0 && !plan.regions.includes(region)) {
|
|
197
|
+
throw new UserFacingError(
|
|
198
|
+
`DigitalOcean size "${size}" is not offered in region "${region}".
|
|
199
|
+
It is available in: ${plan.regions.join(", ")}.
|
|
200
|
+
Pick one with \`--location <slug>\` or \`agentbox config set box.digitaloceanRegion <slug>\`.`
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function mapDigitalOceanProvisionError(err, choice) {
|
|
205
|
+
if (!(err instanceof DigitalOceanApiError)) return err;
|
|
206
|
+
const { size, region } = choice;
|
|
207
|
+
const msg = err.message.toLowerCase();
|
|
208
|
+
if (msg.includes("droplet limit") || msg.includes("exceeded your droplet limit")) {
|
|
209
|
+
return new UserFacingError(
|
|
210
|
+
`DigitalOcean refused to create the Droplet: your account Droplet limit was exceeded (${err.message}).
|
|
211
|
+
New accounts start with a low Droplet limit. Request an increase in the DigitalOcean Console (Account \u2192 your team \u2192 Droplet limit), then retry.`
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
if (msg.includes("not available") || msg.includes("capacity") || msg.includes("sold out")) {
|
|
215
|
+
return new UserFacingError(
|
|
216
|
+
`DigitalOcean has no capacity for "${size}" in "${region}" right now (${err.message}).
|
|
217
|
+
Retry, or pick another region with \`--location <slug>\` (e.g. \`nyc1\`, \`sfo3\`, \`ams3\`, \`fra1\`) or \`agentbox config set box.digitaloceanRegion <slug>\`.`
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
return err;
|
|
221
|
+
}
|
|
222
|
+
async function mintPrepareKey() {
|
|
223
|
+
const root = resolve(homedirOrCwd(), ".agentbox", "digitalocean", `prepare-${Date.now().toString(36)}`);
|
|
224
|
+
const key = await mintSshKey(root, `agentbox-prepare-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`);
|
|
225
|
+
return {
|
|
226
|
+
...key,
|
|
227
|
+
cleanup: async () => {
|
|
228
|
+
try {
|
|
229
|
+
const { rm: rm3 } = await import("fs/promises");
|
|
230
|
+
await rm3(dirname(key.privatePath), { recursive: true, force: true });
|
|
231
|
+
} catch {
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
function homedirOrCwd() {
|
|
237
|
+
try {
|
|
238
|
+
return process.env.HOME ?? process.cwd();
|
|
239
|
+
} catch {
|
|
240
|
+
return process.cwd();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function sshOptArgs(target) {
|
|
244
|
+
const out = [
|
|
245
|
+
"-i",
|
|
246
|
+
target.identity,
|
|
247
|
+
"-o",
|
|
248
|
+
"StrictHostKeyChecking=accept-new",
|
|
249
|
+
"-o",
|
|
250
|
+
`UserKnownHostsFile=${target.knownHosts}`,
|
|
251
|
+
"-o",
|
|
252
|
+
"GlobalKnownHostsFile=/dev/null",
|
|
253
|
+
"-o",
|
|
254
|
+
"BatchMode=yes",
|
|
255
|
+
"-o",
|
|
256
|
+
"LogLevel=ERROR",
|
|
257
|
+
// Detect a dead/stalled peer and drop the connection instead of hanging
|
|
258
|
+
// forever. The per-box firewall is locked to the host's egress IP, so if
|
|
259
|
+
// that IP flaps mid-command (roaming Wi-Fi, VPN toggle) the return traffic
|
|
260
|
+
// is silently dropped and the ssh channel would otherwise block with no
|
|
261
|
+
// EOF — seen as a `prepare`/`exec` that never returns. 15s * 4 = a ~60s
|
|
262
|
+
// fail-fast so callers (retry wrappers, prepare cleanup) can react.
|
|
263
|
+
"-o",
|
|
264
|
+
"ServerAliveInterval=15",
|
|
265
|
+
"-o",
|
|
266
|
+
"ServerAliveCountMax=4"
|
|
267
|
+
];
|
|
268
|
+
if (target.controlPath) {
|
|
269
|
+
out.push("-o", `ControlPath=${target.controlPath}`);
|
|
270
|
+
}
|
|
271
|
+
for (const [k, v] of Object.entries(target.options ?? {})) {
|
|
272
|
+
out.push("-o", `${k}=${v}`);
|
|
273
|
+
}
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
async function sshExec(target, remoteCmd, opts = {}) {
|
|
277
|
+
const argv = [
|
|
278
|
+
...sshOptArgs(target),
|
|
279
|
+
`${target.user}@${target.host}`,
|
|
280
|
+
remoteCmd
|
|
281
|
+
];
|
|
282
|
+
const child = execa("ssh", argv, {
|
|
283
|
+
reject: false,
|
|
284
|
+
timeout: opts.timeoutMs,
|
|
285
|
+
env: { ...process.env, ...opts.env },
|
|
286
|
+
stdio: opts.onLine ? ["ignore", "pipe", "pipe"] : ["ignore", "pipe", "pipe"]
|
|
287
|
+
});
|
|
288
|
+
if (opts.onLine) {
|
|
289
|
+
const handle = (chunk) => {
|
|
290
|
+
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
291
|
+
for (const line of text.split(/\r?\n/)) {
|
|
292
|
+
if (line.length > 0) opts.onLine?.(line);
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
child.stdout?.on("data", handle);
|
|
296
|
+
child.stderr?.on("data", handle);
|
|
297
|
+
}
|
|
298
|
+
const res = await child;
|
|
299
|
+
return {
|
|
300
|
+
exitCode: typeof res.exitCode === "number" ? res.exitCode : 1,
|
|
301
|
+
stdout: typeof res.stdout === "string" ? res.stdout : "",
|
|
302
|
+
stderr: typeof res.stderr === "string" ? res.stderr : ""
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
async function scpUpload(target, localPath, remotePath, opts = {}) {
|
|
306
|
+
const argv = [
|
|
307
|
+
...sshOptArgs(target),
|
|
308
|
+
localPath,
|
|
309
|
+
`${target.user}@${target.host}:${remotePath}`
|
|
310
|
+
];
|
|
311
|
+
const res = await execa("scp", argv, {
|
|
312
|
+
reject: false,
|
|
313
|
+
timeout: opts.timeoutMs
|
|
314
|
+
});
|
|
315
|
+
if (res.exitCode !== 0) {
|
|
316
|
+
throw new Error(
|
|
317
|
+
`scp upload failed (exit ${String(res.exitCode)}): ${localPath} \u2192 ${remotePath}
|
|
318
|
+
${res.stderr ?? ""}`
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
async function scpDownload(target, remotePath, localPath, opts = {}) {
|
|
323
|
+
const argv = [
|
|
324
|
+
...sshOptArgs(target),
|
|
325
|
+
`${target.user}@${target.host}:${remotePath}`,
|
|
326
|
+
localPath
|
|
327
|
+
];
|
|
328
|
+
const res = await execa("scp", argv, {
|
|
329
|
+
reject: false,
|
|
330
|
+
timeout: opts.timeoutMs
|
|
331
|
+
});
|
|
332
|
+
if (res.exitCode !== 0) {
|
|
333
|
+
throw new Error(
|
|
334
|
+
`scp download failed (exit ${String(res.exitCode)}): ${remotePath} \u2192 ${localPath}
|
|
335
|
+
${res.stderr ?? ""}`
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
async function waitForSsh(target, deadlineMs, intervalMs = 5e3) {
|
|
340
|
+
const stop = Date.now() + deadlineMs;
|
|
341
|
+
while (Date.now() < stop) {
|
|
342
|
+
const res = await sshExec(
|
|
343
|
+
{ ...target, options: { ...target.options, ConnectTimeout: "5" } },
|
|
344
|
+
"true",
|
|
345
|
+
{ timeoutMs: 1e4 }
|
|
346
|
+
);
|
|
347
|
+
if (res.exitCode === 0) return true;
|
|
348
|
+
await new Promise((r) => setTimeout(r, intervalMs));
|
|
349
|
+
}
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
var TEMP_SIZE_DEFAULT = "s-2vcpu-4gb";
|
|
353
|
+
var TEMP_REGION_DEFAULT = "nyc3";
|
|
354
|
+
var STOCK_IMAGE_SLUG = "ubuntu-24-04-x64";
|
|
355
|
+
var PREPARE_SSH_DEADLINE_MS = 5 * 6e4;
|
|
356
|
+
var PROVISION_DROPLET_DEADLINE_MS = 5 * 6e4;
|
|
357
|
+
var INSTALL_SCRIPT_TIMEOUT_MS = 30 * 6e4;
|
|
358
|
+
var SNAPSHOT_DEADLINE_MS = 30 * 6e4;
|
|
359
|
+
async function snapshotStillExists(client2, imageId) {
|
|
360
|
+
try {
|
|
361
|
+
const snaps = await client2.listSnapshots();
|
|
362
|
+
return snaps.some((s) => s.id === String(imageId));
|
|
363
|
+
} catch {
|
|
364
|
+
return true;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
async function prepareDigitalOcean(opts = {}) {
|
|
368
|
+
await ensureDigitalOceanCredentials();
|
|
369
|
+
const client2 = makeDigitalOceanClient();
|
|
370
|
+
const log = opts.onLog ?? (() => {
|
|
371
|
+
});
|
|
372
|
+
const progress = (step) => log(`prepare-digitalocean: ${step}`);
|
|
373
|
+
const existingState = readPreparedState();
|
|
374
|
+
const assets = resolveRuntimeAssets({
|
|
375
|
+
cliRuntimeRoot: opts.cliRuntimeRoot ?? findStagedCliRuntimeRoot(),
|
|
376
|
+
repoRoot: opts.repoRoot
|
|
377
|
+
});
|
|
378
|
+
const claudeInstall = opts.claudeInstall ?? "native";
|
|
379
|
+
const contextSha = claudeInstallFingerprint(
|
|
380
|
+
await computeContextSha256(assets.map((a) => ({ rel: a.name, abs: a.localPath }))),
|
|
381
|
+
claudeInstall
|
|
382
|
+
);
|
|
383
|
+
if (!opts.force && existingState.base) {
|
|
384
|
+
const remote = await snapshotStillExists(client2, existingState.base.imageId);
|
|
385
|
+
if (remote && existingState.base.contextSha256 === contextSha) {
|
|
386
|
+
progress(
|
|
387
|
+
`base snapshot ${String(existingState.base.imageId)} already exists (fingerprint ${contextSha.slice(0, 12)} matches); skipping rebuild (pass --force to override)`
|
|
388
|
+
);
|
|
389
|
+
return {
|
|
390
|
+
snapshotName: existingState.base.description,
|
|
391
|
+
imageId: existingState.base.imageId
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
if (!remote) {
|
|
395
|
+
progress(`recorded base snapshot ${String(existingState.base.imageId)} is gone on DigitalOcean; rebuilding`);
|
|
396
|
+
} else {
|
|
397
|
+
progress(
|
|
398
|
+
`build context changed (was ${existingState.base.contextSha256?.slice(0, 12) ?? "<none>"}, now ${contextSha.slice(0, 12)}); rebuilding base snapshot`
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
progress("minting ephemeral ssh key");
|
|
403
|
+
const key = await mintPrepareKey();
|
|
404
|
+
let firewallId = null;
|
|
405
|
+
let dropletId = null;
|
|
406
|
+
const stamp = Date.now().toString(36);
|
|
407
|
+
const prepareTag = `agentbox-prepare-${stamp}`;
|
|
408
|
+
try {
|
|
409
|
+
progress("detecting host egress IP");
|
|
410
|
+
const source = opts.firewallSource ? normalizeSourceCidr(opts.firewallSource) : `${await detectEgressIp({ onLog: log })}/32`;
|
|
411
|
+
const firewallName = `agentbox-prepare-${stamp}`;
|
|
412
|
+
progress(`creating firewall ${firewallName} (source ${source})`);
|
|
413
|
+
const firewall = await createPerBoxFirewall(client2, {
|
|
414
|
+
name: firewallName,
|
|
415
|
+
sources: [source],
|
|
416
|
+
tag: prepareTag
|
|
417
|
+
});
|
|
418
|
+
firewallId = firewall.id;
|
|
419
|
+
const dropletName = `agentbox-prepare-${stamp}`;
|
|
420
|
+
const cloudInit = generatePrepareCloudInit({ sshPubkey: key.publicKey });
|
|
421
|
+
const size = opts.size ?? TEMP_SIZE_DEFAULT;
|
|
422
|
+
const region = opts.region ?? TEMP_REGION_DEFAULT;
|
|
423
|
+
progress(`creating temp Droplet ${dropletName} (${size} / ${region})`);
|
|
424
|
+
const created = await client2.createDroplet({
|
|
425
|
+
name: dropletName,
|
|
426
|
+
region,
|
|
427
|
+
size,
|
|
428
|
+
image: STOCK_IMAGE_SLUG,
|
|
429
|
+
user_data: cloudInit,
|
|
430
|
+
tags: [prepareTag, "agentbox", "agentbox-prepare"],
|
|
431
|
+
ipv6: false
|
|
432
|
+
});
|
|
433
|
+
dropletId = created.droplet.id;
|
|
434
|
+
progress(`droplet ${String(dropletId)} created; waiting for it to boot`);
|
|
435
|
+
const droplet = await pollUntil(
|
|
436
|
+
`droplet ${String(dropletId)} active`,
|
|
437
|
+
async () => {
|
|
438
|
+
const d = await client2.getDroplet(dropletId);
|
|
439
|
+
const ip2 = d?.networks.v4.find((n) => n.type === "public")?.ip_address;
|
|
440
|
+
return d && d.status === "active" && ip2 ? { d, ip: ip2 } : null;
|
|
441
|
+
},
|
|
442
|
+
{ deadlineMs: PROVISION_DROPLET_DEADLINE_MS, intervalMs: 3e3, maxIntervalMs: 1e4, onPoll: (l) => log(`prepare-digitalocean: ${l}`) }
|
|
443
|
+
);
|
|
444
|
+
const ip = droplet.ip;
|
|
445
|
+
progress(`waiting for ssh on ${ip} (deadline ${String(PREPARE_SSH_DEADLINE_MS / 1e3)}s)`);
|
|
446
|
+
const sshTarget = {
|
|
447
|
+
host: ip,
|
|
448
|
+
user: "root",
|
|
449
|
+
identity: key.privatePath,
|
|
450
|
+
knownHosts: join(key.dir, "known_hosts")
|
|
451
|
+
};
|
|
452
|
+
const up = await waitForSsh(sshTarget, PREPARE_SSH_DEADLINE_MS);
|
|
453
|
+
if (!up) {
|
|
454
|
+
throw new Error(`digitalocean: ssh on ${ip} did not come up within ${String(PREPARE_SSH_DEADLINE_MS / 1e3)}s`);
|
|
455
|
+
}
|
|
456
|
+
progress("ssh up \u2014 scp'ing runtime assets");
|
|
457
|
+
for (const asset of assets) {
|
|
458
|
+
const remote = `/tmp/${asset.remoteBasename}`;
|
|
459
|
+
log(`prepare-digitalocean: scp ${asset.name} -> ${remote}`);
|
|
460
|
+
await scpUpload(sshTarget, asset.localPath, remote);
|
|
461
|
+
if (asset.remoteMode !== void 0) {
|
|
462
|
+
const modeOctal = asset.remoteMode.toString(8);
|
|
463
|
+
await sshExec(sshTarget, `chmod ${modeOctal} ${remote}`);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
progress("running install-box.sh on temp Droplet (this takes ~5-15 min)");
|
|
467
|
+
const installRes = await sshExec(
|
|
468
|
+
sshTarget,
|
|
469
|
+
`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`,
|
|
470
|
+
{
|
|
471
|
+
timeoutMs: INSTALL_SCRIPT_TIMEOUT_MS,
|
|
472
|
+
onLine: (line) => log(`[install] ${line}`)
|
|
473
|
+
}
|
|
474
|
+
);
|
|
475
|
+
if (installRes.exitCode !== 0) {
|
|
476
|
+
throw new Error(
|
|
477
|
+
`install-box.sh failed on temp Droplet (exit ${String(installRes.exitCode)})
|
|
478
|
+
Last stderr: ${installRes.stderr.slice(-500) || "(empty)"}
|
|
479
|
+
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.`
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
progress("install script complete");
|
|
483
|
+
progress("staging host agent static config");
|
|
484
|
+
const stagings = [];
|
|
485
|
+
try {
|
|
486
|
+
const claudeTar = await stageClaudeStaticForUpload({ hostWorkspace: opts.hostWorkspace });
|
|
487
|
+
for (const w of claudeTar.warnings) log(`prepare-digitalocean: ${w}`);
|
|
488
|
+
if (claudeTar.tarballPath) stagings.push({ kind: "claude", tar: claudeTar, dest: "/home/vscode/.claude" });
|
|
489
|
+
else await claudeTar.cleanup();
|
|
490
|
+
const codexTar = await stageCodexStaticForUpload();
|
|
491
|
+
for (const w of codexTar.warnings) log(`prepare-digitalocean: ${w}`);
|
|
492
|
+
if (codexTar.tarballPath) stagings.push({ kind: "codex", tar: codexTar, dest: "/home/vscode/.codex" });
|
|
493
|
+
else await codexTar.cleanup();
|
|
494
|
+
const opencodeTar = await stageOpencodeStaticForUpload();
|
|
495
|
+
for (const w of opencodeTar.warnings) log(`prepare-digitalocean: ${w}`);
|
|
496
|
+
if (opencodeTar.tarballPath) stagings.push({ kind: "opencode", tar: opencodeTar, dest: "/home/vscode/.local/share/opencode" });
|
|
497
|
+
else await opencodeTar.cleanup();
|
|
498
|
+
const agentsTar = await stageAgentsStaticForUpload();
|
|
499
|
+
for (const w of agentsTar.warnings) log(`prepare-digitalocean: ${w}`);
|
|
500
|
+
if (agentsTar.tarballPath) stagings.push({ kind: "agents", tar: agentsTar, dest: "/home/vscode/.agents" });
|
|
501
|
+
else await agentsTar.cleanup();
|
|
502
|
+
for (const s of stagings) {
|
|
503
|
+
const remote = `/tmp/agentbox-${s.kind}-static.tar.gz`;
|
|
504
|
+
log(`prepare-digitalocean: scp ${s.kind} static (${s.tar.tarballPath}) -> ${remote}`);
|
|
505
|
+
await scpUpload(sshTarget, s.tar.tarballPath, remote);
|
|
506
|
+
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}`;
|
|
507
|
+
const r = await sshExec(sshTarget, extractCmd, { onLine: (line) => log(`[stage:${s.kind}] ${line}`) });
|
|
508
|
+
if (r.exitCode !== 0) {
|
|
509
|
+
throw new Error(
|
|
510
|
+
`prepare-digitalocean: ${s.kind} static extract failed (exit ${String(r.exitCode)}): ${r.stderr.slice(-300)}`
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
progress(`baked ${s.kind} static config into snapshot`);
|
|
514
|
+
}
|
|
515
|
+
} finally {
|
|
516
|
+
for (const s of stagings) await s.tar.cleanup();
|
|
517
|
+
}
|
|
518
|
+
const description = opts.name ?? `agentbox-base-${stamp}`;
|
|
519
|
+
progress(`creating snapshot '${description}' from droplet ${String(dropletId)}`);
|
|
520
|
+
const action = await client2.snapshotDroplet(dropletId, description);
|
|
521
|
+
progress(`snapshot action ${String(action.id)} requested; polling until complete`);
|
|
522
|
+
await pollUntil(
|
|
523
|
+
`snapshot action ${String(action.id)}`,
|
|
524
|
+
async () => {
|
|
525
|
+
const a = await client2.getAction(action.id);
|
|
526
|
+
if (!a) return null;
|
|
527
|
+
if (a.status === "errored") {
|
|
528
|
+
throw new Error(`digitalocean: snapshot action ${String(action.id)} errored`);
|
|
529
|
+
}
|
|
530
|
+
return a.status === "completed" ? a : null;
|
|
531
|
+
},
|
|
532
|
+
{ deadlineMs: SNAPSHOT_DEADLINE_MS, intervalMs: 3e3, maxIntervalMs: 1e4, onPoll: (l) => log(`prepare-digitalocean: ${l}`) }
|
|
533
|
+
);
|
|
534
|
+
const snap = (await client2.listSnapshots()).find((s) => s.name === description);
|
|
535
|
+
if (!snap) {
|
|
536
|
+
throw new Error(`digitalocean: snapshot '${description}' completed but was not found in the snapshot list`);
|
|
537
|
+
}
|
|
538
|
+
const snapshotId = Number.parseInt(snap.id, 10);
|
|
539
|
+
progress("persisting digitalocean-prepared.json");
|
|
540
|
+
const state = readPreparedState();
|
|
541
|
+
const cliStamp = readCliStamp();
|
|
542
|
+
state.base = {
|
|
543
|
+
imageId: snapshotId,
|
|
544
|
+
description,
|
|
545
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
546
|
+
contextSha256: contextSha,
|
|
547
|
+
cliVersion: cliStamp.cliVersion,
|
|
548
|
+
cliCommit: cliStamp.cliCommit
|
|
549
|
+
};
|
|
550
|
+
writePreparedState(state);
|
|
551
|
+
log(`prepare-digitalocean: wrote ${preparedStatePath()}`);
|
|
552
|
+
progress(`deleting temp Droplet ${String(dropletId)}`);
|
|
553
|
+
await client2.deleteDroplet(dropletId);
|
|
554
|
+
dropletId = null;
|
|
555
|
+
progress(`deleting per-prepare firewall ${firewallId}`);
|
|
556
|
+
await deletePerBoxFirewall(client2, firewallId, { tags: [prepareTag] });
|
|
557
|
+
firewallId = null;
|
|
558
|
+
progress(`prepare complete \u2014 base snapshot ${String(snapshotId)} (${description})`);
|
|
559
|
+
return { snapshotName: description, imageId: snapshotId };
|
|
560
|
+
} catch (err) {
|
|
561
|
+
if (dropletId !== null) {
|
|
562
|
+
log(`prepare-digitalocean: cleanup \u2014 deleting temp Droplet ${String(dropletId)} after failure`);
|
|
563
|
+
try {
|
|
564
|
+
await client2.deleteDroplet(dropletId);
|
|
565
|
+
} catch (cleanupErr) {
|
|
566
|
+
log(
|
|
567
|
+
`prepare-digitalocean: WARN \u2014 failed to delete temp Droplet ${String(dropletId)}; check the DigitalOcean dashboard manually. ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (firewallId !== null) {
|
|
572
|
+
log(`prepare-digitalocean: cleanup \u2014 deleting per-prepare firewall ${firewallId} after failure`);
|
|
573
|
+
try {
|
|
574
|
+
await deletePerBoxFirewall(client2, firewallId, { tags: [prepareTag] });
|
|
575
|
+
} catch (cleanupErr) {
|
|
576
|
+
log(
|
|
577
|
+
`prepare-digitalocean: WARN \u2014 failed to delete firewall ${firewallId}; check the DigitalOcean dashboard manually. ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`
|
|
578
|
+
);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
throw err;
|
|
582
|
+
} finally {
|
|
583
|
+
await key.cleanup();
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
var prepareDigitalOceanProvider = (req) => prepareDigitalOcean({
|
|
587
|
+
name: req.name,
|
|
588
|
+
hostWorkspace: req.hostWorkspace ?? process.cwd(),
|
|
589
|
+
force: req.force,
|
|
590
|
+
// Region for the temp bake Droplet (defaults to nyc3 when unset). Resolved
|
|
591
|
+
// by the CLI from `--location` / `box.digitaloceanRegion`.
|
|
592
|
+
region: req.location,
|
|
593
|
+
// Droplet size for the temp bake VPS (CLI `--size` / `box.sizeDigitalocean`).
|
|
594
|
+
size: req.size,
|
|
595
|
+
// Forward the Claude install mode (native | npm) so the `npm` escape hatch
|
|
596
|
+
// (box.claudeInstall / --claude-install npm) reaches the bake — the native
|
|
597
|
+
// installer's CDN 403s some datacenter egress IPs. (matches Hetzner.)
|
|
598
|
+
claudeInstall: req.claudeInstall,
|
|
599
|
+
onLog: req.onLog
|
|
600
|
+
});
|
|
601
|
+
async function ensureDigitalOceanBaseSnapshot() {
|
|
602
|
+
const state = readPreparedState();
|
|
603
|
+
if (state.base !== void 0) return;
|
|
604
|
+
throw new UserFacingError(
|
|
605
|
+
"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)."
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
var HOST = "127.0.0.1";
|
|
609
|
+
var EPHEMERAL_MIN = 49152;
|
|
610
|
+
var EPHEMERAL_MAX = 65535;
|
|
611
|
+
var SshTunnelManager = class {
|
|
612
|
+
boxes = /* @__PURE__ */ new Map();
|
|
613
|
+
/**
|
|
614
|
+
* Open the ControlMaster for `boxId`. Idempotent: if a master is already
|
|
615
|
+
* up for this box (socket exists + responsive), no-op. Otherwise spawn a
|
|
616
|
+
* fresh `ssh -fNT -M` and wait for the socket to appear.
|
|
617
|
+
*/
|
|
618
|
+
async open(opts) {
|
|
619
|
+
const boxSshDir = opts.boxSshDir ?? defaultBoxSshDir(opts.boxId);
|
|
620
|
+
await mkdir(boxSshDir, { recursive: true, mode: 448 });
|
|
621
|
+
const controlPath = join2(boxSshDir, "control.sock");
|
|
622
|
+
const knownHosts = join2(boxSshDir, "known_hosts");
|
|
623
|
+
const user = opts.vpsUser ?? "vscode";
|
|
624
|
+
const tunnel = {
|
|
625
|
+
controlPath,
|
|
626
|
+
vpsHost: opts.vpsHost,
|
|
627
|
+
vpsUser: user,
|
|
628
|
+
identity: opts.identity,
|
|
629
|
+
boxSshDir,
|
|
630
|
+
forwards: /* @__PURE__ */ new Map()
|
|
631
|
+
};
|
|
632
|
+
if (existsSync(controlPath) && await this.isAlive(controlPath)) {
|
|
633
|
+
this.boxes.set(opts.boxId, tunnel);
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
if (existsSync(controlPath)) {
|
|
637
|
+
await rm(controlPath, { force: true });
|
|
638
|
+
}
|
|
639
|
+
const connectTimeout = opts.connectTimeoutSeconds ?? 10;
|
|
640
|
+
const argv = [
|
|
641
|
+
"-fNT",
|
|
642
|
+
"-M",
|
|
643
|
+
"-S",
|
|
644
|
+
controlPath,
|
|
645
|
+
"-i",
|
|
646
|
+
opts.identity,
|
|
647
|
+
"-o",
|
|
648
|
+
"StrictHostKeyChecking=accept-new",
|
|
649
|
+
"-o",
|
|
650
|
+
`UserKnownHostsFile=${knownHosts}`,
|
|
651
|
+
"-o",
|
|
652
|
+
"GlobalKnownHostsFile=/dev/null",
|
|
653
|
+
"-o",
|
|
654
|
+
"BatchMode=yes",
|
|
655
|
+
"-o",
|
|
656
|
+
"LogLevel=ERROR",
|
|
657
|
+
"-o",
|
|
658
|
+
"ExitOnForwardFailure=yes",
|
|
659
|
+
"-o",
|
|
660
|
+
"ServerAliveInterval=30",
|
|
661
|
+
"-o",
|
|
662
|
+
"ServerAliveCountMax=3",
|
|
663
|
+
"-o",
|
|
664
|
+
`ConnectTimeout=${String(connectTimeout)}`,
|
|
665
|
+
`${user}@${opts.vpsHost}`
|
|
666
|
+
];
|
|
667
|
+
const res = await execa2("ssh", argv, { reject: false });
|
|
668
|
+
if (res.exitCode !== 0 || !existsSync(controlPath)) {
|
|
669
|
+
throw new Error(
|
|
670
|
+
`ssh ControlMaster failed for ${opts.boxId} (exit ${String(res.exitCode)}): ${res.stderr || res.stdout || "(no output)"}`
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
this.boxes.set(opts.boxId, tunnel);
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Mint (or fetch the cached) `127.0.0.1:<localPort> → vps:127.0.0.1:<remotePort>`
|
|
677
|
+
* forward. Returns the local port. Idempotent per (boxId, remotePort).
|
|
678
|
+
*
|
|
679
|
+
* The cached entry is only returned when the underlying ControlMaster is
|
|
680
|
+
* still alive — without that check we'd happily hand back a localPort that
|
|
681
|
+
* stopped listening when the master died (e.g. transient network blip,
|
|
682
|
+
* host sleep/wake). When the master is dead we drop ALL cached forwards
|
|
683
|
+
* for this box (they all share one tunnel) and re-mint from scratch.
|
|
684
|
+
*/
|
|
685
|
+
async forward(boxId, remotePort) {
|
|
686
|
+
const tunnel = this.getTunnelOrThrow(boxId);
|
|
687
|
+
const cached = tunnel.forwards.get(remotePort);
|
|
688
|
+
if (cached !== void 0 && await this.isAlive(tunnel.controlPath)) {
|
|
689
|
+
return cached;
|
|
690
|
+
}
|
|
691
|
+
if (cached !== void 0) {
|
|
692
|
+
tunnel.forwards.clear();
|
|
693
|
+
}
|
|
694
|
+
const localPort = await pickFreePort();
|
|
695
|
+
const argv = [
|
|
696
|
+
"-O",
|
|
697
|
+
"forward",
|
|
698
|
+
"-L",
|
|
699
|
+
`${HOST}:${String(localPort)}:${HOST}:${String(remotePort)}`,
|
|
700
|
+
"-S",
|
|
701
|
+
tunnel.controlPath,
|
|
702
|
+
"dummy"
|
|
703
|
+
// the target host is ignored when -O is used, but argv needs one
|
|
704
|
+
];
|
|
705
|
+
const res = await execa2("ssh", argv, { reject: false });
|
|
706
|
+
if (res.exitCode !== 0) {
|
|
707
|
+
throw new Error(
|
|
708
|
+
`ssh -O forward failed for ${boxId} (exit ${String(res.exitCode)}): ${res.stderr || res.stdout || "(no output)"}`
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
tunnel.forwards.set(remotePort, localPort);
|
|
712
|
+
return localPort;
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Tear down a dead ControlMaster + every cached forward for this box,
|
|
716
|
+
* then re-open from scratch. Idempotent — if the master is already alive
|
|
717
|
+
* the master open() is a no-op, but the cached forwards still get
|
|
718
|
+
* cleared so the next forward() call re-mints them. Returns when the
|
|
719
|
+
* master is open and the box's forwards map is empty (ready for fresh
|
|
720
|
+
* forward() calls).
|
|
721
|
+
*
|
|
722
|
+
* Use case: the cloud-poller observes ECONNREFUSED on the local port and
|
|
723
|
+
* asks the backend to refresh the preview URL — that path calls into
|
|
724
|
+
* here so the master + forward both come back fresh.
|
|
725
|
+
*/
|
|
726
|
+
async refresh(opts) {
|
|
727
|
+
const existing = this.boxes.get(opts.boxId);
|
|
728
|
+
if (existing) {
|
|
729
|
+
const alive = await this.isAlive(existing.controlPath);
|
|
730
|
+
if (!alive && existsSync(existing.controlPath)) {
|
|
731
|
+
try {
|
|
732
|
+
await execa2(
|
|
733
|
+
"ssh",
|
|
734
|
+
["-O", "exit", "-S", existing.controlPath, "dummy"],
|
|
735
|
+
{ reject: false }
|
|
736
|
+
);
|
|
737
|
+
} catch {
|
|
738
|
+
}
|
|
739
|
+
await rm(existing.controlPath, { force: true });
|
|
740
|
+
}
|
|
741
|
+
existing.forwards.clear();
|
|
742
|
+
}
|
|
743
|
+
await this.open(opts);
|
|
744
|
+
}
|
|
745
|
+
/** Tear down a single forward. Idempotent — unknown ports are no-ops. */
|
|
746
|
+
async unforward(boxId, remotePort) {
|
|
747
|
+
const tunnel = this.getTunnelOrThrow(boxId);
|
|
748
|
+
const localPort = tunnel.forwards.get(remotePort);
|
|
749
|
+
if (localPort === void 0) return;
|
|
750
|
+
const argv = [
|
|
751
|
+
"-O",
|
|
752
|
+
"cancel",
|
|
753
|
+
"-L",
|
|
754
|
+
`${HOST}:${String(localPort)}:${HOST}:${String(remotePort)}`,
|
|
755
|
+
"-S",
|
|
756
|
+
tunnel.controlPath,
|
|
757
|
+
"dummy"
|
|
758
|
+
];
|
|
759
|
+
await execa2("ssh", argv, { reject: false });
|
|
760
|
+
tunnel.forwards.delete(remotePort);
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Close the ControlMaster (and all its forwards). Idempotent — if no
|
|
764
|
+
* master is recorded, no-op. Removes the socket file.
|
|
765
|
+
*/
|
|
766
|
+
async close(boxId) {
|
|
767
|
+
const tunnel = this.boxes.get(boxId);
|
|
768
|
+
if (!tunnel) return;
|
|
769
|
+
if (existsSync(tunnel.controlPath)) {
|
|
770
|
+
await execa2("ssh", ["-O", "exit", "-S", tunnel.controlPath, "dummy"], { reject: false });
|
|
771
|
+
await rm(tunnel.controlPath, { force: true });
|
|
772
|
+
}
|
|
773
|
+
this.boxes.delete(boxId);
|
|
774
|
+
}
|
|
775
|
+
/** Tear down every open box. */
|
|
776
|
+
async closeAll() {
|
|
777
|
+
const ids = Array.from(this.boxes.keys());
|
|
778
|
+
await Promise.all(ids.map((id) => this.close(id)));
|
|
779
|
+
}
|
|
780
|
+
/** Path to the ControlMaster socket for `boxId`, if open. */
|
|
781
|
+
controlPath(boxId) {
|
|
782
|
+
return this.boxes.get(boxId)?.controlPath;
|
|
783
|
+
}
|
|
784
|
+
/** True if a ControlMaster is registered for `boxId` (regardless of liveness). */
|
|
785
|
+
has(boxId) {
|
|
786
|
+
return this.boxes.has(boxId);
|
|
787
|
+
}
|
|
788
|
+
/** Per-box ssh dir (tests use this to verify the layout). */
|
|
789
|
+
boxSshDir(boxId) {
|
|
790
|
+
return this.boxes.get(boxId)?.boxSshDir;
|
|
791
|
+
}
|
|
792
|
+
/** Re-open the manager record for an existing-on-disk control socket. */
|
|
793
|
+
registerExisting(boxId, opts) {
|
|
794
|
+
const boxSshDir = opts.boxSshDir ?? defaultBoxSshDir(opts.boxId);
|
|
795
|
+
this.boxes.set(boxId, {
|
|
796
|
+
controlPath: join2(boxSshDir, "control.sock"),
|
|
797
|
+
vpsHost: opts.vpsHost,
|
|
798
|
+
vpsUser: opts.vpsUser ?? "vscode",
|
|
799
|
+
identity: opts.identity,
|
|
800
|
+
boxSshDir,
|
|
801
|
+
forwards: /* @__PURE__ */ new Map()
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
async isAlive(controlPath) {
|
|
805
|
+
const res = await execa2("ssh", ["-O", "check", "-S", controlPath, "dummy"], { reject: false });
|
|
806
|
+
return res.exitCode === 0;
|
|
807
|
+
}
|
|
808
|
+
getTunnelOrThrow(boxId) {
|
|
809
|
+
const t = this.boxes.get(boxId);
|
|
810
|
+
if (!t) throw new Error(`no SSH ControlMaster registered for box ${boxId}; call open() first`);
|
|
811
|
+
return t;
|
|
812
|
+
}
|
|
813
|
+
};
|
|
814
|
+
function defaultBoxSshDir(boxId) {
|
|
815
|
+
return resolve2(homedir(), ".agentbox", "digitalocean", "boxes", boxId, "ssh");
|
|
816
|
+
}
|
|
817
|
+
async function pickFreePort() {
|
|
818
|
+
return new Promise((resolveOk, reject) => {
|
|
819
|
+
const srv = createServer();
|
|
820
|
+
srv.unref();
|
|
821
|
+
srv.on("error", reject);
|
|
822
|
+
srv.listen(0, HOST, () => {
|
|
823
|
+
const addr = srv.address();
|
|
824
|
+
if (!addr || typeof addr === "string") {
|
|
825
|
+
srv.close();
|
|
826
|
+
reject(new Error("could not get a free local port"));
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
const port = addr.port;
|
|
830
|
+
srv.close(() => {
|
|
831
|
+
if (port < EPHEMERAL_MIN || port > EPHEMERAL_MAX) {
|
|
832
|
+
resolveOk(port);
|
|
833
|
+
} else {
|
|
834
|
+
resolveOk(port);
|
|
835
|
+
}
|
|
836
|
+
});
|
|
837
|
+
});
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
var DIGITALOCEAN_DEFAULT_BOX_IMAGE_REF = "agentbox-base";
|
|
841
|
+
var SCAFFOLDING_FALLBACK_IMAGE = "agentbox/box:dev";
|
|
842
|
+
var VPS_USER = "vscode";
|
|
843
|
+
var PROVISION_SSH_DEADLINE_MS = 10 * 6e4;
|
|
844
|
+
var PROVISION_DROPLET_DEADLINE_MS2 = 5 * 6e4;
|
|
845
|
+
var ACTION_DEADLINE_MS = 5 * 6e4;
|
|
846
|
+
var SNAPSHOT_DEADLINE_MS2 = 30 * 6e4;
|
|
847
|
+
var DIGITALOCEAN_DEFAULT_SIZE = "s-2vcpu-4gb";
|
|
848
|
+
var DIGITALOCEAN_DEFAULT_REGION = "nyc3";
|
|
849
|
+
var CLOUD_INIT_BOX_ENV_EXCLUDE = /* @__PURE__ */ new Set([
|
|
850
|
+
"AGENTBOX_RELAY_URL",
|
|
851
|
+
"AGENTBOX_RELAY_TOKEN",
|
|
852
|
+
"AGENTBOX_BRIDGE_TOKEN"
|
|
853
|
+
]);
|
|
854
|
+
function cloudInitBoxEnv(env = {}) {
|
|
855
|
+
const out = {};
|
|
856
|
+
for (const [k, v] of Object.entries(env)) {
|
|
857
|
+
if (v !== void 0 && k.startsWith("AGENTBOX_") && !CLOUD_INIT_BOX_ENV_EXCLUDE.has(k)) {
|
|
858
|
+
out[k] = v;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
return out;
|
|
862
|
+
}
|
|
863
|
+
var tunnels = new SshTunnelManager();
|
|
864
|
+
function mapState(s) {
|
|
865
|
+
switch (s) {
|
|
866
|
+
case "active":
|
|
867
|
+
case "new":
|
|
868
|
+
return "running";
|
|
869
|
+
case "off":
|
|
870
|
+
case "archive":
|
|
871
|
+
return "paused";
|
|
872
|
+
default:
|
|
873
|
+
return "missing";
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
function client() {
|
|
877
|
+
return makeDigitalOceanClient();
|
|
878
|
+
}
|
|
879
|
+
function publicIpv4(droplet) {
|
|
880
|
+
return droplet.networks.v4.find((n) => n.type === "public")?.ip_address;
|
|
881
|
+
}
|
|
882
|
+
async function getDropletStrict(id) {
|
|
883
|
+
const d = await client().getDroplet(id);
|
|
884
|
+
if (!d) {
|
|
885
|
+
throw new Error(`digitalocean: droplet ${String(id)} not found (already destroyed?)`);
|
|
886
|
+
}
|
|
887
|
+
return d;
|
|
888
|
+
}
|
|
889
|
+
function sanitizeTag(name) {
|
|
890
|
+
return name.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 200);
|
|
891
|
+
}
|
|
892
|
+
async function waitAction(c, actionId, label, deadlineMs) {
|
|
893
|
+
await pollUntil(
|
|
894
|
+
label,
|
|
895
|
+
async () => {
|
|
896
|
+
const a = await c.getAction(actionId);
|
|
897
|
+
if (!a) return null;
|
|
898
|
+
if (a.status === "errored") {
|
|
899
|
+
throw new Error(`digitalocean: action ${String(actionId)} (${label}) errored`);
|
|
900
|
+
}
|
|
901
|
+
return a.status === "completed" ? a : null;
|
|
902
|
+
},
|
|
903
|
+
{ deadlineMs, intervalMs: 2e3, maxIntervalMs: 8e3 }
|
|
904
|
+
);
|
|
905
|
+
}
|
|
906
|
+
async function resolveImageRef(c, req) {
|
|
907
|
+
const ref = req.snapshot ?? req.image;
|
|
908
|
+
if (!ref || ref === DIGITALOCEAN_DEFAULT_BOX_IMAGE_REF || ref === SCAFFOLDING_FALLBACK_IMAGE) {
|
|
909
|
+
await ensureDigitalOceanBaseSnapshot();
|
|
910
|
+
const state = readPreparedState();
|
|
911
|
+
if (!state.base) {
|
|
912
|
+
throw new Error(
|
|
913
|
+
"no DigitalOcean base snapshot found \u2014 run `agentbox prepare --provider digitalocean` to bake one."
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
return state.base.imageId;
|
|
917
|
+
}
|
|
918
|
+
if (/^\d+$/.test(ref)) {
|
|
919
|
+
return Number.parseInt(ref, 10);
|
|
920
|
+
}
|
|
921
|
+
const snap = (await c.listSnapshots()).find((s) => s.name === ref);
|
|
922
|
+
if (snap) return Number.parseInt(snap.id, 10);
|
|
923
|
+
return ref;
|
|
924
|
+
}
|
|
925
|
+
function perBoxDir(sandboxId) {
|
|
926
|
+
return resolvePath(defaultBoxSshDir(sandboxId), "..");
|
|
927
|
+
}
|
|
928
|
+
async function ensurePerBoxState(sandboxId) {
|
|
929
|
+
const dir = perBoxDir(sandboxId);
|
|
930
|
+
const sshDir = join3(dir, "ssh");
|
|
931
|
+
await mkdir2(sshDir, { recursive: true, mode: 448 });
|
|
932
|
+
return {
|
|
933
|
+
dir,
|
|
934
|
+
identity: join3(sshDir, "id_ed25519"),
|
|
935
|
+
knownHosts: join3(sshDir, "known_hosts")
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
function bashScript(s) {
|
|
939
|
+
return `bash -lc ${shellQuote(s)}`;
|
|
940
|
+
}
|
|
941
|
+
function shellQuote(s) {
|
|
942
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
943
|
+
}
|
|
944
|
+
function buildSshTarget(state, vpsIp, controlPath) {
|
|
945
|
+
return {
|
|
946
|
+
host: vpsIp,
|
|
947
|
+
user: VPS_USER,
|
|
948
|
+
identity: state.identity,
|
|
949
|
+
knownHosts: state.knownHosts,
|
|
950
|
+
controlPath
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
async function ensureTunnel(sandboxId, state, vpsIp) {
|
|
954
|
+
if (tunnels.has(sandboxId)) return;
|
|
955
|
+
await tunnels.open({
|
|
956
|
+
boxId: sandboxId,
|
|
957
|
+
vpsHost: vpsIp,
|
|
958
|
+
identity: state.identity
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
async function ensureLiveTarget(sandboxId) {
|
|
962
|
+
const id = Number.parseInt(sandboxId, 10);
|
|
963
|
+
if (!Number.isFinite(id)) {
|
|
964
|
+
throw new Error(`digitalocean: invalid sandboxId ${sandboxId}`);
|
|
965
|
+
}
|
|
966
|
+
const droplet = await getDropletStrict(id);
|
|
967
|
+
const vpsIp = publicIpv4(droplet);
|
|
968
|
+
if (!vpsIp) {
|
|
969
|
+
throw new Error(`digitalocean: droplet ${String(id)} has no public IPv4 address`);
|
|
970
|
+
}
|
|
971
|
+
const state = await ensurePerBoxState(sandboxId);
|
|
972
|
+
if (!existsSync2(state.identity)) {
|
|
973
|
+
throw new Error(
|
|
974
|
+
`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.`
|
|
975
|
+
);
|
|
976
|
+
}
|
|
977
|
+
await ensureTunnel(sandboxId, state, vpsIp);
|
|
978
|
+
const controlPath = tunnels.controlPath(sandboxId);
|
|
979
|
+
return { target: buildSshTarget(state, vpsIp, controlPath), state, vpsIp };
|
|
980
|
+
}
|
|
981
|
+
var digitaloceanBackend = {
|
|
982
|
+
name: "digitalocean",
|
|
983
|
+
async provision(req) {
|
|
984
|
+
const c = client();
|
|
985
|
+
const onLog = req.onLog ?? (() => {
|
|
986
|
+
});
|
|
987
|
+
const progress = (s) => onLog(`digitalocean: ${s}`);
|
|
988
|
+
await ensureDigitalOceanBaseSnapshot();
|
|
989
|
+
const imageRef = await resolveImageRef(c, req);
|
|
990
|
+
const size = req.size && req.size.trim() || DIGITALOCEAN_DEFAULT_SIZE;
|
|
991
|
+
const region = req.location && req.location.trim() || req.env?.AGENTBOX_DIGITALOCEAN_REGION || process.env.AGENTBOX_DIGITALOCEAN_REGION || DIGITALOCEAN_DEFAULT_REGION;
|
|
992
|
+
const choice = { size, region };
|
|
993
|
+
const snapshotMeta = typeof imageRef === "number" ? await c.getSnapshot(String(imageRef)) : null;
|
|
994
|
+
const sizeCatalog = await c.listSizes();
|
|
995
|
+
validateSizeChoice(choice, sizeCatalog, snapshotMeta);
|
|
996
|
+
const plan = sizeCatalog.find((s) => s.slug === size);
|
|
997
|
+
const inboundPolicy = parseInboundSpec(req.inbound);
|
|
998
|
+
const egressOverride = req.env?.AGENTBOX_DIGITALOCEAN_FIREWALL_SOURCE ?? process.env.AGENTBOX_DIGITALOCEAN_FIREWALL_SOURCE;
|
|
999
|
+
const hostEgress = inboundPolicy.mode === "open" ? null : egressOverride ? normalizeSourceCidr(egressOverride) : `${await detectEgressIp({ onLog })}/32`;
|
|
1000
|
+
const sources = resolveInboundSources(inboundPolicy, hostEgress);
|
|
1001
|
+
progress(`firewall inbound: ${describeInbound(inboundPolicy)} -> ${sources.join(", ")}`);
|
|
1002
|
+
const stamp = Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8);
|
|
1003
|
+
const tempDir = resolvePath(
|
|
1004
|
+
process.env.HOME ?? process.cwd(),
|
|
1005
|
+
".agentbox",
|
|
1006
|
+
"digitalocean",
|
|
1007
|
+
`pending-${stamp}`,
|
|
1008
|
+
"ssh"
|
|
1009
|
+
);
|
|
1010
|
+
const key = await mintSshKey(tempDir, `agentbox-box-${req.name}-${stamp}`);
|
|
1011
|
+
const boxTag = `agentbox-${sanitizeTag(req.name)}-${stamp}`;
|
|
1012
|
+
let firewallId = null;
|
|
1013
|
+
let dropletId = null;
|
|
1014
|
+
try {
|
|
1015
|
+
const firewall = await createPerBoxFirewall(c, {
|
|
1016
|
+
name: `agentbox-${sanitizeTag(req.name)}-${stamp}`,
|
|
1017
|
+
sources,
|
|
1018
|
+
tag: boxTag
|
|
1019
|
+
});
|
|
1020
|
+
firewallId = firewall.id;
|
|
1021
|
+
const boxEnv = cloudInitBoxEnv(req.env);
|
|
1022
|
+
const cloudInit = generateBoxCloudInit({
|
|
1023
|
+
sshPubkey: key.publicKey,
|
|
1024
|
+
boxName: req.name,
|
|
1025
|
+
boxEnv: Object.keys(boxEnv).length > 0 ? boxEnv : void 0
|
|
1026
|
+
});
|
|
1027
|
+
progress(`creating droplet '${req.name}' from image ${String(imageRef)} (${size} / ${region})`);
|
|
1028
|
+
let created;
|
|
1029
|
+
try {
|
|
1030
|
+
created = await withDigitalOceanRetry(
|
|
1031
|
+
{ method: "createDroplet", retryOnAmbiguous: false, attemptTimeoutMs: 12e4 },
|
|
1032
|
+
() => c.createDroplet({
|
|
1033
|
+
name: `agentbox-${sanitizeTag(req.name)}-${stamp}`,
|
|
1034
|
+
region,
|
|
1035
|
+
size,
|
|
1036
|
+
image: imageRef,
|
|
1037
|
+
user_data: cloudInit,
|
|
1038
|
+
tags: [boxTag, "agentbox"],
|
|
1039
|
+
ipv6: false
|
|
1040
|
+
})
|
|
1041
|
+
);
|
|
1042
|
+
} catch (createErr) {
|
|
1043
|
+
throw mapDigitalOceanProvisionError(createErr, choice);
|
|
1044
|
+
}
|
|
1045
|
+
dropletId = created.droplet.id;
|
|
1046
|
+
progress(`droplet ${String(dropletId)} created; waiting for it to boot`);
|
|
1047
|
+
const droplet = await pollUntil(
|
|
1048
|
+
`droplet ${String(dropletId)} active`,
|
|
1049
|
+
async () => {
|
|
1050
|
+
const d = await c.getDroplet(dropletId);
|
|
1051
|
+
return d && d.status === "active" && publicIpv4(d) ? d : null;
|
|
1052
|
+
},
|
|
1053
|
+
{ deadlineMs: PROVISION_DROPLET_DEADLINE_MS2, intervalMs: 3e3, maxIntervalMs: 1e4 }
|
|
1054
|
+
);
|
|
1055
|
+
const vpsIp = publicIpv4(droplet);
|
|
1056
|
+
if (!vpsIp) {
|
|
1057
|
+
throw new Error(`digitalocean: droplet ${String(dropletId)} came up without a public IPv4`);
|
|
1058
|
+
}
|
|
1059
|
+
progress(`droplet ${String(dropletId)} at ${vpsIp}; waiting for ssh`);
|
|
1060
|
+
const sandboxId = String(dropletId);
|
|
1061
|
+
const state = await ensurePerBoxState(sandboxId);
|
|
1062
|
+
await rename(key.privatePath, state.identity);
|
|
1063
|
+
await rename(key.publicPath, `${state.identity}.pub`);
|
|
1064
|
+
await rm2(key.dir, { recursive: true, force: true });
|
|
1065
|
+
const pendingParent = resolvePath(key.dir, "..");
|
|
1066
|
+
await rm2(pendingParent, { recursive: true, force: true });
|
|
1067
|
+
const up = await waitForSsh(buildSshTarget(state, vpsIp), PROVISION_SSH_DEADLINE_MS);
|
|
1068
|
+
if (!up) {
|
|
1069
|
+
throw new Error(
|
|
1070
|
+
`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).`
|
|
1071
|
+
);
|
|
1072
|
+
}
|
|
1073
|
+
await ensureTunnel(sandboxId, state, vpsIp);
|
|
1074
|
+
progress("ssh up; ControlMaster open");
|
|
1075
|
+
return plan ? {
|
|
1076
|
+
sandboxId,
|
|
1077
|
+
inbound: inboundPolicy,
|
|
1078
|
+
resources: {
|
|
1079
|
+
cpu: plan.vcpus,
|
|
1080
|
+
memory: Math.round(plan.memory / 1024),
|
|
1081
|
+
disk: plan.disk
|
|
1082
|
+
}
|
|
1083
|
+
} : { sandboxId, inbound: inboundPolicy };
|
|
1084
|
+
} catch (err) {
|
|
1085
|
+
if (dropletId !== null) {
|
|
1086
|
+
progress(`cleanup \u2014 deleting droplet ${String(dropletId)} after provision failure`);
|
|
1087
|
+
try {
|
|
1088
|
+
await c.deleteDroplet(dropletId);
|
|
1089
|
+
} catch (cleanupErr) {
|
|
1090
|
+
onLog(
|
|
1091
|
+
`digitalocean: WARN \u2014 failed to delete droplet ${String(dropletId)}; check the DigitalOcean dashboard. ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`
|
|
1092
|
+
);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
if (firewallId !== null) {
|
|
1096
|
+
try {
|
|
1097
|
+
await deletePerBoxFirewall(c, firewallId, { tags: [boxTag] });
|
|
1098
|
+
} catch {
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
try {
|
|
1102
|
+
if (existsSync2(key.dir)) await rm2(key.dir, { recursive: true, force: true });
|
|
1103
|
+
if (dropletId !== null) {
|
|
1104
|
+
const finalDir = perBoxDir(String(dropletId));
|
|
1105
|
+
if (existsSync2(finalDir)) await rm2(finalDir, { recursive: true, force: true });
|
|
1106
|
+
}
|
|
1107
|
+
} catch {
|
|
1108
|
+
}
|
|
1109
|
+
throw err;
|
|
1110
|
+
}
|
|
1111
|
+
},
|
|
1112
|
+
async get(sandboxId) {
|
|
1113
|
+
const id = Number.parseInt(sandboxId, 10);
|
|
1114
|
+
if (!Number.isFinite(id)) return null;
|
|
1115
|
+
const droplet = await client().getDroplet(id);
|
|
1116
|
+
return droplet ? { sandboxId } : null;
|
|
1117
|
+
},
|
|
1118
|
+
async list() {
|
|
1119
|
+
const droplets = await client().listDroplets({ tag_name: "agentbox" });
|
|
1120
|
+
return droplets.map((d) => ({
|
|
1121
|
+
sandboxId: String(d.id),
|
|
1122
|
+
name: d.name,
|
|
1123
|
+
createdAt: d.created_at,
|
|
1124
|
+
state: mapState(d.status)
|
|
1125
|
+
}));
|
|
1126
|
+
},
|
|
1127
|
+
async start(h) {
|
|
1128
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1129
|
+
const c = client();
|
|
1130
|
+
const action = await c.powerOn(id);
|
|
1131
|
+
await waitAction(c, action.id, `droplet ${h.sandboxId} power_on`, ACTION_DEADLINE_MS);
|
|
1132
|
+
const droplet = await pollUntil(
|
|
1133
|
+
`droplet ${h.sandboxId} active`,
|
|
1134
|
+
async () => {
|
|
1135
|
+
const d = await c.getDroplet(id);
|
|
1136
|
+
return d && d.status === "active" && publicIpv4(d) ? d : null;
|
|
1137
|
+
},
|
|
1138
|
+
{ deadlineMs: ACTION_DEADLINE_MS, intervalMs: 2e3, maxIntervalMs: 8e3 }
|
|
1139
|
+
);
|
|
1140
|
+
const vpsIp = publicIpv4(droplet);
|
|
1141
|
+
if (!vpsIp) {
|
|
1142
|
+
throw new Error(`digitalocean: droplet ${h.sandboxId} has no public IPv4 after start`);
|
|
1143
|
+
}
|
|
1144
|
+
const state = await ensurePerBoxState(h.sandboxId);
|
|
1145
|
+
const up = await waitForSsh(buildSshTarget(state, vpsIp), PROVISION_SSH_DEADLINE_MS);
|
|
1146
|
+
if (!up) {
|
|
1147
|
+
throw new Error(
|
|
1148
|
+
`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).`
|
|
1149
|
+
);
|
|
1150
|
+
}
|
|
1151
|
+
},
|
|
1152
|
+
async stop(h) {
|
|
1153
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1154
|
+
const c = client();
|
|
1155
|
+
try {
|
|
1156
|
+
const action = await c.shutdown(id);
|
|
1157
|
+
await waitAction(c, action.id, `droplet ${h.sandboxId} shutdown`, 9e4);
|
|
1158
|
+
} catch {
|
|
1159
|
+
const action = await c.powerOff(id);
|
|
1160
|
+
await waitAction(c, action.id, `droplet ${h.sandboxId} power_off`, ACTION_DEADLINE_MS);
|
|
1161
|
+
}
|
|
1162
|
+
await tunnels.close(h.sandboxId);
|
|
1163
|
+
},
|
|
1164
|
+
async pause(h) {
|
|
1165
|
+
await this.stop(h);
|
|
1166
|
+
},
|
|
1167
|
+
async resume(h) {
|
|
1168
|
+
await this.start(h);
|
|
1169
|
+
},
|
|
1170
|
+
async setInbound(h, policy) {
|
|
1171
|
+
const c = client();
|
|
1172
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1173
|
+
const droplet = await getDropletStrict(id);
|
|
1174
|
+
const fw = await findFirewallForDroplet(c, id, droplet.tags ?? []);
|
|
1175
|
+
if (!fw) {
|
|
1176
|
+
throw new Error(`digitalocean: no per-box firewall found for droplet ${h.sandboxId}`);
|
|
1177
|
+
}
|
|
1178
|
+
const hostEgress = policy.mode === "open" ? null : `${await detectEgressIp({})}/32`;
|
|
1179
|
+
const sources = resolveInboundSources(policy, hostEgress);
|
|
1180
|
+
await syncFirewallSource(c, fw, sources);
|
|
1181
|
+
return { sources };
|
|
1182
|
+
},
|
|
1183
|
+
async repairReachability(h) {
|
|
1184
|
+
const c = client();
|
|
1185
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1186
|
+
const droplet = await c.getDroplet(id).catch(() => null);
|
|
1187
|
+
if (!droplet) return { changed: false };
|
|
1188
|
+
const policy = h.inbound ?? { mode: "locked", sources: [] };
|
|
1189
|
+
if (policy.mode === "open") return { changed: false };
|
|
1190
|
+
const fw = await findFirewallForDroplet(c, id, droplet.tags ?? []).catch(() => null);
|
|
1191
|
+
if (!fw) return { changed: false };
|
|
1192
|
+
const allowed = fw.inbound_rules.find((r) => r.ports === "22")?.sources.addresses ?? [];
|
|
1193
|
+
if (allowed.includes("0.0.0.0/0")) return { changed: false };
|
|
1194
|
+
const currentEgress = `${await detectEgressIp({})}/32`;
|
|
1195
|
+
if (allowed.includes(currentEgress)) return { changed: false };
|
|
1196
|
+
const sources = resolveInboundSources(policy, currentEgress);
|
|
1197
|
+
await syncFirewallSource(c, fw, sources);
|
|
1198
|
+
return {
|
|
1199
|
+
changed: true,
|
|
1200
|
+
detail: `firewall updated: SSH now allowed from ${sources.join(", ")} (was ${allowed.join(", ") || "(no rule)"})`
|
|
1201
|
+
};
|
|
1202
|
+
},
|
|
1203
|
+
async destroy(h) {
|
|
1204
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1205
|
+
await tunnels.close(h.sandboxId);
|
|
1206
|
+
const c = client();
|
|
1207
|
+
let firewallId;
|
|
1208
|
+
let firewallTags;
|
|
1209
|
+
try {
|
|
1210
|
+
const droplet = await c.getDroplet(id);
|
|
1211
|
+
if (droplet) {
|
|
1212
|
+
const fw = await findFirewallForDroplet(c, id, droplet.tags);
|
|
1213
|
+
firewallId = fw?.id;
|
|
1214
|
+
firewallTags = fw?.tags;
|
|
1215
|
+
}
|
|
1216
|
+
} catch {
|
|
1217
|
+
}
|
|
1218
|
+
try {
|
|
1219
|
+
await c.deleteDroplet(id);
|
|
1220
|
+
} catch (err) {
|
|
1221
|
+
if (!(err instanceof DigitalOceanApiError && (err.statusCode === 404 || err.code === "not_found"))) {
|
|
1222
|
+
throw err;
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
if (firewallId) {
|
|
1226
|
+
await deletePerBoxFirewall(c, firewallId, { tags: firewallTags });
|
|
1227
|
+
}
|
|
1228
|
+
const dir = perBoxDir(h.sandboxId);
|
|
1229
|
+
try {
|
|
1230
|
+
await rm2(dir, { recursive: true, force: true });
|
|
1231
|
+
} catch {
|
|
1232
|
+
}
|
|
1233
|
+
},
|
|
1234
|
+
async state(h) {
|
|
1235
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1236
|
+
const d = await client().getDroplet(id);
|
|
1237
|
+
return d ? mapState(d.status) : "missing";
|
|
1238
|
+
},
|
|
1239
|
+
async exec(h, cmd, opts) {
|
|
1240
|
+
const { target } = await ensureLiveTarget(h.sandboxId);
|
|
1241
|
+
const argv = [
|
|
1242
|
+
...sshOptArgs(target),
|
|
1243
|
+
`${target.user}@${target.host}`,
|
|
1244
|
+
bashScript(opts?.cwd ? `cd ${shellQuote(opts.cwd)} && ${cmd}` : cmd)
|
|
1245
|
+
];
|
|
1246
|
+
const res = await execa3("ssh", argv, {
|
|
1247
|
+
reject: false,
|
|
1248
|
+
timeout: opts?.attemptTimeoutMs ?? 12e4,
|
|
1249
|
+
env: { ...process.env, ...opts?.env ?? {} }
|
|
1250
|
+
});
|
|
1251
|
+
return {
|
|
1252
|
+
exitCode: typeof res.exitCode === "number" ? res.exitCode : 1,
|
|
1253
|
+
stdout: typeof res.stdout === "string" ? res.stdout : "",
|
|
1254
|
+
stderr: typeof res.stderr === "string" ? res.stderr : ""
|
|
1255
|
+
};
|
|
1256
|
+
},
|
|
1257
|
+
async uploadFile(h, localPath, remotePath) {
|
|
1258
|
+
const { target } = await ensureLiveTarget(h.sandboxId);
|
|
1259
|
+
const argv = [...sshOptArgs(target), localPath, `${target.user}@${target.host}:${remotePath}`];
|
|
1260
|
+
const res = await execa3("scp", argv, { reject: false, timeout: 3e5 });
|
|
1261
|
+
if (res.exitCode !== 0) {
|
|
1262
|
+
throw new Error(`digitalocean: scp upload failed (exit ${String(res.exitCode)}): ${res.stderr || ""}`);
|
|
1263
|
+
}
|
|
1264
|
+
},
|
|
1265
|
+
async downloadFile(h, remotePath, localPath) {
|
|
1266
|
+
const { target } = await ensureLiveTarget(h.sandboxId);
|
|
1267
|
+
const argv = [...sshOptArgs(target), `${target.user}@${target.host}:${remotePath}`, localPath];
|
|
1268
|
+
const res = await execa3("scp", argv, { reject: false, timeout: 3e5 });
|
|
1269
|
+
if (res.exitCode !== 0) {
|
|
1270
|
+
throw new Error(`digitalocean: scp download failed (exit ${String(res.exitCode)}): ${res.stderr || ""}`);
|
|
1271
|
+
}
|
|
1272
|
+
},
|
|
1273
|
+
async listFiles(h, remoteDir) {
|
|
1274
|
+
const res = await this.exec(
|
|
1275
|
+
h,
|
|
1276
|
+
`find ${shellQuote(remoteDir)} -mindepth 1 -maxdepth 1 -printf '%f\\t%y\\n'`
|
|
1277
|
+
);
|
|
1278
|
+
if (res.exitCode !== 0) return [];
|
|
1279
|
+
return res.stdout.split(/\r?\n/).filter((line) => line.length > 0).map((line) => {
|
|
1280
|
+
const [name, kind] = line.split(" ");
|
|
1281
|
+
return { name: name ?? line, isDir: kind === "d" };
|
|
1282
|
+
});
|
|
1283
|
+
},
|
|
1284
|
+
async previewUrl(h, port) {
|
|
1285
|
+
await ensureLiveTarget(h.sandboxId);
|
|
1286
|
+
const localPort = await tunnels.forward(h.sandboxId, port);
|
|
1287
|
+
return { url: `http://127.0.0.1:${String(localPort)}` };
|
|
1288
|
+
},
|
|
1289
|
+
async signedPreviewUrl(h, port, _ttl) {
|
|
1290
|
+
void _ttl;
|
|
1291
|
+
return this.previewUrl(h, port);
|
|
1292
|
+
},
|
|
1293
|
+
async refreshPreviewUrl(h, port) {
|
|
1294
|
+
const { state, vpsIp } = await ensureLiveTarget(h.sandboxId);
|
|
1295
|
+
await tunnels.refresh({
|
|
1296
|
+
boxId: h.sandboxId,
|
|
1297
|
+
vpsHost: vpsIp,
|
|
1298
|
+
identity: state.identity
|
|
1299
|
+
});
|
|
1300
|
+
const localPort = await tunnels.forward(h.sandboxId, port);
|
|
1301
|
+
return { url: `http://127.0.0.1:${String(localPort)}` };
|
|
1302
|
+
},
|
|
1303
|
+
async startInBoxPortless(h, opts) {
|
|
1304
|
+
const tlsFlag = opts.tls ? "" : "--no-tls";
|
|
1305
|
+
const startCmd = `sudo portless proxy start ${tlsFlag} -p ${String(opts.proxyPort)}`.replace(/\s+/g, " ");
|
|
1306
|
+
const aliasCmd = `sudo portless alias ${shellQuote(opts.boxName)} ${String(opts.webPort)}`;
|
|
1307
|
+
const cmds = [startCmd, aliasCmd];
|
|
1308
|
+
if (opts.tls) {
|
|
1309
|
+
cmds.push(
|
|
1310
|
+
"sudo agentbox-portless-trust /root/.portless/ca.pem >/dev/null 2>&1 || true",
|
|
1311
|
+
`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`
|
|
1312
|
+
);
|
|
1313
|
+
}
|
|
1314
|
+
await this.exec(h, cmds.join("; "));
|
|
1315
|
+
},
|
|
1316
|
+
async attachArgv(h) {
|
|
1317
|
+
const { target } = await ensureLiveTarget(h.sandboxId);
|
|
1318
|
+
return ["ssh", ...sshOptArgs(target), `${target.user}@${target.host}`];
|
|
1319
|
+
},
|
|
1320
|
+
async createSnapshot(h, name) {
|
|
1321
|
+
const id = Number.parseInt(h.sandboxId, 10);
|
|
1322
|
+
const c = client();
|
|
1323
|
+
const action = await withDigitalOceanRetry(
|
|
1324
|
+
{ method: "snapshotDroplet", retryOnAmbiguous: false, attemptTimeoutMs: 12e4 },
|
|
1325
|
+
() => c.snapshotDroplet(id, name)
|
|
1326
|
+
);
|
|
1327
|
+
await waitAction(c, action.id, `droplet ${h.sandboxId} snapshot`, SNAPSHOT_DEADLINE_MS2);
|
|
1328
|
+
},
|
|
1329
|
+
async deleteSnapshot(name) {
|
|
1330
|
+
const c = client();
|
|
1331
|
+
const snap = (await c.listSnapshots()).find((s) => s.name === name);
|
|
1332
|
+
if (!snap) return;
|
|
1333
|
+
try {
|
|
1334
|
+
await c.deleteSnapshot(snap.id);
|
|
1335
|
+
} catch (err) {
|
|
1336
|
+
if (err instanceof DigitalOceanApiError && (err.statusCode === 404 || err.code === "not_found")) return;
|
|
1337
|
+
throw err;
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
};
|
|
1341
|
+
function readCredStatusSummary() {
|
|
1342
|
+
return { configured: readDigitalOceanCredStatus().source !== "none" };
|
|
1343
|
+
}
|
|
1344
|
+
async function doctorChecks() {
|
|
1345
|
+
try {
|
|
1346
|
+
const cred = readDigitalOceanCredStatus();
|
|
1347
|
+
const credRes = cred.source === "none" ? {
|
|
1348
|
+
label: "credentials",
|
|
1349
|
+
status: "warn",
|
|
1350
|
+
detail: "DIGITALOCEAN_TOKEN not set",
|
|
1351
|
+
hint: "`agentbox digitalocean login`"
|
|
1352
|
+
} : { label: "credentials", status: "ok", detail: `token from ${cred.source}` };
|
|
1353
|
+
const prepared = readPreparedState();
|
|
1354
|
+
const snapRes = prepared.base?.imageId ? {
|
|
1355
|
+
label: "base snapshot",
|
|
1356
|
+
status: "ok",
|
|
1357
|
+
detail: `snapshot ${String(prepared.base.imageId)} (${prepared.base.cliVersion ?? "\u2014"})`
|
|
1358
|
+
} : {
|
|
1359
|
+
label: "base snapshot",
|
|
1360
|
+
status: "warn",
|
|
1361
|
+
detail: "not baked",
|
|
1362
|
+
hint: "`agentbox prepare --provider digitalocean`"
|
|
1363
|
+
};
|
|
1364
|
+
const portlessRes = portlessDoctorRow(await detectPortless());
|
|
1365
|
+
return [credRes, snapRes, portlessRes];
|
|
1366
|
+
} catch (err) {
|
|
1367
|
+
return [{ label: "credentials", status: "warn", detail: errSummary(err) }];
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
var cloudProvider = createCloudProvider(digitaloceanBackend, {
|
|
1371
|
+
// s-2vcpu-4gb = 2 vCPU / 4 GB / 80 GB SSD.
|
|
1372
|
+
defaultResources: { cpu: 2, memory: 4, disk: 80 }
|
|
1373
|
+
});
|
|
1374
|
+
var digitaloceanProvider = {
|
|
1375
|
+
...cloudProvider,
|
|
1376
|
+
prepare: prepareDigitalOceanProvider,
|
|
1377
|
+
baseFingerprint: () => currentDigitalOceanBaseFingerprintLive()
|
|
1378
|
+
};
|
|
1379
|
+
var providerModule = {
|
|
1380
|
+
provider: digitaloceanProvider,
|
|
1381
|
+
backend: digitaloceanBackend,
|
|
1382
|
+
ensureCredentials: ensureDigitalOceanCredentials,
|
|
1383
|
+
readCredStatus: readCredStatusSummary,
|
|
1384
|
+
setCredentials: setDigitalOceanCredentials,
|
|
1385
|
+
currentBaseFingerprintLive: (claudeInstall) => currentDigitalOceanBaseFingerprintLive(claudeInstall),
|
|
1386
|
+
doctorChecks
|
|
1387
|
+
};
|
|
1388
|
+
export {
|
|
1389
|
+
DEFAULT_DO_ENDPOINT,
|
|
1390
|
+
DIGITALOCEAN_DEFAULT_BOX_IMAGE_REF,
|
|
1391
|
+
DigitalOceanApiError,
|
|
1392
|
+
RUNTIME_ASSETS,
|
|
1393
|
+
allowAllOutboundRules,
|
|
1394
|
+
candidatesFor,
|
|
1395
|
+
createPerBoxFirewall,
|
|
1396
|
+
currentDigitalOceanBaseFingerprintLive,
|
|
1397
|
+
deletePerBoxFirewall,
|
|
1398
|
+
detectEgressIp,
|
|
1399
|
+
digitaloceanBackend,
|
|
1400
|
+
digitaloceanProvider,
|
|
1401
|
+
ensureDigitalOceanBaseSnapshot,
|
|
1402
|
+
ensureDigitalOceanCredentials,
|
|
1403
|
+
ensureDigitalOceanEnvLoaded,
|
|
1404
|
+
findFirewallForDroplet,
|
|
1405
|
+
generateBoxCloudInit,
|
|
1406
|
+
generatePrepareCloudInit,
|
|
1407
|
+
isAttemptTimeout,
|
|
1408
|
+
isRetriable,
|
|
1409
|
+
makeDigitalOceanClient,
|
|
1410
|
+
mapDigitalOceanProvisionError,
|
|
1411
|
+
maskKey,
|
|
1412
|
+
mintPrepareKey,
|
|
1413
|
+
mintSshKey,
|
|
1414
|
+
normalizeSourceCidr,
|
|
1415
|
+
pollUntil,
|
|
1416
|
+
prepareDigitalOcean,
|
|
1417
|
+
prepareDigitalOceanProvider,
|
|
1418
|
+
preparedStatePath,
|
|
1419
|
+
providerModule,
|
|
1420
|
+
readDigitalOceanCredStatus,
|
|
1421
|
+
readPreparedState,
|
|
1422
|
+
resolveRuntimeAssets,
|
|
1423
|
+
scpDownload,
|
|
1424
|
+
scpUpload,
|
|
1425
|
+
secretsPath,
|
|
1426
|
+
setDigitalOceanCredentials,
|
|
1427
|
+
sshExec,
|
|
1428
|
+
sshInboundRules,
|
|
1429
|
+
sshOptArgs,
|
|
1430
|
+
syncFirewallSource,
|
|
1431
|
+
updatePreparedState,
|
|
1432
|
+
validateSizeChoice,
|
|
1433
|
+
waitForSsh,
|
|
1434
|
+
withDigitalOceanRetry,
|
|
1435
|
+
writePreparedState
|
|
1436
|
+
};
|
|
1437
|
+
//# sourceMappingURL=dist-3KIJ2KQ2.js.map
|