@madarco/agentbox 0.24.3 → 0.24.5
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 +22 -0
- package/dist/{_cloud-attach-D5OC7DCC.js → _cloud-attach-ESCPOKG5.js} +5 -5
- package/dist/{chunk-DEDTPG2D.js → chunk-3MDYQROX.js} +5 -5
- package/dist/{chunk-SS6ZEKLL.js → chunk-4HPLS5HJ.js} +7 -4
- package/dist/chunk-4HPLS5HJ.js.map +1 -0
- package/dist/{chunk-3253DDXI.js → chunk-5JDOTQTM.js} +4 -4
- package/dist/{chunk-5KHEH47T.js → chunk-7DPDUZ7L.js} +2 -2
- package/dist/{chunk-24PXPJI3.js → chunk-CE3S7UDQ.js} +10 -10
- package/dist/chunk-G3H2L3O2.js +0 -0
- package/dist/{chunk-UIRBYL4G.js → chunk-H6A4BQMG.js} +9 -1
- package/dist/chunk-H6A4BQMG.js.map +1 -0
- package/dist/{chunk-WLHJZPFJ.js → chunk-LJMGHFLZ.js} +152 -3
- package/dist/chunk-LJMGHFLZ.js.map +1 -0
- package/dist/{chunk-5WF7PAH2.js → chunk-OSPM4Q5V.js} +3 -3
- package/dist/{chunk-QMA3DB5L.js → chunk-QHISF6O6.js} +3 -3
- package/dist/{chunk-LC4E2EIZ.js → chunk-RFRWS5CD.js} +2 -2
- package/dist/chunk-WJFZJZIM.js +0 -0
- package/dist/cloud-poller-SUNA6ZQC-7M5LJHHE.js +0 -0
- package/dist/{dist-UWUTNRCK.js → dist-2N3XHMBQ.js} +6 -6
- package/dist/{dist-FWB3MIQ5.js → dist-3M53BF4E.js} +39 -58
- package/dist/dist-3M53BF4E.js.map +1 -0
- package/dist/{dist-TK3STVUP.js → dist-FGXCG4JY.js} +6 -6
- package/dist/{dist-T5MXBZGP.js → dist-HPPHBZTO.js} +2 -2
- package/dist/{dist-2JWYYJZR.js → dist-NOUPH5E6.js} +4 -4
- package/dist/{dist-3NFY6M53.js → dist-TRKHS6I7.js} +6 -6
- package/dist/{dist-72EYR5DW.js → dist-VFPT5TDH.js} +6 -6
- package/dist/index.js +116 -90
- package/dist/index.js.map +1 -1
- package/dist/{prepared-state-BUO75YLZ-RQRFFBJW.js → prepared-state-BUO75YLZ-46W2PAHH.js} +2 -2
- package/package.json +29 -28
- package/runtime/_shared/agentbox-checkpoint-cleanup +0 -0
- 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 +8 -0
- package/runtime/_shared/gh-shim +0 -0
- package/runtime/_shared/git-shim +0 -0
- package/runtime/_shared/linear-shim +0 -0
- package/runtime/_shared/ntn-shim +0 -0
- package/runtime/digitalocean/agentbox-checkpoint-cleanup +0 -0
- package/runtime/digitalocean/agentbox-dockerd-start +0 -0
- package/runtime/digitalocean/agentbox-open +0 -0
- package/runtime/digitalocean/agentbox-portless-trust +0 -0
- package/runtime/digitalocean/agentbox-vnc-start +0 -0
- package/runtime/digitalocean/ctl.cjs +8 -0
- package/runtime/digitalocean/gh-shim +0 -0
- package/runtime/digitalocean/git-shim +0 -0
- package/runtime/digitalocean/linear-shim +0 -0
- package/runtime/digitalocean/ntn-shim +0 -0
- package/runtime/digitalocean/scripts/install-box.sh +0 -0
- package/runtime/docker/packages/ctl/dist/bin.cjs +8 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup +0 -0
- 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/gh-shim +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/git-shim +0 -0
- 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-dockerd-start +0 -0
- package/runtime/e2b/agentbox-open +0 -0
- package/runtime/e2b/agentbox-vnc-start +0 -0
- package/runtime/e2b/ctl.cjs +8 -0
- package/runtime/e2b/gh-shim +0 -0
- package/runtime/e2b/git-shim +0 -0
- package/runtime/e2b/linear-shim +0 -0
- package/runtime/e2b/ntn-shim +0 -0
- package/runtime/e2b/scripts/build-template.sh +0 -0
- package/runtime/hetzner/agentbox-checkpoint-cleanup +0 -0
- 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 +8 -0
- package/runtime/hetzner/gh-shim +0 -0
- package/runtime/hetzner/git-shim +0 -0
- package/runtime/hetzner/linear-shim +0 -0
- package/runtime/hetzner/ntn-shim +0 -0
- package/runtime/hetzner/scripts/install-box.sh +0 -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)/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 +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0760z6y._.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/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/1z4elhg8gyq98.js +1 -0
- package/runtime/hub/apps/hub/{auth-Q447765C.js → auth-HY5K55Y5.js} +2 -2
- package/runtime/hub/apps/hub/{auth-config-SIL635ZD.js → auth-config-MNW2XGKK.js} +2 -2
- package/runtime/hub/apps/hub/{chunk-OJAHNFNV.js → chunk-5KMJIVZC.js} +6 -3
- package/runtime/hub/apps/hub/{chunk-IRIK4DQF.js → chunk-DNR2YM2G.js} +2 -2
- package/runtime/hub/apps/hub/{chunk-3VE7AYVK.js → chunk-EY6HEDTK.js} +4 -4
- package/runtime/hub/apps/hub/{chunk-DZPQB2JZ.js → chunk-PROXBLRJ.js} +1 -1
- package/runtime/hub/apps/hub/{chunk-64WEKO34.js → chunk-TRUQCO4U.js} +8 -0
- package/runtime/hub/apps/hub/{dist-PWBKGUDG.js → dist-3DCKZYID.js} +4 -4
- package/runtime/hub/apps/hub/{dist-6AEQJL7W.js → dist-KV5ESR24.js} +4 -4
- package/runtime/hub/apps/hub/{dist-PRUR2E5L.js → dist-M73U3ZDH.js} +4 -4
- package/runtime/hub/apps/hub/{dist-GF5EBRNG.js → dist-NTKPAYA3.js} +1 -1
- package/runtime/hub/apps/hub/{dist-7GTRUGLC.js → dist-RSWTJWRN.js} +3 -3
- package/runtime/hub/apps/hub/{dist-HHHK5LRX.js → dist-SX2NXGI6.js} +177 -57
- package/runtime/hub/apps/hub/{dist-DLPVQMKD.js → dist-YCRESLWD.js} +4 -4
- package/runtime/hub/apps/hub/{hub-token-UITZEWVP.js → hub-token-QKQWV2I6.js} +2 -2
- package/runtime/hub/apps/hub/{prepared-state-BUO75YLZ-O4GZMDRF.js → prepared-state-BUO75YLZ-KR4YLKDC.js} +1 -1
- package/runtime/hub/apps/hub/server.js +15 -15
- package/runtime/relay/bin.cjs +8 -0
- package/runtime/vercel/agentbox-checkpoint-cleanup +0 -0
- 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 +8 -0
- package/runtime/vercel/gh-shim +0 -0
- package/runtime/vercel/git-shim +0 -0
- package/runtime/vercel/linear-shim +0 -0
- package/runtime/vercel/ntn-shim +0 -0
- package/runtime/vercel/scripts/provision.sh +0 -0
- package/LICENSE +0 -21
- package/dist/chunk-SS6ZEKLL.js.map +0 -1
- package/dist/chunk-UIRBYL4G.js.map +0 -1
- package/dist/chunk-WLHJZPFJ.js.map +0 -1
- package/dist/dist-FWB3MIQ5.js.map +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/380qcmusmigzz.js +0 -1
- /package/dist/{_cloud-attach-D5OC7DCC.js.map → _cloud-attach-ESCPOKG5.js.map} +0 -0
- /package/dist/{chunk-DEDTPG2D.js.map → chunk-3MDYQROX.js.map} +0 -0
- /package/dist/{chunk-3253DDXI.js.map → chunk-5JDOTQTM.js.map} +0 -0
- /package/dist/{chunk-5KHEH47T.js.map → chunk-7DPDUZ7L.js.map} +0 -0
- /package/dist/{chunk-24PXPJI3.js.map → chunk-CE3S7UDQ.js.map} +0 -0
- /package/dist/{chunk-5WF7PAH2.js.map → chunk-OSPM4Q5V.js.map} +0 -0
- /package/dist/{chunk-QMA3DB5L.js.map → chunk-QHISF6O6.js.map} +0 -0
- /package/dist/{chunk-LC4E2EIZ.js.map → chunk-RFRWS5CD.js.map} +0 -0
- /package/dist/{dist-UWUTNRCK.js.map → dist-2N3XHMBQ.js.map} +0 -0
- /package/dist/{dist-TK3STVUP.js.map → dist-FGXCG4JY.js.map} +0 -0
- /package/dist/{dist-2JWYYJZR.js.map → dist-HPPHBZTO.js.map} +0 -0
- /package/dist/{dist-3NFY6M53.js.map → dist-NOUPH5E6.js.map} +0 -0
- /package/dist/{dist-72EYR5DW.js.map → dist-TRKHS6I7.js.map} +0 -0
- /package/dist/{dist-T5MXBZGP.js.map → dist-VFPT5TDH.js.map} +0 -0
- /package/dist/{prepared-state-BUO75YLZ-RQRFFBJW.js.map → prepared-state-BUO75YLZ-46W2PAHH.js.map} +0 -0
- /package/runtime/hub/apps/hub/.next/static/{4CStLAgdl_oxCRh8votRw → 43_nml7FKErUxJXpspAhb}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{4CStLAgdl_oxCRh8votRw → 43_nml7FKErUxJXpspAhb}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{4CStLAgdl_oxCRh8votRw → 43_nml7FKErUxJXpspAhb}/_ssgManifest.js +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../packages/sandbox-digitalocean/src/env-loader.ts","../../../packages/sandbox-digitalocean/src/client.ts","../../../packages/sandbox-digitalocean/src/preflight.ts","../../../packages/sandbox-digitalocean/src/credentials.ts","../../../packages/sandbox-digitalocean/src/egress-ip.ts","../../../packages/sandbox-digitalocean/src/retry.ts","../../../packages/sandbox-digitalocean/src/firewall.ts","../../../packages/sandbox-digitalocean/src/runtime-assets.ts","../../../packages/sandbox-digitalocean/src/prepared-state.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\n\n/**\n * DigitalOcean env auto-loader — mirrors `ensureDaytonaEnvLoaded()`. The DigitalOcean\n * REST client reads `DIGITALOCEAN_TOKEN` from `process.env`. We pull it in from\n * `~/.agentbox/secrets.env` so the client Just Works after the user runs\n * `agentbox digitalocean login` once.\n *\n * Lookup order (first wins; process.env is never overwritten):\n * 1. `process.env` (already set in the shell).\n * 2. `~/.agentbox/secrets.env` — written by `agentbox digitalocean login`.\n *\n * Project-level `.env` / `.env.local` are intentionally NOT consulted: those\n * files belong to the app code being developed, and a `DIGITALOCEAN_TOKEN` there\n * is typically meant for in-box infrastructure work, not for the host CLI to\n * harvest and provision Droplets with.\n *\n * Only DigitalOcean-prefixed keys are imported. Idempotent + side-effect-free\n * after the first call.\n */\nconst DIGITALOCEAN_KEYS = ['DIGITALOCEAN_TOKEN', 'DIGITALOCEAN_API_URL'] as const;\n\nlet loaded = false;\n\nexport function ensureDigitalOceanEnvLoaded(): void {\n if (loaded) return;\n loaded = true;\n importDigitalOceanFromFile(resolve(homedir(), '.agentbox', 'secrets.env'));\n}\n\nfunction importDigitalOceanFromFile(path: string): void {\n if (!existsSync(path)) return;\n let body: string;\n try {\n body = readFileSync(path, 'utf8');\n } catch {\n return;\n }\n const parsed = parseEnvFile(body);\n for (const key of DIGITALOCEAN_KEYS) {\n if (process.env[key] !== undefined) continue;\n const value = parsed[key];\n if (typeof value === 'string') {\n process.env[key] = value;\n }\n }\n}\n\n/**\n * Minimal `.env` parser: handles `KEY=value`, `KEY=\"value with spaces\"`,\n * `KEY='value with $special chars'`, `export KEY=value`, blank lines, and\n * `#` comments. Same shape as the daytona env-loader's parser — kept local\n * here rather than imported across packages to avoid the cycle (daytona\n * doesn't import from digitalocean and shouldn't start now).\n */\nexport function parseEnvFile(body: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const rawLine of body.split(/\\r?\\n/)) {\n const line = rawLine.trim();\n if (line.length === 0 || line.startsWith('#')) continue;\n const stripped = line.startsWith('export ') ? line.slice('export '.length) : line;\n const eq = stripped.indexOf('=');\n if (eq <= 0) continue;\n const key = stripped.slice(0, eq).trim();\n let value = stripped.slice(eq + 1).trim();\n if (\n value.length >= 2 &&\n ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\")))\n ) {\n value = value.slice(1, -1);\n }\n out[key] = value;\n }\n return out;\n}\n","/**\n * DigitalOcean API v2 REST client — hand-rolled fetch wrapper.\n *\n * Why not an SDK: the subset of the API we need is small (droplets, droplet\n * actions, snapshots, firewalls, plus a cheap `account` lookup for token\n * validation). A hand-rolled client gives us strict typing of just the\n * fields we touch, no heavy dep tree, and full control over the retry\n * wrapper. Mirrors `sandbox-hetzner/src/client.ts` in shape.\n *\n * Auth: bearer token in `DIGITALOCEAN_TOKEN` env. The env-loader pulls it\n * from `~/.agentbox/secrets.env` so the user only sets it once via\n * `agentbox digitalocean login`.\n *\n * Errors: REST responses get unwrapped into typed `DigitalOceanApiError`s\n * that carry the response `status` + the API's `{ id, message }` body\n * (https://docs.digitalocean.com/reference/api/api-reference/#section/Introduction/Responses).\n * Network failures bubble up as raw `Error`s with a `code` property\n * (ECONNRESET, ETIMEDOUT, …) — the retry wrapper classifies both shapes.\n */\n\nimport { ensureDigitalOceanEnvLoaded } from './env-loader.js';\n\nexport const DEFAULT_DO_ENDPOINT = 'https://api.digitalocean.com/v2';\n\n/**\n * DigitalOcean Droplet lifecycle states. `new` = provisioning (no network\n * yet), `active` = running, `off` = powered off, `archive` = archived/locked.\n * Mapped in `backend.ts` to the four-value `CloudState` everyone else\n * consumes.\n */\nexport type DigitalOceanDropletStatus = 'new' | 'active' | 'off' | 'archive';\n\nexport interface DigitalOceanNetworkV4 {\n ip_address: string;\n netmask: string;\n gateway: string;\n type: 'public' | 'private';\n}\n\nexport interface DigitalOceanDroplet {\n id: number;\n name: string;\n status: DigitalOceanDropletStatus;\n created_at: string;\n networks: {\n v4: DigitalOceanNetworkV4[];\n v6: Array<{ ip_address: string; type: 'public' | 'private' }>;\n };\n image: { id: number; slug: string | null; distribution?: string; name?: string } | null;\n size_slug: string;\n region: { slug: string; name: string } | null;\n tags: string[];\n}\n\nexport interface DigitalOceanAction {\n id: number;\n status: 'in-progress' | 'completed' | 'errored';\n type: string;\n resource_id: number;\n resource_type: string;\n region_slug?: string;\n}\n\nexport interface DigitalOceanSnapshot {\n /** Snapshot id — a numeric *string* in DigitalOcean's API (e.g. \"119192817\"). */\n id: string;\n name: string;\n created_at: string;\n regions: string[];\n resource_id: string;\n resource_type: 'droplet';\n min_disk_size: number;\n size_gigabytes: number;\n}\n\n/**\n * A DigitalOcean Droplet size (plan), narrowed to the fields the create\n * preflight reads. `memory` is MB (DO reports it that way); `disk` is GB;\n * `regions` is the authoritative \"offered here\" list; `available` is false for\n * sold-out / retired plans. See GET /v2/sizes.\n */\nexport interface DigitalOceanSize {\n slug: string;\n memory: number;\n vcpus: number;\n disk: number;\n available: boolean;\n regions: string[];\n description?: string;\n}\n\n/**\n * A DigitalOcean Project — the account's resource-grouping unit (billing /\n * visibility). `id` is a UUID. Exactly one project has `is_default`, and every\n * resource lands there unless assigned elsewhere. See GET /v2/projects.\n */\nexport interface DigitalOceanProject {\n id: string;\n name: string;\n is_default: boolean;\n purpose?: string;\n environment?: string;\n}\n\n/**\n * A firewall rule's source (inbound) / destination (outbound) selector.\n * `addresses` accepts IPv4/IPv6 + CIDR; `tags` auto-includes droplets.\n */\nexport interface DigitalOceanFirewallEndpoint {\n addresses?: string[];\n droplet_ids?: number[];\n tags?: string[];\n load_balancer_uids?: string[];\n}\n\nexport interface DigitalOceanInboundRule {\n protocol: 'tcp' | 'udp' | 'icmp';\n /** Port range as a string (\"22\", \"1-65535\"). Omitted for icmp. */\n ports?: string;\n sources: DigitalOceanFirewallEndpoint;\n}\n\nexport interface DigitalOceanOutboundRule {\n protocol: 'tcp' | 'udp' | 'icmp';\n ports?: string;\n destinations: DigitalOceanFirewallEndpoint;\n}\n\nexport interface DigitalOceanFirewall {\n /** Firewall id — a UUID *string* in DigitalOcean's API. */\n id: string;\n name: string;\n status: 'waiting' | 'succeeded' | 'failed';\n inbound_rules: DigitalOceanInboundRule[];\n outbound_rules: DigitalOceanOutboundRule[];\n droplet_ids: number[];\n tags: string[];\n}\n\nexport interface CreateDropletRequest {\n name: string;\n region: string;\n size: string;\n /** Image slug (e.g. `ubuntu-24-04-x64`) or a numeric snapshot/image id. */\n image: string | number;\n user_data?: string;\n ssh_keys?: Array<string | number>;\n tags?: string[];\n ipv6?: boolean;\n backups?: boolean;\n}\n\nexport interface CreateFirewallRequest {\n name: string;\n inbound_rules: DigitalOceanInboundRule[];\n outbound_rules: DigitalOceanOutboundRule[];\n droplet_ids?: number[];\n tags?: string[];\n}\n\n/**\n * Strongly-typed DigitalOcean API error. The API returns `{ id, message,\n * request_id }` for 4xx/5xx. We unwrap that into this class so callers can\n * do `instanceof DigitalOceanApiError` and inspect `.code` (the API's `id`)\n * / `.statusCode` without parsing the body again.\n */\nexport class DigitalOceanApiError extends Error {\n readonly statusCode: number;\n readonly code: string;\n readonly requestId?: string;\n constructor(statusCode: number, code: string, message: string, requestId?: string) {\n super(`digitalocean ${String(statusCode)} ${code}: ${message}`);\n this.name = 'DigitalOceanApiError';\n this.statusCode = statusCode;\n this.code = code;\n this.requestId = requestId;\n }\n}\n\nexport interface DigitalOceanAccount {\n uuid: string;\n email: string;\n status: string;\n droplet_limit: number;\n}\n\n/**\n * Subset of the DigitalOcean API v2 the agentbox provider talks to. Methods\n * map 1:1 to REST endpoints; the retry wrapper around the provider methods\n * handles transient 5xx / 429 / connection failures.\n */\nexport interface DigitalOceanClient {\n /** GET /account — cheap auth-validation call for `agentbox digitalocean login`. */\n getAccount(): Promise<DigitalOceanAccount>;\n /** GET /droplets/{id}. Returns null on 404. */\n getDroplet(id: number): Promise<DigitalOceanDroplet | null>;\n /** POST /droplets. Returns the created droplet + the create-action id (if any). */\n createDroplet(req: CreateDropletRequest): Promise<{ droplet: DigitalOceanDroplet; actionId: number | null }>;\n /** GET /droplets (optionally filtered by a single tag). Paginates. */\n listDroplets(opts?: { tag_name?: string }): Promise<DigitalOceanDroplet[]>;\n /** DELETE /droplets/{id}. Idempotent on 404. */\n deleteDroplet(id: number): Promise<void>;\n /** POST /droplets/{id}/actions {type:'power_on'}. */\n powerOn(id: number): Promise<DigitalOceanAction>;\n /** POST /droplets/{id}/actions {type:'power_off'} — hard power off. */\n powerOff(id: number): Promise<DigitalOceanAction>;\n /** POST /droplets/{id}/actions {type:'shutdown'} — graceful ACPI shutdown. */\n shutdown(id: number): Promise<DigitalOceanAction>;\n /** POST /droplets/{id}/actions {type:'snapshot', name}. */\n snapshotDroplet(id: number, name: string): Promise<DigitalOceanAction>;\n /** GET /actions/{id}. Returns null on 404. */\n getAction(id: number): Promise<DigitalOceanAction | null>;\n /** GET /snapshots?resource_type=droplet. Paginates. */\n listSnapshots(): Promise<DigitalOceanSnapshot[]>;\n /** GET /snapshots/{id}. Returns null on 404. */\n getSnapshot(id: string): Promise<DigitalOceanSnapshot | null>;\n /** DELETE /snapshots/{id}. Idempotent on 404. */\n deleteSnapshot(id: string): Promise<void>;\n /** GET /sizes — the Droplet-plan catalog (paginated). Used by the create preflight. */\n listSizes(): Promise<DigitalOceanSize[]>;\n /** GET /projects — the account's projects (paginated). Used by the create preflight + login picker. */\n listProjects(): Promise<DigitalOceanProject[]>;\n /** GET /projects/default — the project resources land in when unassigned. Returns null on 404. */\n getDefaultProject(): Promise<DigitalOceanProject | null>;\n /**\n * POST /projects/{id}/resources — move resources into a project. DO has no\n * project field on droplet-create, so this is the only way in, and it can only\n * run once the droplet exists.\n */\n assignProjectResources(projectId: string, urns: string[]): Promise<void>;\n /** POST /firewalls. */\n createFirewall(req: CreateFirewallRequest): Promise<DigitalOceanFirewall>;\n /** GET /firewalls/{id}. Returns null on 404. */\n getFirewall(id: string): Promise<DigitalOceanFirewall | null>;\n /** GET /firewalls. Paginates. */\n listFirewalls(): Promise<DigitalOceanFirewall[]>;\n /** PUT /firewalls/{id}. Full replacement of the firewall's rules/name/tags. */\n updateFirewall(id: string, req: CreateFirewallRequest): Promise<DigitalOceanFirewall>;\n /** DELETE /firewalls/{id}. Idempotent on 404. */\n deleteFirewall(id: string): Promise<void>;\n /**\n * POST /tags — create a tag. DigitalOcean requires a tag to EXIST before it\n * can be referenced by a firewall or a droplet's `tags`, so the per-box\n * firewall flow creates its tag first. Idempotent: a 422 \"already exists\"\n * is swallowed (re-provision / retry safe).\n */\n createTag(name: string): Promise<void>;\n /** DELETE /tags/{name}. Idempotent on 404 (already gone). */\n deleteTag(name: string): Promise<void>;\n}\n\ninterface MakeClientOptions {\n /** Override the bearer token (else read from `DIGITALOCEAN_TOKEN`). */\n token?: string;\n /** Override the API base URL (else read from `DIGITALOCEAN_API_URL` or use the default). */\n endpoint?: string;\n /** Per-request fetch impl (tests inject this). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Build a DigitalOcean client bound to the current `DIGITALOCEAN_TOKEN`. The\n * token is resolved at construction time, so re-running `agentbox\n * digitalocean login` mid-process won't pick up the new token without a\n * fresh `makeDigitalOceanClient()` call (we accept this — the CLI re-imports\n * the provider on each invocation).\n */\nexport function makeDigitalOceanClient(opts: MakeClientOptions = {}): DigitalOceanClient {\n ensureDigitalOceanEnvLoaded();\n const rawToken = opts.token ?? process.env.DIGITALOCEAN_TOKEN;\n if (!rawToken || rawToken.trim().length === 0) {\n throw new Error(\n 'DigitalOcean credentials not configured: DIGITALOCEAN_TOKEN is empty.\\n' +\n 'Run `agentbox digitalocean login` interactively, or set DIGITALOCEAN_TOKEN in the environment.',\n );\n }\n const token: string = rawToken.trim();\n const endpoint = (opts.endpoint ?? process.env.DIGITALOCEAN_API_URL ?? DEFAULT_DO_ENDPOINT).replace(/\\/$/, '');\n const fetchImpl = opts.fetchImpl ?? fetch;\n\n async function req<T>(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n body?: unknown,\n ): Promise<T | null> {\n const url = path.startsWith('http') ? path : `${endpoint}${path}`;\n const init: RequestInit = {\n method,\n headers: {\n Authorization: `Bearer ${token}`,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n };\n const res = await fetchImpl(url, init);\n if (res.status === 204) return null;\n if (res.status === 404) return null;\n if (!res.ok) {\n let parsed: { id?: string; message?: string; request_id?: string } = {};\n try {\n parsed = (await res.json()) as typeof parsed;\n } catch {\n // body wasn't json\n }\n const code = parsed.id ?? `http_${String(res.status)}`;\n const msg = parsed.message ?? res.statusText ?? 'unknown error';\n throw new DigitalOceanApiError(res.status, code, msg, parsed.request_id);\n }\n const text = await res.text();\n if (text.length === 0) return null;\n return JSON.parse(text) as T;\n }\n\n async function reqExpect<T>(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n body?: unknown,\n ): Promise<T> {\n const out = await req<T>(method, path, body);\n if (out === null) {\n throw new DigitalOceanApiError(0, 'empty_response', `expected a body from ${method} ${path}`);\n }\n return out;\n }\n\n /**\n * Page through a list endpoint. DigitalOcean returns `{ <key>: [...],\n * links: { pages: { next } }, meta: { total } }`. We follow `links.pages.next`\n * (a full URL) until it's absent.\n */\n async function paginate<T>(firstPath: string, key: string): Promise<T[]> {\n const all: T[] = [];\n let next: string | undefined = firstPath;\n while (next) {\n const r: Record<string, unknown> = await reqExpect<Record<string, unknown>>('GET', next);\n const page = (r[key] as T[] | undefined) ?? [];\n all.push(...page);\n const links = r.links as { pages?: { next?: string } } | undefined;\n next = links?.pages?.next;\n }\n return all;\n }\n\n function withPerPage(path: string): string {\n return path.includes('?') ? `${path}&per_page=200` : `${path}?per_page=200`;\n }\n\n async function dropletAction(id: number, payload: Record<string, unknown>): Promise<DigitalOceanAction> {\n const r = await reqExpect<{ action: DigitalOceanAction }>(\n 'POST',\n `/droplets/${String(id)}/actions`,\n payload,\n );\n return r.action;\n }\n\n return {\n async getAccount() {\n const r = await reqExpect<{ account: DigitalOceanAccount }>('GET', '/account');\n return r.account;\n },\n async getDroplet(id) {\n const r = await req<{ droplet: DigitalOceanDroplet }>('GET', `/droplets/${String(id)}`);\n return r?.droplet ?? null;\n },\n async createDroplet(reqBody) {\n const r = await reqExpect<{\n droplet: DigitalOceanDroplet;\n links?: { actions?: Array<{ id: number; rel: string }> };\n }>('POST', '/droplets', reqBody);\n const createAction = r.links?.actions?.find((a) => a.rel === 'create') ?? r.links?.actions?.[0];\n return { droplet: r.droplet, actionId: createAction?.id ?? null };\n },\n async listDroplets(opts) {\n const base = opts?.tag_name\n ? `/droplets?tag_name=${encodeURIComponent(opts.tag_name)}`\n : '/droplets';\n return paginate<DigitalOceanDroplet>(withPerPage(base), 'droplets');\n },\n async deleteDroplet(id) {\n await req<unknown>('DELETE', `/droplets/${String(id)}`);\n },\n async powerOn(id) {\n return dropletAction(id, { type: 'power_on' });\n },\n async powerOff(id) {\n return dropletAction(id, { type: 'power_off' });\n },\n async shutdown(id) {\n return dropletAction(id, { type: 'shutdown' });\n },\n async snapshotDroplet(id, name) {\n return dropletAction(id, { type: 'snapshot', name });\n },\n async getAction(id) {\n const r = await req<{ action: DigitalOceanAction }>('GET', `/actions/${String(id)}`);\n return r?.action ?? null;\n },\n async listSnapshots() {\n return paginate<DigitalOceanSnapshot>(\n withPerPage('/snapshots?resource_type=droplet'),\n 'snapshots',\n );\n },\n async getSnapshot(id) {\n const r = await req<{ snapshot: DigitalOceanSnapshot }>('GET', `/snapshots/${encodeURIComponent(id)}`);\n return r?.snapshot ?? null;\n },\n async deleteSnapshot(id) {\n await req<unknown>('DELETE', `/snapshots/${encodeURIComponent(id)}`);\n },\n async listSizes() {\n return paginate<DigitalOceanSize>(withPerPage('/sizes'), 'sizes');\n },\n async listProjects() {\n return paginate<DigitalOceanProject>(withPerPage('/projects'), 'projects');\n },\n async getDefaultProject() {\n const r = await req<{ project: DigitalOceanProject }>('GET', '/projects/default');\n return r?.project ?? null;\n },\n async assignProjectResources(projectId, urns) {\n await req<unknown>('POST', `/projects/${encodeURIComponent(projectId)}/resources`, {\n resources: urns,\n });\n },\n async createFirewall(reqBody) {\n const r = await reqExpect<{ firewall: DigitalOceanFirewall }>('POST', '/firewalls', reqBody);\n return r.firewall;\n },\n async getFirewall(id) {\n const r = await req<{ firewall: DigitalOceanFirewall }>('GET', `/firewalls/${encodeURIComponent(id)}`);\n return r?.firewall ?? null;\n },\n async listFirewalls() {\n return paginate<DigitalOceanFirewall>(withPerPage('/firewalls'), 'firewalls');\n },\n async updateFirewall(id, reqBody) {\n const r = await reqExpect<{ firewall: DigitalOceanFirewall }>(\n 'PUT',\n `/firewalls/${encodeURIComponent(id)}`,\n reqBody,\n );\n return r.firewall;\n },\n async deleteFirewall(id) {\n await req<unknown>('DELETE', `/firewalls/${encodeURIComponent(id)}`);\n },\n async createTag(name) {\n try {\n await req<unknown>('POST', '/tags', { name });\n } catch (err) {\n // A tag that already exists returns 422 — treat as success so\n // re-provision / retry paths don't fail on an existing tag.\n if (err instanceof DigitalOceanApiError && err.statusCode === 422) return;\n throw err;\n }\n },\n async deleteTag(name) {\n await req<unknown>('DELETE', `/tags/${encodeURIComponent(name)}`);\n },\n };\n}\n","/**\n * Pure DigitalOcean create preflight — no network. Given a fetched `/sizes`\n * catalog and (optionally) the base snapshot, validate the user's size +\n * region choice BEFORE we start creating billable resources (firewall, SSH\n * key, droplet), and map the late provision errors DigitalOcean returns into\n * actionable guidance.\n *\n * Kept side-effect-free so it unit-tests against fake catalogs/snapshots. The\n * backend fetches the catalog + snapshot and calls in. Mirrors the Hetzner\n * `preflight.ts`.\n */\n\nimport { UserFacingError } from '@agentbox/core';\nimport {\n DigitalOceanApiError,\n type DigitalOceanProject,\n type DigitalOceanSize,\n type DigitalOceanSnapshot,\n} from './client.js';\n\nexport interface SizeChoice {\n size: string;\n region: string;\n}\n\n/**\n * Up to `limit` available size slugs from the catalog, in catalog order (DO\n * roughly orders `/sizes` cheapest-first). Used to suggest alternatives when\n * the user's slug is unknown.\n */\nfunction suggestSizes(catalog: DigitalOceanSize[], limit = 6): string[] {\n return catalog\n .filter((s) => s.available)\n .map((s) => s.slug)\n .slice(0, limit);\n}\n\n/**\n * Validate a size + region choice against the live catalog and the base\n * snapshot, throwing a `UserFacingError` with a fix on the first problem.\n * Checks, in order: size exists → is available → disk fits the snapshot →\n * region offers the size.\n *\n * `snapshot` is null when the box boots from a DigitalOcean stock image slug\n * (a plain string like `ubuntu-24-04-x64`, not a numeric snapshot id) — the\n * disk check is skipped in that case since we don't have the `min_disk_size`.\n */\nexport function validateSizeChoice(\n choice: SizeChoice,\n catalog: DigitalOceanSize[],\n snapshot: DigitalOceanSnapshot | null,\n): void {\n const { size, region } = choice;\n const plan = catalog.find((s) => s.slug === size);\n\n if (!plan) {\n const suggestions = suggestSizes(catalog);\n const hint = suggestions.length > 0 ? ` Valid sizes include: ${suggestions.join(', ')}.` : '';\n throw new UserFacingError(\n `DigitalOcean size \"${size}\" does not exist.${hint}\\n` +\n 'Set one with `--size <slug>` or `agentbox config set box.sizeDigitalocean <slug>`.',\n );\n }\n\n if (!plan.available) {\n throw new UserFacingError(\n `DigitalOcean size \"${size}\" is not currently available for new Droplets.\\n` +\n `Pick an available size instead: ${suggestSizes(catalog).join(', ')}.`,\n );\n }\n\n // Snapshot disk must fit the plan's disk. Skip for stock string refs\n // (snapshot null) — DO sizes those itself.\n if (snapshot && typeof snapshot.min_disk_size === 'number' && plan.disk < snapshot.min_disk_size) {\n throw new UserFacingError(\n `DigitalOcean size \"${size}\" has a ${String(plan.disk)} GB disk, but the base ` +\n `snapshot needs at least ${String(snapshot.min_disk_size)} GB.\\n` +\n 'Choose a larger size (bigger plans have bigger disks).',\n );\n }\n\n if (plan.regions.length > 0 && !plan.regions.includes(region)) {\n throw new UserFacingError(\n `DigitalOcean size \"${size}\" is not offered in region \"${region}\".\\n` +\n `It is available in: ${plan.regions.join(', ')}.\\n` +\n 'Pick one with `--location <slug>` or `agentbox config set box.digitaloceanRegion <slug>`.',\n );\n }\n}\n\n/**\n * Resolve `box.digitaloceanProject` (a project **name or id**) to a project id,\n * throwing a `UserFacingError` listing the real projects when it matches\n * nothing.\n *\n * This runs in the create preflight, before any billable resource exists,\n * because the assignment itself cannot: DigitalOcean has no project field on\n * droplet-create, so the assign only happens once the Droplet is up — far too\n * late to tell someone they typed the project name wrong.\n *\n * Name matching is case-insensitive; an exact id match wins over a name match so\n * a project literally named like another's id can't shadow it.\n */\nexport function resolveProjectChoice(project: string, projects: DigitalOceanProject[]): string {\n const wanted = project.trim();\n if (wanted.length === 0) {\n throw new UserFacingError('DigitalOcean project must not be empty.');\n }\n\n const byId = projects.find((p) => p.id === wanted);\n if (byId) return byId.id;\n\n const matches = projects.filter((p) => p.name.toLowerCase() === wanted.toLowerCase());\n if (matches.length === 1) return matches[0]!.id;\n\n if (matches.length > 1) {\n throw new UserFacingError(\n `DigitalOcean project name \"${wanted}\" is ambiguous — ${String(matches.length)} projects share it.\\n` +\n `Use the id instead: ${matches.map((p) => p.id).join(', ')}.\\n` +\n 'Set it with `agentbox config set box.digitaloceanProject <id>`.',\n );\n }\n\n const known = projects\n .map((p) => (p.is_default ? `${p.name} (default)` : p.name))\n .join(', ');\n throw new UserFacingError(\n `DigitalOcean project \"${wanted}\" not found on this account.\\n` +\n (known.length > 0 ? `Your projects: ${known}.\\n` : 'This account has no projects.\\n') +\n 'Set it with `agentbox config set box.digitaloceanProject <name|id>`, ' +\n 'or unset it to use the account default.',\n );\n}\n\n/**\n * Map a DigitalOcean provision error (from `createDroplet`) into a friendlier\n * `UserFacingError`, preserving the original message. Non-DO errors and\n * unrecognized codes pass through unchanged so we never hide an unexpected\n * failure. Called around the `createDroplet` call in the backend.\n */\nexport function mapDigitalOceanProvisionError(err: unknown, choice: SizeChoice): unknown {\n if (!(err instanceof DigitalOceanApiError)) return err;\n const { size, region } = choice;\n const msg = err.message.toLowerCase();\n\n // DO reports the account droplet limit as a 422 with a message rather than a\n // stable machine code, so match on the text.\n if (msg.includes('droplet limit') || msg.includes('exceeded your droplet limit')) {\n return new UserFacingError(\n `DigitalOcean refused to create the Droplet: your account Droplet limit was exceeded ` +\n `(${err.message}).\\n` +\n 'New accounts start with a low Droplet limit. Request an increase in the DigitalOcean ' +\n 'Console (Account → your team → Droplet limit), then retry.',\n );\n }\n\n if (msg.includes('not available') || msg.includes('capacity') || msg.includes('sold out')) {\n return new UserFacingError(\n `DigitalOcean has no capacity for \"${size}\" in \"${region}\" right now ` +\n `(${err.message}).\\n` +\n 'Retry, or pick another region with `--location <slug>` (e.g. `nyc1`, `sfo3`, `ams3`, ' +\n '`fra1`) or `agentbox config set box.digitaloceanRegion <slug>`.',\n );\n }\n\n return err;\n}\n","import { spawnSync } from 'node:child_process';\nimport { hostOpenCommand, type CredSetResult } from '@agentbox/sandbox-core';\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, resolve } from 'node:path';\nimport {\n cancel,\n confirm,\n isCancel,\n intro,\n log,\n note,\n outro,\n password,\n select,\n spinner,\n} from '@clack/prompts';\nimport { loadEffectiveConfig, setConfigValue, unsetConfigValue } from '@agentbox/config';\nimport { makeDigitalOceanClient, type DigitalOceanProject } from './client.js';\nimport { ensureDigitalOceanEnvLoaded } from './env-loader.js';\nimport { resolveProjectChoice } from './preflight.js';\n\n// Ctrl+C at a prompt resolves with the cancel symbol; turn that into a real\n// quit so the command never silently continues as if the user answered \"No\".\nfunction exitOnCancel<T>(v: T | symbol): T {\n if (isCancel(v)) {\n cancel('Cancelled.');\n process.exit(130);\n }\n return v as T;\n}\n\nconst DASHBOARD_KEYS_URL = 'https://cloud.digitalocean.com/account/api/tokens';\n\n/**\n * Keys we manage in `~/.agentbox/secrets.env`. When the user reconfigures\n * we strip prior values before appending so the file never accumulates\n * duplicates. `DIGITALOCEAN_API_URL` is honored but we don't prompt for it\n * (default endpoint covers 100% of users).\n */\nconst MANAGED_KEYS = ['DIGITALOCEAN_TOKEN', 'DIGITALOCEAN_API_URL'] as const;\ntype ManagedKey = (typeof MANAGED_KEYS)[number];\n\nexport interface EnsureDigitalOceanCredentialsOptions {\n /** Re-prompt even when valid credentials are already present (used by `agentbox digitalocean login`). */\n force?: boolean;\n}\n\n/**\n * First-run interactive setup for DigitalOcean credentials. Walks the user\n * through creating a project API token, pasting it, validating, and\n * persisting to `~/.agentbox/secrets.env`.\n *\n * No-op when credentials are already configured (env var or our secrets\n * file). Silent no-op when stdin isn't a TTY so scripted/CI callers get\n * the API \"401 unauthorized\" error instead of a hung prompt.\n *\n * Mirrors `ensureDaytonaCredentials()` in shape so the registry's first-\n * run gate stays uniform across providers.\n */\nexport async function ensureDigitalOceanCredentials(\n opts: EnsureDigitalOceanCredentialsOptions = {},\n): Promise<void> {\n ensureDigitalOceanEnvLoaded();\n\n if (!opts.force && hasUsableCredentials()) return;\n if (!process.stdin.isTTY) return;\n\n intro('DigitalOcean setup');\n note(\n `AgentBox needs a DigitalOcean Personal Access Token to provision Droplets.\\n\\n` +\n `1. Open ${DASHBOARD_KEYS_URL}\\n` +\n `2. Click \"Generate New Token\".\\n` +\n `3. Give it Read + Write scopes, then copy the token.`,\n 'API token required',\n );\n\n const open = exitOnCancel(\n await confirm({\n message: `Open ${DASHBOARD_KEYS_URL} in your browser?`,\n initialValue: true,\n }),\n );\n if (open) openDashboard();\n\n // One retry on auth failure (typos / expired token are the common case).\n for (let attempt = 0; attempt < 2; attempt++) {\n const creds = await promptForCredentials();\n\n const result = await validateCredentials(creds);\n if (result.ok) {\n persistCredentials(creds);\n log.success(`DigitalOcean credentials saved to ${secretsPath()}`);\n await promptForProject(creds);\n outro('Setup complete.');\n return;\n }\n if (result.kind === 'auth' && attempt === 0) {\n log.error(`That token was rejected by DigitalOcean: ${result.message}`);\n log.info('Try again, or press Ctrl-C to cancel.');\n continue;\n }\n if (result.kind === 'network') {\n log.warn(`Could not reach DigitalOcean to validate (${result.message}) — saving anyway.`);\n persistCredentials(creds);\n log.success(`DigitalOcean credentials saved to ${secretsPath()}`);\n outro('Setup complete (unvalidated).');\n return;\n }\n throw new Error(`DigitalOcean credentials rejected: ${result.message}`);\n }\n}\n\n/**\n * Offer to pick the DigitalOcean **Project** new boxes land in, right after the\n * token validates — the one moment we hold a known-good token.\n *\n * The choice goes to the **global config** (`box.digitaloceanProject`), not\n * `secrets.env`: it is a placement preference, not a secret, and it has to take\n * part in config layering so a repo can override it in `agentbox.yaml`.\n *\n * Entirely optional. Skipping (or an account with a single project, or a\n * failure to list them) leaves the key unset, which means DigitalOcean's own\n * behavior: everything lands in the account's default project. A network blip\n * here must never fail an otherwise-good login.\n */\nasync function promptForProject(creds: Credentials): Promise<void> {\n let projects: DigitalOceanProject[];\n try {\n const client = makeDigitalOceanClient({ token: creds.token, endpoint: creds.endpoint });\n projects = await client.listProjects();\n } catch (err) {\n log.warn(\n `Could not list your DigitalOcean projects (${err instanceof Error ? err.message : String(err)}) — ` +\n \"boxes will use the account's default project. Set it later with \" +\n '`agentbox config set box.digitaloceanProject <name|id>`.',\n );\n return;\n }\n\n // Nothing to choose between — don't ask a question with one answer.\n if (projects.length < 2) return;\n\n const current = (await loadEffectiveConfig(process.cwd())).effective.box.digitaloceanProject;\n const choice = exitOnCancel(\n await select({\n message: 'Which DigitalOcean project should new boxes go into?',\n initialValue: current || SKIP_PROJECT,\n options: [\n ...projects.map((p) => ({\n value: p.id,\n label: p.is_default ? `${p.name} (account default)` : p.name,\n hint: p.id,\n })),\n { value: SKIP_PROJECT, label: \"Skip — use the account's default project\" },\n ],\n }),\n );\n\n if (choice === SKIP_PROJECT) {\n // \"Use the account's default\" has to actually mean that. A previously saved\n // global key would otherwise keep sending boxes to the old project while this\n // line claims the opposite — so clear it rather than just not writing one.\n // (A repo-level override in agentbox.yaml still wins; that is the point of it.)\n if (current) await unsetConfigValue('global', 'box.digitaloceanProject', process.cwd());\n log.info(\"Boxes will go into your account's default DigitalOcean project.\");\n return;\n }\n\n await setConfigValue('global', 'box.digitaloceanProject', choice, process.cwd());\n const picked = projects.find((p) => p.id === choice);\n log.success(`New boxes will be created in the \"${picked?.name ?? choice}\" project.`);\n}\n\nconst SKIP_PROJECT = '__skip__';\n\nfunction hasUsableCredentials(): boolean {\n return typeof process.env.DIGITALOCEAN_TOKEN === 'string' && process.env.DIGITALOCEAN_TOKEN.length > 0;\n}\n\ninterface Credentials {\n token: string;\n endpoint?: string;\n}\n\nasync function promptForCredentials(): Promise<Credentials> {\n const token = exitOnCancel(\n await password({\n message: 'Paste your DigitalOcean Cloud API token',\n validate(v) {\n if (!v || v.trim().length === 0) return 'Cannot be empty';\n return undefined;\n },\n }),\n );\n return { token: token.trim() };\n}\n\ntype ValidationResult =\n | { ok: true }\n | { ok: false; kind: 'auth'; message: string }\n | { ok: false; kind: 'network'; message: string };\n\nasync function validateCredentials(creds: Credentials): Promise<ValidationResult> {\n const s = spinner();\n s.start('Validating credentials with DigitalOcean');\n\n try {\n const client = makeDigitalOceanClient({ token: creds.token, endpoint: creds.endpoint });\n // `getAccount()` is a cheap, deterministic call that exercises auth +\n // basic API reachability without provisioning anything.\n await client.getAccount();\n s.stop('DigitalOcean credentials accepted');\n return { ok: true };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n s.stop('DigitalOcean credentials check failed');\n if (/401|403|unauthor|forbidden|invalid|token/i.test(message)) {\n return { ok: false, kind: 'auth', message };\n }\n return { ok: false, kind: 'network', message };\n }\n}\n\nfunction persistCredentials(creds: Credentials): void {\n process.env.DIGITALOCEAN_TOKEN = creds.token;\n if (creds.endpoint) process.env.DIGITALOCEAN_API_URL = creds.endpoint;\n const path = secretsPath();\n mkdirSync(dirname(path), { recursive: true });\n\n let existing = '';\n if (existsSync(path)) {\n try {\n existing = readFileSync(path, 'utf8');\n } catch {\n existing = '';\n }\n }\n\n const kept = existing\n .split(/\\r?\\n/)\n .filter((line) => {\n const stripped = line.startsWith('export ') ? line.slice('export '.length) : line;\n const eq = stripped.indexOf('=');\n if (eq <= 0) return true;\n const key = stripped.slice(0, eq).trim();\n return !(MANAGED_KEYS as readonly string[]).includes(key);\n })\n .join('\\n')\n .replace(/\\s+$/u, '');\n\n const lines: string[] = [`DIGITALOCEAN_TOKEN=${creds.token}`];\n if (creds.endpoint) lines.push(`DIGITALOCEAN_API_URL=${creds.endpoint}`);\n\n const body = (kept ? `${kept}\\n` : '') + lines.join('\\n') + '\\n';\n\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, body, { mode: 0o600 });\n try {\n chmodSync(tmp, 0o600);\n } catch {\n // chmod best-effort; writeFileSync mode already covers most filesystems.\n }\n renameSync(tmp, path);\n try {\n chmodSync(path, 0o600);\n } catch {\n // ignore — already attempted above.\n }\n}\n\n/**\n * Non-interactive credential set (the headless path the hub drives). Validates\n * `{ token, endpoint? }` against the DigitalOcean API (a cheap `getAccount`),\n * then persists to `~/.agentbox/secrets.env`. A network failure still persists\n * (so an offline host isn't blocked) but reports `ok:true` with a warning label.\n */\nexport async function setDigitalOceanCredentials(\n fields: Record<string, string>,\n): Promise<CredSetResult> {\n const token = (fields.token ?? '').trim();\n const endpoint = (fields.endpoint ?? '').trim() || undefined;\n if (!token) {\n return { ok: false, error: 'token is required', status: { configured: false } };\n }\n const creds: Credentials = { token, endpoint };\n const result = await validateCredentials(creds);\n if (!result.ok && result.kind === 'auth') {\n return {\n ok: false,\n error: `token rejected by DigitalOcean: ${result.message}`,\n status: { configured: false },\n };\n }\n persistCredentials(creds);\n\n // The optional Project field from the hub / tray settings form. It is NOT a\n // secret and must not land in secrets.env: `box.digitaloceanProject` is the\n // single source of truth (it also has to layer, so a repo can override it).\n // Resolve the name to an id here so a typo is reported inline in the form\n // rather than surfacing much later as a failed create.\n const project = (fields.project ?? '').trim();\n if (project.length > 0) {\n try {\n const client = makeDigitalOceanClient({ token: creds.token, endpoint: creds.endpoint });\n const projectId = resolveProjectChoice(project, await client.listProjects());\n await setConfigValue('global', 'box.digitaloceanProject', projectId, process.cwd());\n } catch (err) {\n // The token is already saved and good — only the project is bad, so say\n // exactly that rather than implying the credentials were rejected.\n return {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n status: { configured: true, label: 'token (project not set)' },\n };\n }\n }\n\n const label = result.ok ? 'token' : 'token (unvalidated)';\n return { ok: true, status: { configured: true, label } };\n}\n\nfunction openDashboard(): void {\n try {\n const r = spawnSync(hostOpenCommand(), [DASHBOARD_KEYS_URL], { stdio: 'ignore' });\n if (r.status !== 0) {\n log.warn(`Could not auto-open the browser — visit ${DASHBOARD_KEYS_URL} manually.`);\n }\n } catch {\n log.warn(`Could not auto-open the browser — visit ${DASHBOARD_KEYS_URL} manually.`);\n }\n}\n\nexport function secretsPath(): string {\n return resolve(homedir(), '.agentbox', 'secrets.env');\n}\n\nexport interface DigitalOceanCredStatus {\n token?: string;\n endpoint?: string;\n source: 'env' | 'secrets.env' | 'none';\n}\n\nexport function readDigitalOceanCredStatus(): DigitalOceanCredStatus {\n const shellHadToken = !!process.env.DIGITALOCEAN_TOKEN;\n ensureDigitalOceanEnvLoaded();\n const token = process.env.DIGITALOCEAN_TOKEN;\n const endpoint = process.env.DIGITALOCEAN_API_URL;\n if (!token) return { source: 'none' };\n return {\n token,\n endpoint,\n source: shellHadToken ? 'env' : 'secrets.env',\n };\n}\n\nexport function maskKey(value: string): string {\n if (value.length <= 8) return '*'.repeat(value.length);\n return `${value.slice(0, 4)}…${'*'.repeat(8)}${value.slice(-4)}`;\n}\n\n/** Snapshot of the managed env keys (used by tests around `applyToEnv`). */\nexport function snapshotManagedEnv(): Record<ManagedKey, string | undefined> {\n const out = {} as Record<ManagedKey, string | undefined>;\n for (const k of MANAGED_KEYS) out[k] = process.env[k];\n return out;\n}\n\nexport function restoreManagedEnv(snap: Record<ManagedKey, string | undefined>): void {\n for (const k of MANAGED_KEYS) {\n if (snap[k] === undefined) delete process.env[k];\n else process.env[k] = snap[k];\n }\n}\n","/**\n * Host egress-IP detection for the DigitalOcean firewall lock-down. Probes three\n * independent providers in sequence; first 3s success wins. Fails loud\n * (throws) if all three fail — we do **not** silently fall back to\n * `0.0.0.0/0`, because that would defeat the safe-by-default firewall.\n *\n * The user can always override the auto-detect via\n * `--firewall-source <cidr>` (or `--firewall-source 0.0.0.0/0` for the\n * explicit dynamic-IP opt-in).\n */\n\nconst PROBES = [\n 'https://api.ipify.org',\n 'https://ifconfig.io/ip',\n 'https://icanhazip.com',\n] as const;\n\nconst TIMEOUT_MS = 3_000;\n\nconst IPV4_RE = /^(?:\\d{1,3}\\.){3}\\d{1,3}$/;\nconst IPV6_RE = /^[0-9a-fA-F:]+$/;\n\nexport interface DetectEgressIpOptions {\n /** Override the probe list (tests inject this). */\n probes?: readonly string[];\n /** Per-probe timeout in ms (default 3_000). */\n timeoutMs?: number;\n /** Override `fetch` (tests inject this). */\n fetchImpl?: typeof fetch;\n /** Best-effort logger for probe attempts. */\n onLog?: (line: string) => void;\n}\n\n/**\n * Detect the host's egress IP. Returns the bare IP string (no `/32`); the\n * caller composes the CIDR.\n *\n * Throws when no probe responded. The error message lists each probe that\n * was tried so the user can see whether their network is blocking a\n * specific provider.\n */\nexport async function detectEgressIp(opts: DetectEgressIpOptions = {}): Promise<string> {\n const probes = opts.probes ?? PROBES;\n const timeout = opts.timeoutMs ?? TIMEOUT_MS;\n const fetchImpl = opts.fetchImpl ?? fetch;\n const errors: string[] = [];\n\n for (const url of probes) {\n try {\n const ip = await raceTimeout(probe(url, fetchImpl), timeout);\n if (ip) {\n opts.onLog?.(`egress-ip: detected ${ip} via ${url}`);\n return ip;\n }\n errors.push(`${url}: empty/invalid response`);\n } catch (err) {\n errors.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n throw new Error(\n `could not auto-detect the host's egress IP — all ${String(probes.length)} probes failed:\\n` +\n errors.map((e) => ` - ${e}`).join('\\n') +\n `\\nOverride with --firewall-source <cidr> (e.g. --firewall-source 0.0.0.0/0 for the explicit-open opt-in).`,\n );\n}\n\nasync function probe(url: string, fetchImpl: typeof fetch): Promise<string | null> {\n const res = await fetchImpl(url, { method: 'GET' });\n if (!res.ok) return null;\n const body = (await res.text()).trim();\n if (IPV4_RE.test(body)) {\n // Cheap sanity: each octet in 0–255.\n const parts = body.split('.').map((p) => Number.parseInt(p, 10));\n if (parts.every((p) => p >= 0 && p <= 255)) return body;\n return null;\n }\n // We do not currently use IPv6 for firewall rules (DigitalOcean accepts them\n // but the rest of the provider talks IPv4), but accept the probe answer\n // so a v6-only network surfaces an actionable error rather than a silent\n // empty result. Composing the CIDR is the caller's job.\n if (IPV6_RE.test(body) && body.includes(':')) return body;\n return null;\n}\n\nasync function raceTimeout<T>(p: Promise<T>, ms: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n p,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(`probe timed out after ${String(ms)}ms`)), ms);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","/**\n * Bounded retry wrapper for DigitalOcean Cloud API calls — mirrors\n * `withDaytonaRetry` in shape and intent. DigitalOcean is generally well-behaved\n * but the public API does rate-limit (429) and occasionally returns 502/504\n * during regional incidents; without bounded retries those propagate as\n * wedges in the calling lifecycle code.\n *\n * Non-idempotent ops (`provision`, `createImage`) pass\n * `retryOnAmbiguous: false` so a 504 after the request reached the origin\n * doesn't create a duplicate billable resource.\n */\n\nimport { DigitalOceanApiError } from './client.js';\n\nexport interface WithRetryOptions {\n /** Method name, used in retry log lines. */\n method: string;\n /** Per-attempt timeout (ms). Default 30_000. */\n attemptTimeoutMs?: number;\n /** Backoff before attempts 2, 3, … (ms). Default [1000, 2000, 4000]. */\n backoffMs?: readonly number[];\n /**\n * Whether to retry on errors where we can't be sure the server applied\n * the request — connection failures, per-attempt timeouts, and 5xx\n * responses. Set false for non-idempotent operations (e.g. `provision`,\n * `createImage`) where a retry could create a duplicate resource.\n */\n retryOnAmbiguous: boolean;\n /** Override the default `process.stderr` retry sink (used by tests). */\n onRetry?: (line: string) => void;\n}\n\nconst DEFAULT_BACKOFF: readonly number[] = [1000, 2000, 4000];\nconst DEFAULT_ATTEMPT_TIMEOUT_MS = 30_000;\n\nclass AttemptTimeoutError extends Error {\n constructor(method: string, ms: number) {\n super(`digitalocean ${method}: per-attempt timeout after ${String(ms)}ms`);\n this.name = 'AttemptTimeoutError';\n }\n}\n\nexport function isAttemptTimeout(err: unknown): err is AttemptTimeoutError {\n return err instanceof AttemptTimeoutError;\n}\n\n/**\n * Classify an error as retriable or not. `allowAmbiguous` gates the cases\n * where the server may or may not have applied the request — the caller\n * decides based on idempotency.\n */\nexport function isRetriable(err: unknown, allowAmbiguous: boolean): boolean {\n if (err instanceof DigitalOceanApiError) {\n // Rate limit: always back off — the server told us to.\n if (err.statusCode === 429 || err.code === 'rate_limit_exceeded') return true;\n // 5xx: ambiguous (the API may or may not have applied the change).\n if (err.statusCode >= 500 && err.statusCode <= 599) return allowAmbiguous;\n // DigitalOcean conflict / locked errors: the API tells us to wait — same as\n // rate-limit semantically. `conflict` is what `delete_server` returns\n // when another action (e.g. our own poweroff) is still in flight.\n if (err.code === 'locked' || err.code === 'conflict') return true;\n // Everything else is a permanent client error (auth, validation, not_found).\n return false;\n }\n\n if (err instanceof AttemptTimeoutError) return allowAmbiguous;\n\n // Raw fetch / undici errors. The Node fetch impl wraps low-level errors in\n // `{ cause }`; we check both shapes for portability.\n if (err && typeof err === 'object') {\n const candidates: unknown[] = [err, (err as { cause?: unknown }).cause];\n for (const c of candidates) {\n if (!c || typeof c !== 'object') continue;\n const code = (c as { code?: unknown }).code;\n if (\n code === 'ECONNRESET' ||\n code === 'ETIMEDOUT' ||\n code === 'ECONNABORTED' ||\n code === 'EAI_AGAIN' ||\n code === 'ECONNREFUSED' ||\n code === 'ENOTFOUND' ||\n code === 'UND_ERR_SOCKET' ||\n code === 'UND_ERR_CONNECT_TIMEOUT'\n ) {\n return allowAmbiguous;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Run `fn`, retrying on transient failures with capped exponential backoff.\n * Each attempt is bounded by `attemptTimeoutMs` via Promise.race; total\n * wall-clock = sum(backoffMs) + maxAttempts * attemptTimeoutMs.\n */\nexport async function withDigitalOceanRetry<T>(\n opts: WithRetryOptions,\n fn: () => Promise<T>,\n): Promise<T> {\n const backoff = opts.backoffMs ?? DEFAULT_BACKOFF;\n const maxAttempts = backoff.length + 1;\n const timeoutMs = opts.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS;\n const log = opts.onRetry ?? defaultRetryLog;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await raceTimeout(fn(), timeoutMs, opts.method);\n } catch (err) {\n const last = attempt === maxAttempts;\n if (last || !isRetriable(err, opts.retryOnAmbiguous)) throw err;\n const delay = backoff[attempt - 1] ?? backoff[backoff.length - 1] ?? 4000;\n log(\n `digitalocean ${opts.method}: attempt ${String(attempt)} failed (${errorSummary(err)}); retrying in ${String(delay)}ms`,\n );\n await sleep(delay);\n }\n }\n throw new Error(`withDigitalOceanRetry: exhausted attempts for ${opts.method}`);\n}\n\nfunction defaultRetryLog(line: string): void {\n process.stderr.write(`\\n[digitalocean-retry] ${line}\\n`);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function raceTimeout<T>(p: Promise<T>, ms: number, method: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n p,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new AttemptTimeoutError(method, ms)), ms);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\nfunction errorSummary(err: unknown): string {\n if (err instanceof DigitalOceanApiError) {\n return `DigitalOceanApiError ${String(err.statusCode)} ${err.code}: ${truncate(err.message)}`;\n }\n if (err instanceof Error) {\n const code = (err as { code?: unknown }).code;\n return code !== undefined\n ? `${err.name}(${String(code)}): ${truncate(err.message)}`\n : `${err.name}: ${truncate(err.message)}`;\n }\n return truncate(String(err));\n}\n\nfunction truncate(s: string, max = 160): string {\n return s.length > max ? `${s.slice(0, max)}…` : s;\n}\n","/**\n * DigitalOcean Cloud Firewall provisioning + drift sync.\n *\n * Defense-in-depth model (mirrors the Hetzner provider's safety model):\n *\n * 1. In-VPS services bind to loopback (the load-bearing layer).\n * 2. DigitalOcean Cloud Firewall locks SSH to the host's egress IP — created\n * here at provision time *before* the droplet boots and attached to it\n * via a unique per-box tag, so there is never an unprotected window.\n * Everything else is denied inbound.\n * 3. sshd hardening (PasswordAuthentication no, AllowUsers vscode, …)\n * written by cloud-init at first boot.\n *\n * Two DigitalOcean-specific wrinkles vs. Hetzner:\n * - Firewall ids are UUID strings, not numbers.\n * - A DO firewall with *only* inbound rules blocks ALL egress. We must add\n * explicit allow-all outbound rules or the box can't `git clone` / `npm i`.\n *\n * The firewall is per-box (1:1 with the droplet) so an egress-IP drift on one\n * box doesn't affect siblings, and a destroy cleanly removes everything.\n */\n\nimport {\n DigitalOceanApiError,\n type CreateFirewallRequest,\n type DigitalOceanClient,\n type DigitalOceanFirewall,\n type DigitalOceanInboundRule,\n type DigitalOceanOutboundRule,\n} from './client.js';\nimport { withDigitalOceanRetry } from './retry.js';\n\n/**\n * Build the SSH-only inbound rule for one or more source CIDRs. DigitalOcean's\n * `sources.addresses` is a list, so all allowed CIDRs ride a single tcp/22 rule\n * (host egress for `locked`, `0.0.0.0/0`+`::/0` for `open`, host egress + the\n * whitelist for `whitelist`). Accepts a bare string for back-compat callers.\n */\nexport function sshInboundRules(sources: string | string[]): DigitalOceanInboundRule[] {\n const addresses = Array.isArray(sources) ? sources : [sources];\n return [\n {\n protocol: 'tcp',\n ports: '22',\n sources: { addresses },\n },\n ];\n}\n\n/**\n * Allow-all outbound rules. A DigitalOcean firewall with inbound rules but no\n * outbound rules blocks ALL egress — so we explicitly permit everything\n * outbound (the box needs to reach github / npm / pypi / the agentbox relay).\n * Egress locking is out of scope for the per-box SSH firewall.\n */\nexport function allowAllOutboundRules(): DigitalOceanOutboundRule[] {\n const everywhere = { addresses: ['0.0.0.0/0', '::/0'] };\n return [\n { protocol: 'tcp', ports: '1-65535', destinations: everywhere },\n { protocol: 'udp', ports: '1-65535', destinations: everywhere },\n // icmp takes no ports in DigitalOcean's API.\n { protocol: 'icmp', destinations: everywhere },\n ];\n}\n\nexport interface CreateFirewallOptions {\n /** Human-readable name (visible in the DigitalOcean dashboard). Must be unique-ish. */\n name: string;\n /** Inbound source CIDRs (already normalized/resolved by the caller). */\n sources: string[];\n /**\n * Per-box tag the firewall is bound to. The droplet is created with the\n * same tag so DigitalOcean auto-applies this firewall the moment the\n * droplet boots — no unprotected window.\n */\n tag: string;\n}\n\n/**\n * Provision a fresh per-box firewall locked to the given source CIDR and\n * bound to `opts.tag`. Returns the created `DigitalOceanFirewall` (its `id`\n * is a UUID string).\n */\nexport async function createPerBoxFirewall(\n client: DigitalOceanClient,\n opts: CreateFirewallOptions,\n): Promise<DigitalOceanFirewall> {\n // DigitalOcean rejects a firewall (or droplet) referencing a tag that does\n // not exist yet — the tag must be created first. Create it before the\n // firewall so the tag-bound auto-apply still happens with no unprotected\n // window (the droplet is created with the same tag later).\n await withDigitalOceanRetry(\n { method: 'createTag', retryOnAmbiguous: true, attemptTimeoutMs: 60_000 },\n () => client.createTag(opts.tag),\n );\n const body: CreateFirewallRequest = {\n name: opts.name,\n inbound_rules: sshInboundRules(opts.sources),\n outbound_rules: allowAllOutboundRules(),\n tags: [opts.tag],\n };\n return withDigitalOceanRetry(\n { method: 'createFirewall', retryOnAmbiguous: false, attemptTimeoutMs: 60_000 },\n () => client.createFirewall(body),\n );\n}\n\n/**\n * Re-detect the egress IP and replace the firewall's inbound rule with the\n * new source (preserving its name, tags, droplet attachments, and the\n * allow-all outbound rules). Used by `agentbox digitalocean firewall sync\n * <box>` after the host laptop moves networks. Cheap — no droplet restart.\n */\nexport async function syncFirewallSource(\n client: DigitalOceanClient,\n firewall: DigitalOceanFirewall,\n sources: string | string[],\n): Promise<void> {\n const body: CreateFirewallRequest = {\n name: firewall.name,\n inbound_rules: sshInboundRules(sources),\n outbound_rules: allowAllOutboundRules(),\n droplet_ids: firewall.droplet_ids,\n tags: firewall.tags,\n };\n await withDigitalOceanRetry(\n { method: 'updateFirewall', retryOnAmbiguous: true, attemptTimeoutMs: 60_000 },\n () => client.updateFirewall(firewall.id, body),\n );\n}\n\n/**\n * Find the per-box firewall for a droplet. DigitalOcean firewalls have no\n * server-side filter, so we list and match on either the explicit\n * `droplet_ids` attachment or an overlapping tag. Returns null if none.\n */\nexport async function findFirewallForDroplet(\n client: DigitalOceanClient,\n dropletId: number,\n dropletTags: string[],\n): Promise<DigitalOceanFirewall | null> {\n const tagSet = new Set(dropletTags);\n const all = await client.listFirewalls();\n return (\n all.find(\n (fw) =>\n fw.droplet_ids.includes(dropletId) || fw.tags.some((t) => tagSet.has(t)),\n ) ?? null\n );\n}\n\n/**\n * Delete a per-box firewall. Idempotent on 404. DigitalOcean returns 409 /\n * `conflict` while the firewall is still detaching from a just-deleted\n * droplet, so we poll for a short window (default 60s) before giving up.\n */\nexport async function deletePerBoxFirewall(\n client: DigitalOceanClient,\n firewallId: string,\n opts: { detachWaitMs?: number; tags?: readonly string[] } = {},\n): Promise<void> {\n const deadline = Date.now() + (opts.detachWaitMs ?? 60_000);\n let interval = 1_000;\n // Delete the per-box tag(s) `createPerBoxFirewall` minted, once the firewall\n // (the last referencing resource) is gone — otherwise they leak as empty tags.\n // Best-effort: a failure here must not fail destroy. Never touches the shared\n // `agentbox` / `agentbox-prepare` tags (those aren't passed in — only the\n // unique per-box tag the firewall carried).\n const cleanupTags = async () => {\n for (const t of opts.tags ?? []) {\n try {\n await client.deleteTag(t);\n } catch {\n // best-effort — leaked tags are harmless (empty labels, no cost)\n }\n }\n };\n while (true) {\n try {\n await withDigitalOceanRetry(\n { method: 'deleteFirewall', retryOnAmbiguous: true, attemptTimeoutMs: 30_000 },\n () => client.deleteFirewall(firewallId),\n );\n await cleanupTags();\n return;\n } catch (err) {\n if (err instanceof DigitalOceanApiError && (err.statusCode === 404 || err.code === 'not_found')) {\n await cleanupTags();\n return;\n }\n const stillAttached =\n err instanceof DigitalOceanApiError &&\n (err.statusCode === 409 || err.code === 'conflict' || err.code === 'resource_in_use');\n if (stillAttached && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, interval));\n interval = Math.min(interval * 2, 8_000);\n continue;\n }\n throw err;\n }\n }\n}\n\n/**\n * Normalize a source spec into a CIDR. Accepts:\n * - bare IPv4 → appends `/32`\n * - bare IPv6 → appends `/128`\n * - already-CIDR (anything with `/`) → returned as-is\n *\n * Whitespace is trimmed. Does **not** validate the address itself — that's\n * either the API's job or `detectEgressIp`'s job.\n */\nexport function normalizeSourceCidr(raw: string): string {\n const trimmed = raw.trim();\n if (trimmed.includes('/')) return trimmed;\n if (trimmed.includes(':')) return `${trimmed}/128`;\n return `${trimmed}/32`;\n}\n","/**\n * Resolver for the on-disk files we need to ship into a fresh VPS during\n * `prepareDigitalOcean()` — same shape as the docker provider's runtime/docker\n * staging, but lighter (no Dockerfile build, just a flat tarball of files\n * to scp into /tmp).\n *\n * Lookup order for each file:\n * 1. The CLI's staged runtime tree: `<cliRoot>/runtime/digitalocean/...`\n * (populated by `apps/cli/scripts/stage-runtime.mjs`).\n * 2. The monorepo source tree (dev fallback): the file's canonical\n * package-relative path under `packages/`.\n *\n * Failure mode: any missing file throws a clear error naming the lookup\n * paths so a partial dev rebuild is obvious to debug.\n */\n\nimport { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst SELF = dirname(fileURLToPath(import.meta.url));\n\n/**\n * Locate the staged `runtime/digitalocean/` tree. Two candidates:\n *\n * 1. Bundled CLI: the digitalocean module is inlined into apps/cli's dist/, so\n * `dirname(import.meta.url)` is `<cliRoot>/dist`; the staged runtime\n * sits at `<cliRoot>/runtime/digitalocean`.\n * 2. Workspace dev: this module's dist is at\n * `packages/sandbox-digitalocean/dist/`. There's no staged runtime there;\n * callers fall through to the monorepo source paths in\n * `candidatesFor()`. Returns undefined in that case.\n *\n * The CLI doesn't have to pass `cliRuntimeRoot` explicitly — this helper\n * picks it up by inspecting where the module was loaded from.\n */\nexport function findStagedCliRuntimeRoot(): string | undefined {\n const candidates = [\n resolve(SELF, '..', 'runtime'), // <cliRoot>/dist/.. → <cliRoot> then /runtime\n resolve(SELF, '..', '..', 'runtime'), // chunk-NNNN.js at <cliRoot>/dist/<sub>/.. → <cliRoot>/runtime\n ];\n for (const c of candidates) {\n if (existsSync(resolve(c, 'digitalocean', 'scripts', 'install-box.sh'))) return c;\n }\n return undefined;\n}\n\n/**\n * Each runtime asset has a stable, well-known destination basename in\n * `/tmp` on the prepare VPS and is resolved from one of N candidate\n * source paths on the host.\n */\nexport interface RuntimeAsset {\n /** Logical name (used in error messages + log lines). */\n name: string;\n /** Basename on the prepare VPS (under /tmp/). */\n remoteBasename: string;\n /** Optional file mode at scp-time. */\n remoteMode?: number;\n}\n\nexport const RUNTIME_ASSETS: readonly RuntimeAsset[] = [\n { name: 'install-box.sh', remoteBasename: 'agentbox-install.sh', remoteMode: 0o755 },\n { name: 'agentbox-ctl', remoteBasename: 'agentbox-ctl', remoteMode: 0o755 },\n { name: 'agentbox-vnc-start', remoteBasename: 'agentbox-vnc-start', remoteMode: 0o755 },\n { name: 'agentbox-dockerd-start', remoteBasename: 'agentbox-dockerd-start', remoteMode: 0o755 },\n { name: 'agentbox-portless-trust', remoteBasename: 'agentbox-portless-trust', remoteMode: 0o755 },\n { name: 'agentbox-checkpoint-cleanup', remoteBasename: 'agentbox-checkpoint-cleanup', remoteMode: 0o755 },\n { name: 'agentbox-open', remoteBasename: 'agentbox-open', remoteMode: 0o755 },\n { name: 'gh-shim', remoteBasename: 'agentbox-gh-shim', remoteMode: 0o755 },\n { name: 'git-shim', remoteBasename: 'agentbox-git-shim', remoteMode: 0o755 },\n { name: 'ntn-shim', remoteBasename: 'agentbox-ntn-shim', remoteMode: 0o755 },\n { name: 'linear-shim', remoteBasename: 'agentbox-linear-shim', remoteMode: 0o755 },\n { name: 'custom-system-CLAUDE.md', remoteBasename: 'agentbox-custom-CLAUDE.md', remoteMode: 0o644 },\n { name: 'claude-managed-settings.json', remoteBasename: 'agentbox-managed-settings.json', remoteMode: 0o644 },\n { name: 'agentbox-codex-hooks.json', remoteBasename: 'agentbox-codex-hooks.json', remoteMode: 0o644 },\n { name: 'agentbox-setup-skill.md', remoteBasename: 'agentbox-setup-skill.md', remoteMode: 0o644 },\n] as const;\n\nexport interface ResolvedAsset extends RuntimeAsset {\n localPath: string;\n}\n\n/**\n * Build the candidate search paths for a given asset. Tries CLI runtime\n * first, then the monorepo source tree. The first one that exists wins.\n *\n * `cliRuntimeRoot` is provided by the caller because we don't know how the\n * embedding CLI lays out its dist (the @madarco/agentbox CLI puts dist + a\n * sibling runtime/ next to it; tests pass a tmp dir). Use the helper\n * `findCliRuntimeRoot()` below from the calling context that has the right\n * anchor (typically `import.meta.url` of an apps/cli module).\n */\nexport function candidatesFor(\n name: string,\n opts: { cliRuntimeRoot?: string; repoRoot?: string } = {},\n): string[] {\n const cliRoot = opts.cliRuntimeRoot;\n const monorepo = opts.repoRoot ?? guessRepoRoot();\n\n // Map logical → relative paths (relative to either anchor).\n const monorepoRelative: Record<string, string[]> = {\n 'install-box.sh': ['packages/sandbox-digitalocean/scripts/install-box.sh'],\n 'agentbox-ctl': ['packages/ctl/dist/bin.cjs'],\n 'agentbox-vnc-start': ['packages/sandbox-docker/scripts/agentbox-vnc-start'],\n 'agentbox-dockerd-start': ['packages/sandbox-docker/scripts/agentbox-dockerd-start'],\n 'agentbox-portless-trust': ['packages/sandbox-docker/scripts/agentbox-portless-trust'],\n 'agentbox-checkpoint-cleanup': ['packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup'],\n 'agentbox-open': ['packages/sandbox-docker/scripts/agentbox-open'],\n 'gh-shim': ['packages/sandbox-docker/scripts/gh-shim'],\n 'git-shim': ['packages/sandbox-docker/scripts/git-shim'],\n 'ntn-shim': ['packages/sandbox-docker/scripts/ntn-shim'],\n 'linear-shim': ['packages/sandbox-docker/scripts/linear-shim'],\n 'custom-system-CLAUDE.md': ['packages/sandbox-digitalocean/scripts/custom-system-CLAUDE.md'],\n 'claude-managed-settings.json': ['packages/sandbox-docker/scripts/claude-managed-settings.json'],\n 'agentbox-codex-hooks.json': ['packages/sandbox-docker/scripts/agentbox-codex-hooks.json'],\n 'agentbox-setup-skill.md': ['apps/cli/share/agentbox-setup/SKILL.md'],\n };\n\n // CLI-runtime-tree relative paths (mirrors the staging layout).\n const cliRelative: Record<string, string[]> = {\n 'install-box.sh': ['digitalocean/scripts/install-box.sh'],\n 'agentbox-ctl': ['digitalocean/ctl.cjs'],\n 'agentbox-vnc-start': ['digitalocean/agentbox-vnc-start', 'docker/packages/sandbox-docker/scripts/agentbox-vnc-start'],\n 'agentbox-dockerd-start': ['digitalocean/agentbox-dockerd-start', 'docker/packages/sandbox-docker/scripts/agentbox-dockerd-start'],\n 'agentbox-portless-trust': ['digitalocean/agentbox-portless-trust', 'docker/packages/sandbox-docker/scripts/agentbox-portless-trust'],\n 'agentbox-checkpoint-cleanup': ['digitalocean/agentbox-checkpoint-cleanup', 'docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup'],\n 'agentbox-open': ['digitalocean/agentbox-open', 'docker/packages/sandbox-docker/scripts/agentbox-open'],\n 'gh-shim': ['digitalocean/gh-shim', 'docker/packages/sandbox-docker/scripts/gh-shim'],\n 'git-shim': ['digitalocean/git-shim', 'docker/packages/sandbox-docker/scripts/git-shim'],\n 'ntn-shim': ['digitalocean/ntn-shim', 'docker/packages/sandbox-docker/scripts/ntn-shim'],\n 'linear-shim': ['digitalocean/linear-shim', 'docker/packages/sandbox-docker/scripts/linear-shim'],\n 'custom-system-CLAUDE.md': ['digitalocean/custom-system-CLAUDE.md'],\n 'claude-managed-settings.json': ['digitalocean/claude-managed-settings.json', 'docker/packages/sandbox-docker/scripts/claude-managed-settings.json'],\n 'agentbox-codex-hooks.json': ['digitalocean/agentbox-codex-hooks.json', 'docker/packages/sandbox-docker/scripts/agentbox-codex-hooks.json'],\n 'agentbox-setup-skill.md': ['digitalocean/agentbox-setup-skill.md', 'docker/apps/cli/share/agentbox-setup/SKILL.md'],\n };\n\n const out: string[] = [];\n if (cliRoot) {\n for (const rel of cliRelative[name] ?? []) out.push(resolve(cliRoot, rel));\n }\n for (const rel of monorepoRelative[name] ?? []) out.push(resolve(monorepo, rel));\n return out;\n}\n\n/**\n * Resolve every runtime asset to its absolute on-host path. Throws an\n * actionable error if any asset can't be found (lists every path tried).\n */\nexport function resolveRuntimeAssets(opts: {\n cliRuntimeRoot?: string;\n repoRoot?: string;\n} = {}): ResolvedAsset[] {\n const out: ResolvedAsset[] = [];\n const missing: Array<{ name: string; tried: string[] }> = [];\n for (const asset of RUNTIME_ASSETS) {\n const cands = candidatesFor(asset.name, opts);\n const hit = cands.find((p) => existsSync(p));\n if (!hit) {\n missing.push({ name: asset.name, tried: cands });\n continue;\n }\n out.push({ ...asset, localPath: hit });\n }\n if (missing.length > 0) {\n const lines = missing.flatMap((m) => [` - ${m.name}: tried`, ...m.tried.map((p) => ` ${p}`)]);\n throw new Error(\n `digitalocean: could not resolve runtime assets — these files are needed to install on the prepare VPS:\\n` +\n lines.join('\\n') +\n `\\n\\nIf you are running from the monorepo, ensure \\`pnpm -w build\\` has run so packages/ctl/dist/bin.cjs exists. ` +\n `If you are running from a published CLI bundle, the runtime/digitalocean tree should be staged automatically.`,\n );\n }\n return out;\n}\n\n/** Best-effort: walk up from this file looking for `pnpm-workspace.yaml`. */\nfunction guessRepoRoot(): string {\n let cur = SELF;\n for (let i = 0; i < 8; i++) {\n if (existsSync(resolve(cur, 'pnpm-workspace.yaml'))) return cur;\n const parent = dirname(cur);\n if (parent === cur) break;\n cur = parent;\n }\n return SELF; // fall through to itself; resolution will fail with a clear error\n}\n","/**\n * Persisted record of what `agentbox prepare --provider digitalocean` has built.\n * Lives at `~/.agentbox/digitalocean-prepared.json` so the auto-prepare gate\n * (`ensureDigitalOceanBaseSnapshot()`) and runtime image resolution can see it.\n *\n * Only the shared `base` snapshot is recorded here — built once per DigitalOcean\n * project / API token: Ubuntu + deps + agentbox-ctl + agents + agent-browser,\n * baked from `install-box.sh`.\n *\n * The per-project snapshot tier is NOT a separate registry: it's the existing\n * `agentbox checkpoint create --set-default` + `box.defaultCheckpointDigitalOcean`\n * flow (see `docs/cloud-create-flow.md` §\"base vs project snapshot\"), and\n * auto-capture at the end of setup is driven by the `/agentbox-setup` skill\n * (`agentbox-ctl checkpoint --set-default`), cross-provider. So there's no\n * `projects[<hash>]` map here.\n *\n * Schema versioned so future shape changes can migrate.\n */\n\nimport { claudeInstallFingerprint, computeContextSha256, preparedStatePathFor, readPreparedStateRaw, writePreparedStateRaw } from '@agentbox/sandbox-core';\nimport { findStagedCliRuntimeRoot, resolveRuntimeAssets } from './runtime-assets.js';\n\n/**\n * Schema history:\n * 1 — `base.imageId`, `base.description`, `base.createdAt`,\n * `base.installScriptSha256?`\n * 2 — `base.installScriptSha256` → `base.contextSha256` (now covers every\n * asset we scp'd in, not just the install script); `base.cliVersion`\n * and `base.cliCommit?` added so we can warn when an old snapshot\n * predates the running CLI.\n *\n * Read-time migration is lossy in one direction: a schema-1 file is lifted\n * to schema 2 by *renaming* `installScriptSha256` to `contextSha256`. The\n * hash doesn't change but the meaning narrows (install script only → full\n * asset list), so the next `agentbox prepare --provider digitalocean` run will\n * recompute and overwrite. A legacy `projects` key (an early, never-wired\n * per-project tier) is simply ignored — removing the field doesn't break\n * reads, so no schema bump is needed.\n */\nconst SCHEMA = 2 as const;\n\nexport interface PreparedBaseSnapshot {\n /** DigitalOcean image id (numeric — opaque, but stable across `getImage` calls). */\n imageId: number;\n /** User-facing description (matches the firewall-dashboard rows). */\n description: string;\n /** ISO timestamp of bake-completion. */\n createdAt: string;\n /**\n * Deterministic SHA-256 of the build context (every file scp'd into the\n * prepare VPS). Rebuild when it changes.\n */\n contextSha256?: string;\n /** CLI version that produced this snapshot (informational). */\n cliVersion?: string;\n /** Git short SHA of the CLI build (informational). */\n cliCommit?: string;\n}\n\nexport interface PreparedDigitalOceanState {\n schema: typeof SCHEMA;\n /** The shared base snapshot. Absent until first `agentbox prepare`. */\n base?: PreparedBaseSnapshot;\n}\n\ninterface LegacyV1Base {\n imageId: number;\n description: string;\n createdAt: string;\n installScriptSha256?: string;\n}\n\ninterface LegacyV1State {\n schema: 1;\n base?: LegacyV1Base;\n}\n\nexport function preparedStatePath(): string {\n return preparedStatePathFor('digitalocean');\n}\n\nexport function readPreparedState(): PreparedDigitalOceanState {\n const raw = readPreparedStateRaw('digitalocean');\n if (raw === null || typeof raw !== 'object') return { schema: SCHEMA };\n const parsed = raw as Partial<PreparedDigitalOceanState> | LegacyV1State;\n if ((parsed as { schema?: unknown }).schema === 1) {\n const v1 = parsed as LegacyV1State;\n return migrateFromV1(v1);\n }\n if (parsed.schema !== SCHEMA) {\n // Unknown schema: don't crash, just refuse to read — the file will be\n // overwritten on the next successful prepare.\n return { schema: SCHEMA };\n }\n return {\n schema: SCHEMA,\n base: parsed.base,\n };\n}\n\nfunction migrateFromV1(v1: LegacyV1State): PreparedDigitalOceanState {\n // The v1 `installScriptSha256` covered only `install-box.sh`, not the full\n // asset list a v2 `contextSha256` represents. Lifting it forward as a\n // placeholder fingerprint means the next prepare run will mismatch and\n // rebuild — exactly what we want, since the broader hash semantics also\n // changed.\n const base: PreparedBaseSnapshot | undefined = v1.base\n ? {\n imageId: v1.base.imageId,\n description: v1.base.description,\n createdAt: v1.base.createdAt,\n contextSha256: v1.base.installScriptSha256,\n }\n : undefined;\n return {\n schema: SCHEMA,\n base,\n };\n}\n\nexport function writePreparedState(state: PreparedDigitalOceanState): void {\n writePreparedStateRaw('digitalocean', state);\n}\n\n/**\n * Convenience helper: update one field of the state without forcing callers\n * to read/merge/write themselves.\n */\nexport function updatePreparedState(mutate: (s: PreparedDigitalOceanState) => void): void {\n const s = readPreparedState();\n mutate(s);\n writePreparedState(s);\n}\n\n/**\n * Compute the CURRENT build-context fingerprint for the digitalocean base snapshot\n * (the SHA over every file `prepare` would scp into the prepare VPS).\n * Side-effect-free — never builds. Returns `undefined` when the runtime\n * assets can't be resolved (dev tree without `pnpm -w build`) so the CLI\n * can degrade to \"can't tell, don't nag\".\n *\n * Used by `evaluateBaseFreshness` to compare against the stored value in\n * `digitalocean-prepared.json.base.contextSha256`. Must produce a byte-identical\n * hash to the one `prepare` writes — both go through the same\n * `resolveRuntimeAssets` + `computeContextSha256` chain.\n */\nexport async function currentDigitalOceanBaseFingerprintLive(\n claudeInstall: 'native' | 'npm' = 'native',\n): Promise<string | undefined> {\n try {\n const assets = resolveRuntimeAssets({ cliRuntimeRoot: findStagedCliRuntimeRoot() });\n // Fold in claudeInstall exactly as `prepare` does — otherwise an npm-baked\n // base never matches the stored (npm-folded) fingerprint.\n return claudeInstallFingerprint(\n await computeContextSha256(assets.map((a) => ({ rel: a.name, abs: a.localPath }))),\n claudeInstall,\n );\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,eAAe;AACxB,SAAS,eAAe;AGFxB,SAAS,iBAAiB;AAE1B;EACE;EACA,cAAAA;EACA;EACA,gBAAAC;EACA;EACA;OACK;AACP,SAAS,WAAAC,gBAAe;AACxB,SAAS,SAAS,WAAAC,gBAAe;AACjC;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;OACK;AIPP,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,WAAAC,UAAS,WAAAC,gBAAe;AACjC,SAAS,qBAAqB;API9B,IAAM,oBAAoB,CAAC,sBAAsB,sBAAsB;AAEvE,IAAI,SAAS;AAEN,SAAS,8BAAoC;AAClD,MAAI,OAAQ;AACZ,WAAS;AACT,6BAA2B,QAAQ,QAAQ,GAAG,aAAa,aAAa,CAAC;AAC3E;AAEA,SAAS,2BAA2B,MAAoB;AACtD,MAAI,CAAC,WAAW,IAAI,EAAG;AACvB,M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E,QAAQ,OAAO;AACrE,QAAM,SAAS;AACf,MAAK,OAAgC,WAAW,GAAG;AACjD,UAAM,KAAK;AACX,WAAO,cAAc,EAAE;EACzB;AACA,MAAI,OAAO,WAAW,QAAQ;AAG5B,WAAO,EAAE,QAAQ,OAAO;EAC1B;AACA,SAAO;IACL,QAAQ;IACR,MAAM,OAAO;EACf;AACF;AAEA,SAAS,cAAc,IAA8C;AAMnE,QAAM,OAAyC,GAAG,OAC9C;IACE,SAAS,GAAG,KAAK;IACjB,aAAa,GAAG,KAAK;IACrB,WAAW,GAAG,KAAK;IACnB,eAAe,GAAG,KAAK;EACzB,IACA;AACJ,SAAO;IACL,QAAQ;IACR;EACF;AACF;AAEO,SAAS,mBAAmB,OAAwC;AACzE,wBAAsB,gBAAgB,KAAK;AAC7C;AAMO,SAAS,oBAAoB,QAAsD;AACxF,QAAM,IAAI,kBAAkB;AAC5B,SAAO,CAAC;AACR,qBAAmB,CAAC;AACtB;AAcA,eAAsB,uCACpB,gBAAkC,UACL;AAC7B,MAAI;AACF,UAAM,SAAS,qBAAqB,EAAE,gBAAgB,yBAAyB,EAAE,CAAC;AAGlF,WAAO;MACL,MAAM,qBAAqB,OAAO,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,KAAK,EAAE,UAAU,EAAE,CAAC;MACjF;IACF;EACF,QAAQ;AACN,WAAO;EACT;AACF;","names":["existsSync","readFileSync","homedir","resolve","existsSync","dirname","resolve","opts","existsSync","readFileSync","resolve","homedir","log","raceTimeout","dirname"]}
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
projectDirSegment,
|
|
9
9
|
sanitizeMnemonic,
|
|
10
10
|
setConfigValue
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-H6A4BQMG.js";
|
|
12
12
|
import {
|
|
13
13
|
AmbiguousBoxError,
|
|
14
14
|
BOX_HOME,
|
|
@@ -70,7 +70,7 @@ import {
|
|
|
70
70
|
syncAgentboxSshConfig,
|
|
71
71
|
trustWorkspace,
|
|
72
72
|
writeClaudeMergedRegistries
|
|
73
|
-
} from "./chunk-
|
|
73
|
+
} from "./chunk-3MDYQROX.js";
|
|
74
74
|
|
|
75
75
|
// ../../packages/sandbox-docker/dist/index.js
|
|
76
76
|
import { spawnSync } from "child_process";
|
|
@@ -9320,4 +9320,4 @@ export {
|
|
|
9320
9320
|
ensureBoxBrowser,
|
|
9321
9321
|
ensureBoxBrowserShowingApp
|
|
9322
9322
|
};
|
|
9323
|
-
//# sourceMappingURL=chunk-
|
|
9323
|
+
//# sourceMappingURL=chunk-OSPM4Q5V.js.map
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
renderInnerCommand,
|
|
9
9
|
resolveCloudCheckpoint,
|
|
10
10
|
writeCloudCheckpointManifest
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-4HPLS5HJ.js";
|
|
12
12
|
import {
|
|
13
13
|
UserFacingError,
|
|
14
14
|
claudeInstallFingerprint,
|
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
stageOpencodeStaticForUpload,
|
|
25
25
|
writeManagedSecrets,
|
|
26
26
|
writePreparedStateRaw
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-3MDYQROX.js";
|
|
28
28
|
|
|
29
29
|
// ../../packages/sandbox-vercel/dist/chunk-6SDDZRAG.js
|
|
30
30
|
import { existsSync, readFileSync } from "fs";
|
|
@@ -1665,4 +1665,4 @@ export {
|
|
|
1665
1665
|
vercelProvider,
|
|
1666
1666
|
providerModule
|
|
1667
1667
|
};
|
|
1668
|
-
//# sourceMappingURL=chunk-
|
|
1668
|
+
//# sourceMappingURL=chunk-QHISF6O6.js.map
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
readPreparedStateRaw,
|
|
9
9
|
writeManagedSecrets,
|
|
10
10
|
writePreparedStateRaw
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-3MDYQROX.js";
|
|
12
12
|
|
|
13
13
|
// ../../packages/sandbox-e2b/dist/chunk-WQRH5SXA.js
|
|
14
14
|
import { existsSync, readFileSync } from "fs";
|
|
@@ -324,4 +324,4 @@ export {
|
|
|
324
324
|
currentE2bBaseFingerprintLive,
|
|
325
325
|
ensureE2bBaseTemplate
|
|
326
326
|
};
|
|
327
|
-
//# sourceMappingURL=chunk-
|
|
327
|
+
//# sourceMappingURL=chunk-RFRWS5CD.js.map
|
package/dist/chunk-WJFZJZIM.js
CHANGED
|
File without changes
|
|
File without changes
|
|
@@ -14,17 +14,17 @@ import {
|
|
|
14
14
|
resolveDockerfileContext,
|
|
15
15
|
setDaytonaCredentials,
|
|
16
16
|
writePreparedDaytonaState
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-7DPDUZ7L.js";
|
|
18
18
|
import {
|
|
19
19
|
createCloudProvider
|
|
20
|
-
} from "./chunk-
|
|
21
|
-
import "./chunk-
|
|
22
|
-
import "./chunk-
|
|
20
|
+
} from "./chunk-4HPLS5HJ.js";
|
|
21
|
+
import "./chunk-OSPM4Q5V.js";
|
|
22
|
+
import "./chunk-H6A4BQMG.js";
|
|
23
23
|
import {
|
|
24
24
|
claudeInstallFingerprint,
|
|
25
25
|
errSummary,
|
|
26
26
|
stageAllAgentStatic
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-3MDYQROX.js";
|
|
28
28
|
import "./chunk-G3H2L3O2.js";
|
|
29
29
|
import "./chunk-WJFZJZIM.js";
|
|
30
30
|
|
|
@@ -319,4 +319,4 @@ export {
|
|
|
319
319
|
resolveDockerfileContext,
|
|
320
320
|
setDaytonaCredentials
|
|
321
321
|
};
|
|
322
|
-
//# sourceMappingURL=dist-
|
|
322
|
+
//# sourceMappingURL=dist-2N3XHMBQ.js.map
|
|
@@ -16,28 +16,33 @@ import {
|
|
|
16
16
|
isAttemptTimeout,
|
|
17
17
|
isRetriable,
|
|
18
18
|
makeDigitalOceanClient,
|
|
19
|
+
mapDigitalOceanProvisionError,
|
|
19
20
|
maskKey,
|
|
20
21
|
normalizeSourceCidr,
|
|
21
22
|
preparedStatePath,
|
|
22
23
|
readDigitalOceanCredStatus,
|
|
23
24
|
readPreparedState,
|
|
25
|
+
resolveProjectChoice,
|
|
24
26
|
resolveRuntimeAssets,
|
|
25
27
|
secretsPath,
|
|
26
28
|
setDigitalOceanCredentials,
|
|
27
29
|
sshInboundRules,
|
|
28
30
|
syncFirewallSource,
|
|
29
31
|
updatePreparedState,
|
|
32
|
+
validateSizeChoice,
|
|
30
33
|
withDigitalOceanRetry,
|
|
31
34
|
writePreparedState
|
|
32
|
-
} from "./chunk-
|
|
35
|
+
} from "./chunk-LJMGHFLZ.js";
|
|
33
36
|
import {
|
|
34
37
|
createCloudProvider
|
|
35
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-4HPLS5HJ.js";
|
|
36
39
|
import {
|
|
37
40
|
detectPortless,
|
|
38
41
|
portlessDoctorRow
|
|
39
|
-
} from "./chunk-
|
|
40
|
-
import
|
|
42
|
+
} from "./chunk-OSPM4Q5V.js";
|
|
43
|
+
import {
|
|
44
|
+
loadEffectiveConfig
|
|
45
|
+
} from "./chunk-H6A4BQMG.js";
|
|
41
46
|
import {
|
|
42
47
|
UserFacingError,
|
|
43
48
|
claudeInstallFingerprint,
|
|
@@ -52,7 +57,7 @@ import {
|
|
|
52
57
|
stageClaudeStaticForUpload,
|
|
53
58
|
stageCodexStaticForUpload,
|
|
54
59
|
stageOpencodeStaticForUpload
|
|
55
|
-
} from "./chunk-
|
|
60
|
+
} from "./chunk-3MDYQROX.js";
|
|
56
61
|
import "./chunk-G3H2L3O2.js";
|
|
57
62
|
import "./chunk-WJFZJZIM.js";
|
|
58
63
|
|
|
@@ -167,58 +172,6 @@ async function pollUntil(label, check, opts = {}) {
|
|
|
167
172
|
interval = Math.min(interval * 2, max);
|
|
168
173
|
}
|
|
169
174
|
}
|
|
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
175
|
async function mintPrepareKey() {
|
|
223
176
|
const root = resolve(homedirOrCwd(), ".agentbox", "digitalocean", `prepare-${Date.now().toString(36)}`);
|
|
224
177
|
const key = await mintSshKey(root, `agentbox-prepare-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`);
|
|
@@ -431,6 +384,18 @@ async function prepareDigitalOcean(opts = {}) {
|
|
|
431
384
|
ipv6: false
|
|
432
385
|
});
|
|
433
386
|
dropletId = created.droplet.id;
|
|
387
|
+
const wantedProject = (opts.project ?? (await loadEffectiveConfig(opts.hostWorkspace ?? process.cwd())).effective.box.digitaloceanProject).trim();
|
|
388
|
+
if (wantedProject.length > 0) {
|
|
389
|
+
try {
|
|
390
|
+
const projectId = resolveProjectChoice(wantedProject, await client2.listProjects());
|
|
391
|
+
await client2.assignProjectResources(projectId, [`do:droplet:${String(dropletId)}`]);
|
|
392
|
+
progress(`bake droplet assigned to project ${wantedProject}`);
|
|
393
|
+
} catch (assignErr) {
|
|
394
|
+
progress(
|
|
395
|
+
`WARN \u2014 could not assign the bake droplet to project ${wantedProject} (continuing): ${assignErr instanceof Error ? assignErr.message : String(assignErr)}`
|
|
396
|
+
);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
434
399
|
progress(`droplet ${String(dropletId)} created; waiting for it to boot`);
|
|
435
400
|
const droplet = await pollUntil(
|
|
436
401
|
`droplet ${String(dropletId)} active`,
|
|
@@ -994,6 +959,11 @@ var digitaloceanBackend = {
|
|
|
994
959
|
const sizeCatalog = await c.listSizes();
|
|
995
960
|
validateSizeChoice(choice, sizeCatalog, snapshotMeta);
|
|
996
961
|
const plan = sizeCatalog.find((s) => s.slug === size);
|
|
962
|
+
const projectWanted = (req.project ?? "").trim();
|
|
963
|
+
let projectId = null;
|
|
964
|
+
if (projectWanted.length > 0) {
|
|
965
|
+
projectId = resolveProjectChoice(projectWanted, await c.listProjects());
|
|
966
|
+
}
|
|
997
967
|
const inboundPolicy = parseInboundSpec(req.inbound);
|
|
998
968
|
const egressOverride = req.env?.AGENTBOX_DIGITALOCEAN_FIREWALL_SOURCE ?? process.env.AGENTBOX_DIGITALOCEAN_FIREWALL_SOURCE;
|
|
999
969
|
const hostEgress = inboundPolicy.mode === "open" ? null : egressOverride ? normalizeSourceCidr(egressOverride) : `${await detectEgressIp({ onLog })}/32`;
|
|
@@ -1044,6 +1014,16 @@ var digitaloceanBackend = {
|
|
|
1044
1014
|
}
|
|
1045
1015
|
dropletId = created.droplet.id;
|
|
1046
1016
|
progress(`droplet ${String(dropletId)} created; waiting for it to boot`);
|
|
1017
|
+
if (projectId !== null) {
|
|
1018
|
+
try {
|
|
1019
|
+
await c.assignProjectResources(projectId, [`do:droplet:${String(dropletId)}`]);
|
|
1020
|
+
progress(`droplet ${String(dropletId)} assigned to project ${projectWanted}`);
|
|
1021
|
+
} catch (assignErr) {
|
|
1022
|
+
onLog(
|
|
1023
|
+
`digitalocean: WARN \u2014 could not assign droplet ${String(dropletId)} to project ${projectWanted} (continuing; it stays in the account's default project): ${assignErr instanceof Error ? assignErr.message : String(assignErr)}`
|
|
1024
|
+
);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1047
1027
|
const droplet = await pollUntil(
|
|
1048
1028
|
`droplet ${String(dropletId)} active`,
|
|
1049
1029
|
async () => {
|
|
@@ -1419,6 +1399,7 @@ export {
|
|
|
1419
1399
|
providerModule,
|
|
1420
1400
|
readDigitalOceanCredStatus,
|
|
1421
1401
|
readPreparedState,
|
|
1402
|
+
resolveProjectChoice,
|
|
1422
1403
|
resolveRuntimeAssets,
|
|
1423
1404
|
scpDownload,
|
|
1424
1405
|
scpUpload,
|
|
@@ -1434,4 +1415,4 @@ export {
|
|
|
1434
1415
|
withDigitalOceanRetry,
|
|
1435
1416
|
writePreparedState
|
|
1436
1417
|
};
|
|
1437
|
-
//# sourceMappingURL=dist-
|
|
1418
|
+
//# sourceMappingURL=dist-3M53BF4E.js.map
|