@madarco/agentbox 0.24.3 → 0.24.4
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 +11 -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-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/{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 +22 -18
- package/dist/index.js.map +1 -1
- package/dist/{prepared-state-BUO75YLZ-RQRFFBJW.js → prepared-state-BUO75YLZ-46W2PAHH.js} +2 -2
- package/package.json +5 -5
- package/runtime/_shared/ctl.cjs +8 -0
- package/runtime/digitalocean/ctl.cjs +8 -0
- package/runtime/docker/packages/ctl/dist/bin.cjs +8 -0
- package/runtime/e2b/ctl.cjs +8 -0
- package/runtime/hetzner/ctl.cjs +8 -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/ctl.cjs +8 -0
- 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 → bwxNg9k-GQFyi2ouG8Aeh}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{4CStLAgdl_oxCRh8votRw → bwxNg9k-GQFyi2ouG8Aeh}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{4CStLAgdl_oxCRh8votRw → bwxNg9k-GQFyi2ouG8Aeh}/_ssgManifest.js +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/config/src/providers.ts","../../../packages/config/src/types.ts","../../../packages/config/src/parse.ts","../../../packages/config/src/paths.ts","../../../packages/config/src/load.ts","../../../packages/config/src/image.ts","../../../packages/config/src/checkpoint.ts","../../../packages/config/src/size.ts","../../../packages/config/src/write.ts"],"sourcesContent":["/**\n * Single source of truth for the set of sandbox providers.\n *\n * Adding one row to `PROVIDERS` is the *only* place a new provider's identity\n * has to be registered. This table drives, by derivation:\n * - the `ProviderKind` union (below),\n * - the `box.provider` enum + its description (see `types.ts`),\n * - the per-provider `box.image<P>` / `box.size<P>` / `box.defaultCheckpoint<P>`\n * entries in `KEY_REGISTRY` (generated in `types.ts`),\n * - the CLI's known/cloud provider lists, the install-wizard picker\n * labels/hints, the wizard's rebuild-time estimate, and the doctor groups.\n *\n * The interface fields on `UserConfig`/`EffectiveConfig` and the JSON schema\n * still list the per-provider keys explicitly (static types can't be generated\n * from a runtime array); a test (`test/providers.test.ts`) fails if either\n * drifts from this table.\n */\n\nexport interface ProviderMeta {\n /** Canonical name — MUST equal the `@agentbox/sandbox-<name>` package suffix. */\n readonly name: string;\n /** 'local' = docker; 'cloud' = has a CloudBackend + a prepared base snapshot. */\n readonly kind: 'local' | 'cloud';\n /** Human label for the install-wizard picker. */\n readonly label: string;\n /** One-line hint for the install-wizard picker. */\n readonly loginHint: string;\n /** Rough base-image/snapshot bake time (minutes) shown by the install wizard. */\n readonly rebuildMinutes: string;\n /** Fragment describing this backend, joined into the `box.provider` enum description. */\n readonly blurb: string;\n /** Description of the per-provider `box.size<P>` KEY_REGISTRY entry. */\n readonly sizeDesc: string;\n /** Description of the per-provider `box.image<P>` KEY_REGISTRY entry. */\n readonly imageDesc: string;\n}\n\nexport const PROVIDERS = [\n {\n name: 'docker',\n kind: 'local',\n label: 'Docker (local)',\n loginHint: 'builds a ~1GB local image; no login needed',\n rebuildMinutes: '1',\n blurb: 'local Docker containers',\n sizeDesc:\n 'Per-provider override of `box.size` for docker. Reserved — docker sizing is controlled via `box.memory` / `box.cpus` / `box.disk`.',\n imageDesc:\n 'Per-provider override of `box.image` for docker (local docker image ref, e.g. `agentbox/box:dev`). Wins over the generic when set.',\n },\n {\n name: 'daytona',\n kind: 'cloud',\n label: 'Daytona (cloud sandbox)',\n loginHint: 'approve a browser sign-in link',\n rebuildMinutes: '7',\n blurb: 'Daytona Cloud sandboxes',\n sizeDesc:\n 'Per-provider override of `box.size` for daytona. `cpu-memory-disk` GB spec (e.g. `4-8-20`). Only honored on the image/Dockerfile create path; on the snapshot path the size is fixed at bake time (Daytona rejects custom resources on snapshot-resume).',\n imageDesc:\n 'Per-provider override of `box.image` for daytona (named snapshot, e.g. `agentbox-base-<fingerprint>`). Written by `agentbox prepare --provider daytona`.',\n },\n {\n name: 'hetzner',\n kind: 'cloud',\n label: 'Hetzner (cloud VPS)',\n loginHint: 'paste an API token from the Hetzner Console',\n rebuildMinutes: '7-10',\n blurb: 'Hetzner Cloud VPSes',\n sizeDesc:\n 'Per-provider override of `box.size` for hetzner. Server type string (e.g. `cx23`, `cx33`, `cx43`).',\n imageDesc:\n 'Per-provider override of `box.image` for hetzner (image description, e.g. `agentbox-base-<fingerprint>`). Written by `agentbox prepare --provider hetzner`.',\n },\n {\n name: 'vercel',\n kind: 'cloud',\n label: 'Vercel (cloud microVM)',\n loginHint: 'installs the Vercel sandbox CLI, then a browser sign-in',\n rebuildMinutes: '5-10',\n blurb: 'Vercel Sandboxes',\n sizeDesc:\n 'Per-provider override of `box.size` for vercel. vCPU count — one of `1`, `2`, `4`, `8` (Vercel couples RAM at 2048 MB/vCPU). Default 2.',\n imageDesc:\n 'Per-provider override of `box.image` for vercel (snapshot id, e.g. `snap_…`). Written by `agentbox prepare --provider vercel`.',\n },\n {\n name: 'e2b',\n kind: 'cloud',\n label: 'E2B (cloud microVM)',\n loginHint: 'paste an API key from the E2B dashboard',\n rebuildMinutes: '2',\n blurb: 'E2B microVMs',\n sizeDesc:\n 'Per-provider override of `box.size` for e2b. `cpu-memory` GB spec (e.g. `4-8`). Template-level: baked by `agentbox prepare --provider e2b --size <spec>`; E2B rejects per-create resources.',\n imageDesc:\n 'Per-provider override of `box.image` for e2b (template id or `name:tag`, e.g. `agentbox-base:latest`). Written by `agentbox prepare --provider e2b`.',\n },\n {\n name: 'digitalocean',\n kind: 'cloud',\n label: 'DigitalOcean (cloud VPS)',\n loginHint: 'paste a Personal Access Token from the DigitalOcean Console',\n rebuildMinutes: '7-10',\n blurb: 'DigitalOcean Droplets',\n sizeDesc:\n 'Per-provider override of `box.size` for digitalocean. Droplet size slug (e.g. `s-2vcpu-4gb`, `s-4vcpu-8gb`).',\n imageDesc:\n 'Per-provider override of `box.image` for digitalocean (numeric snapshot id). Written by `agentbox prepare --provider digitalocean`.',\n },\n] as const satisfies readonly ProviderMeta[];\n\n/** Sandbox backend new boxes are created on. Derived from the `PROVIDERS` table. */\nexport type ProviderKind = (typeof PROVIDERS)[number]['name'];\n\n/** All provider names, in canonical order. */\nexport const PROVIDER_NAMES: readonly ProviderKind[] = PROVIDERS.map((p) => p.name);\n\n/** Cloud provider names only (everything except docker). */\nexport const CLOUD_PROVIDER_NAMES: readonly ProviderKind[] = PROVIDERS.filter(\n (p) => p.kind === 'cloud',\n).map((p) => p.name);\n\nexport function isProviderKind(name: string): name is ProviderKind {\n return (PROVIDER_NAMES as readonly string[]).includes(name);\n}\n\nexport function providerMeta(name: ProviderKind): ProviderMeta {\n const m = PROVIDERS.find((p) => p.name === name);\n if (!m) throw new Error(`unknown provider: ${String(name)}`);\n return m;\n}\n\n/**\n * Capitalize a provider name for its config-key suffix: `e2b` -> `E2b`,\n * `docker` -> `Docker`, `digitalocean` -> `Digitalocean`. First char upper,\n * the rest verbatim — matches the hand-written keys this table replaced.\n */\nexport function providerKeyCap(name: string): string {\n return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\n/** Per-provider config key, e.g. `('image','hetzner')` -> `'box.imageHetzner'`. */\nexport function perProviderConfigKey(\n base: 'image' | 'size' | 'defaultCheckpoint',\n provider: string,\n): string {\n return `box.${base}${providerKeyCap(provider)}`;\n}\n","/**\n * Layered user config. The same shape is accepted at three layers:\n * - global ~/.agentbox/config.yaml\n * - project ~/.agentbox/projects/<hash>/config.yaml\n * - workspace defaults: block in ./agentbox.yaml\n *\n * Plus a CLI-flag layer at runtime. Precedence (highest wins):\n * cli > workspace > project > global > built-in defaults.\n */\n\nimport {\n PROVIDERS,\n PROVIDER_NAMES,\n perProviderConfigKey,\n type ProviderKind,\n} from './providers.js';\n\nexport type IdeFlavor = 'vscode' | 'cursor' | 'auto';\nexport type EngineKind = 'orbstack' | 'docker-desktop' | 'other' | 'auto';\nexport type BrowserKind = 'agent-browser' | 'playwright' | 'both';\n/** Sandbox backend new boxes are created on. Defined in `providers.ts` (the single source of truth) and re-exported here for back-compat. */\nexport type { ProviderKind };\n/**\n * How the base image/snapshot installs Claude Code at bake time. `native`\n * (Anthropic's installer, the default) or `npm` (`@anthropic-ai/claude-code`) —\n * an opt-in fallback for cloud egress IPs whose CDN the native installer 403s.\n */\nexport type ClaudeInstallMethod = 'native' | 'npm';\n/**\n * How a box's `git push` reaches GitHub:\n * - `relay` — the box asks the host relay to push with the HOST's credentials\n * (they never enter the box). Docker boxes always use this; for a cloud box it\n * runs through the host relay's cloud poller (git-bundle pull-back).\n * - `lease` — the relay/plane leases a short-lived GitHub-App token and the box\n * pushes directly with it (keeps working with the laptop off). Needs a\n * reachable relay/plane with a GitHub App configured.\n * - `direct` — the box holds a COPY of your git credentials (token + SSH key)\n * and pushes/pulls/signs entirely on its own, so it keeps working with the\n * laptop off and needs no hub. Selected via `--with-credentials`, which copies\n * the credentials in behind a confirmation prompt. Dangerous: the credentials\n * live inside the box and in any snapshot/checkpoint of it. Cloud boxes only.\n * - `auto` (default) — lease when a control plane is configured for the box\n * (`relay.controlPlaneUrl`), else relay. Today's behavior.\n * Docker boxes ignore this (always `relay` — they bind-mount the host `.git`).\n */\nexport type GitPushMode = 'auto' | 'relay' | 'lease' | 'direct';\n/** Where `agentbox claude|codex|opencode` opens the attached session when the host\n * shell is running inside tmux, cmux, Herdr, or iTerm2. `same` keeps today's inline behavior. */\nexport type AttachOpenIn = 'split' | 'window' | 'tab' | 'same';\n/** Where a background `-i` (queued) run opens the box once the worker has created\n * it. `none` (default) opens nothing — the historical behavior. The open is\n * driven by the host relay's queue worker when the box becomes ready, not at\n * submit time, so there is no `same` (inline) mode here. */\nexport type QueueOpenIn = 'none' | 'split' | 'window' | 'tab';\n\nexport interface UserConfig {\n /**\n * Config-file shape version. Stamped to `1` on first write so future\n * migrations (e.g. a renamed key, a leaf-shape change) have a stable\n * read-time discriminator. No behavioural effect yet — placeholder for\n * later. Loader strips it before merge so it never leaks into\n * `EffectiveConfig`.\n */\n schema?: number;\n box?: {\n provider?: ProviderKind;\n hostSnapshot?: boolean;\n defaultCheckpoint?: string;\n /** Per-provider override of `defaultCheckpoint`. Resolved before falling back to the global. */\n defaultCheckpointDocker?: string;\n defaultCheckpointDaytona?: string;\n defaultCheckpointHetzner?: string;\n defaultCheckpointVercel?: string;\n defaultCheckpointE2b?: string;\n defaultCheckpointDigitalocean?: string;\n /**\n * Generic VM-size fallback for cloud providers. Provider-interpreted:\n * Hetzner = server type string (e.g. `cx33`); Daytona = `cpu-memory-disk`\n * GB spec (e.g. `4-8-20`); Vercel = vCPU count (`1`/`2`/`4`/`8`);\n * E2B = `cpu-memory` GB spec (e.g. `4-8`), applied at `prepare` time.\n * Per-provider `size{Provider}` wins over this. Docker ignores it (it uses\n * `memory`/`cpus`/`disk`).\n */\n size?: string;\n sizeDocker?: string;\n sizeDaytona?: string;\n sizeHetzner?: string;\n sizeVercel?: string;\n sizeE2b?: string;\n sizeDigitalocean?: string;\n withPlaywright?: boolean;\n /**\n * How the base image/snapshot installs Claude Code at bake time. Bake-time\n * only (read by `agentbox prepare`, not `create`); `npm` is a fallback for\n * cloud egress IPs the native installer's CDN 403s.\n */\n claudeInstall?: ClaudeInstallMethod;\n withEnv?: boolean;\n resyncOnStart?: boolean;\n vnc?: boolean;\n autoApproveHostActions?: boolean;\n autoApproveSafeHostActions?: boolean;\n isolateClaudeConfig?: boolean;\n isolateCodexConfig?: boolean;\n isolateOpencodeConfig?: boolean;\n image?: string;\n /**\n * Per-provider override of `image`. Written by `agentbox prepare\n * --provider <name>` so a daytona prepare can't poison a hetzner create.\n * Resolved before falling back to the generic.\n */\n imageDocker?: string;\n imageDaytona?: string;\n imageHetzner?: string;\n imageVercel?: string;\n imageE2b?: string;\n imageDigitalocean?: string;\n imageRegistry?: string;\n dockerCacheShared?: boolean;\n memory?: number;\n cpus?: number;\n pidsLimit?: number;\n disk?: string;\n bundleDepth?: number;\n hetznerLocation?: string;\n digitaloceanRegion?: string;\n vercelTimeoutMs?: number;\n vercelNetworkPolicy?: string;\n e2bTimeoutMs?: number;\n cpMaxBytes?: number;\n credentialSync?: boolean;\n inbound?: string;\n };\n checkpoint?: {\n maxLayers?: number;\n };\n claude?: {\n sessionName?: string;\n dangerouslySkipPermissions?: boolean;\n };\n codex?: {\n sessionName?: string;\n dangerouslySkipPermissions?: boolean;\n };\n opencode?: {\n sessionName?: string;\n };\n attach?: {\n openIn?: AttachOpenIn;\n cmuxStatus?: boolean;\n herdrStatus?: boolean;\n };\n code?: {\n ide?: IdeFlavor;\n wait?: boolean;\n timeoutMs?: number;\n autoTerminals?: boolean;\n };\n shell?: {\n user?: string;\n login?: boolean;\n tmux?: boolean;\n };\n ssh?: {\n autoConfig?: boolean;\n };\n engine?: {\n kind?: EngineKind;\n };\n browser?: {\n default?: BrowserKind;\n };\n relay?: {\n port?: number;\n /**\n * Public HTTPS URL of a deployed control plane (the hosted Next.js +\n * Postgres app). When set, newly created cloud boxes point at it for their\n * centralized concerns — git-token leasing, permission state, the box\n * registry/events — and push to GitHub directly with a leased token, so\n * they keep working with the laptop off. Empty/unset = laptop-local relay\n * (the default). Set via `agentbox control-plane set-url`.\n */\n controlPlaneUrl?: string;\n };\n git?: {\n pushMode?: GitPushMode;\n };\n vnc?: {\n containerPort?: number;\n };\n portless?: {\n enabled?: boolean;\n stateDir?: string;\n };\n autopause?: {\n enabled?: boolean;\n maxRunningBoxes?: number;\n idleMinutes?: number;\n };\n queue?: {\n enabled?: boolean;\n maxConcurrent?: number;\n maxWorking?: number;\n idleGraceSeconds?: number;\n openIn?: QueueOpenIn;\n };\n cloud?: {\n useCurrentBranch?: boolean;\n };\n maintenance?: {\n pruneProjectConfigs?: boolean;\n pruneProjectConfigsEvery?: number;\n };\n update?: {\n /**\n * Daily background check for a newer published CLI (npm registry) and\n * tray app (release sha sidecar), plus the \"newer version available\"\n * nudge it feeds. At most one network probe per 24h; `false` disables\n * both the probe and the nudge.\n */\n check?: boolean;\n };\n integrations?: {\n notion?: {\n enabled?: boolean;\n };\n linear?: {\n enabled?: boolean;\n };\n };\n}\n\n/**\n * Required-everywhere variant returned as the merged effective config. Each\n * leaf is filled from BUILT_IN_DEFAULTS when no layer set it.\n *\n * `box.hostSnapshot` and `portless.enabled` are intentionally\n * `boolean | undefined` (unprompted): the default is \"ask the user\", expressed\n * as undefined.\n */\nexport interface EffectiveConfig {\n box: {\n provider: ProviderKind;\n hostSnapshot: boolean | undefined;\n defaultCheckpoint: string;\n defaultCheckpointDocker: string;\n defaultCheckpointDaytona: string;\n defaultCheckpointHetzner: string;\n defaultCheckpointVercel: string;\n defaultCheckpointE2b: string;\n defaultCheckpointDigitalocean: string;\n size: string;\n sizeDocker: string;\n sizeDaytona: string;\n sizeHetzner: string;\n sizeVercel: string;\n sizeE2b: string;\n sizeDigitalocean: string;\n withPlaywright: boolean;\n claudeInstall: ClaudeInstallMethod;\n withEnv: boolean;\n resyncOnStart: boolean;\n vnc: boolean;\n autoApproveHostActions: boolean;\n autoApproveSafeHostActions: boolean;\n isolateClaudeConfig: boolean;\n isolateCodexConfig: boolean;\n isolateOpencodeConfig: boolean;\n image: string;\n imageDocker: string;\n imageDaytona: string;\n imageHetzner: string;\n imageVercel: string;\n imageE2b: string;\n imageDigitalocean: string;\n imageRegistry: string;\n dockerCacheShared: boolean;\n memory: number;\n cpus: number;\n pidsLimit: number;\n disk: string;\n bundleDepth: number | undefined;\n hetznerLocation: string;\n digitaloceanRegion: string;\n vercelTimeoutMs: number;\n vercelNetworkPolicy: string;\n e2bTimeoutMs: number;\n cpMaxBytes: number;\n credentialSync: boolean;\n inbound: string;\n };\n checkpoint: {\n maxLayers: number;\n };\n claude: {\n sessionName: string;\n dangerouslySkipPermissions: boolean;\n };\n codex: {\n sessionName: string;\n dangerouslySkipPermissions: boolean;\n };\n opencode: {\n sessionName: string;\n };\n attach: {\n openIn: AttachOpenIn;\n cmuxStatus: boolean;\n herdrStatus: boolean;\n };\n code: {\n ide: IdeFlavor;\n wait: boolean;\n timeoutMs: number;\n autoTerminals: boolean;\n };\n shell: {\n user: string;\n login: boolean;\n tmux: boolean;\n };\n ssh: {\n autoConfig: boolean;\n };\n engine: {\n kind: EngineKind;\n };\n browser: {\n default: BrowserKind;\n };\n relay: {\n port: number;\n controlPlaneUrl: string | undefined;\n };\n git: {\n pushMode: GitPushMode;\n };\n vnc: {\n containerPort: number;\n };\n portless: {\n enabled: boolean | undefined;\n stateDir: string;\n };\n autopause: {\n enabled: boolean;\n maxRunningBoxes: number;\n idleMinutes: number;\n };\n queue: {\n enabled: boolean;\n maxConcurrent: number;\n maxWorking: number;\n idleGraceSeconds: number;\n openIn: QueueOpenIn;\n };\n cloud: {\n useCurrentBranch: boolean;\n };\n maintenance: {\n pruneProjectConfigs: boolean;\n pruneProjectConfigsEvery: number;\n };\n update: {\n check: boolean;\n };\n integrations: {\n notion: {\n enabled: boolean;\n };\n linear: {\n enabled: boolean;\n };\n };\n}\n\nexport type ConfigSource = 'cli' | 'workspace' | 'project' | 'global' | 'default';\n\nexport interface ConfigLayer {\n source: ConfigSource;\n /** File path the layer was loaded from. Absent for `cli` and `default`. */\n path?: string;\n values: Partial<UserConfig>;\n}\n\nexport interface LoadedConfig {\n effective: EffectiveConfig;\n layers: {\n cli: { values: Partial<UserConfig> };\n workspace: { path: string | null; values: Partial<UserConfig> };\n project: { path: string; values: Partial<UserConfig> };\n global: { path: string; values: Partial<UserConfig> };\n defaults: EffectiveConfig;\n };\n /** Per-leaf source map: 'box.hostSnapshot' -> 'workspace'. Powers `config get --all`. */\n sources: Record<string, ConfigSource>;\n /** Resolved project root used for the project layer (cwd if no agentbox.yaml found). */\n projectRoot: string;\n projectHash: string;\n /** True if we walked up to an agentbox.yaml; false if we fell back to cwd. */\n hasAgentboxYaml: boolean;\n}\n\nexport const BUILT_IN_DEFAULTS: EffectiveConfig = {\n box: {\n provider: 'docker',\n hostSnapshot: undefined,\n defaultCheckpoint: '',\n defaultCheckpointDocker: '',\n defaultCheckpointDaytona: '',\n defaultCheckpointHetzner: '',\n defaultCheckpointVercel: '',\n defaultCheckpointE2b: '',\n defaultCheckpointDigitalocean: '',\n size: '',\n sizeDocker: '',\n sizeDaytona: '',\n sizeHetzner: '',\n sizeVercel: '',\n sizeE2b: '',\n sizeDigitalocean: '',\n withPlaywright: false,\n claudeInstall: 'native',\n withEnv: false,\n resyncOnStart: true,\n vnc: true,\n autoApproveHostActions: false,\n autoApproveSafeHostActions: true,\n isolateClaudeConfig: false,\n isolateCodexConfig: false,\n isolateOpencodeConfig: false,\n image: 'agentbox/box:dev',\n imageDocker: '',\n imageDaytona: '',\n imageHetzner: '',\n imageVercel: '',\n imageE2b: '',\n imageDigitalocean: '',\n // Mirrors BOX_IMAGE_REGISTRY in @agentbox/sandbox-docker. Empty disables the\n // registry pull (always build the docker base image locally).\n imageRegistry: 'ghcr.io/madarco/agentbox/box',\n dockerCacheShared: false,\n memory: 0,\n cpus: 0,\n pidsLimit: 0,\n disk: '',\n bundleDepth: undefined,\n hetznerLocation: 'nbg1',\n digitaloceanRegion: 'nyc3',\n vercelTimeoutMs: 2_700_000,\n vercelNetworkPolicy: '',\n e2bTimeoutMs: 2_700_000,\n cpMaxBytes: 100 * 1024 * 1024,\n credentialSync: true,\n inbound: 'locked',\n },\n checkpoint: {\n maxLayers: 3,\n },\n claude: {\n sessionName: 'claude',\n dangerouslySkipPermissions: true,\n },\n codex: {\n sessionName: 'codex',\n dangerouslySkipPermissions: true,\n },\n opencode: {\n sessionName: 'opencode',\n },\n attach: {\n openIn: 'split',\n cmuxStatus: true,\n herdrStatus: true,\n },\n code: {\n ide: 'auto',\n wait: true,\n timeoutMs: 120_000,\n autoTerminals: true,\n },\n shell: {\n user: 'vscode',\n login: true,\n tmux: true,\n },\n ssh: {\n autoConfig: true,\n },\n engine: {\n kind: 'auto',\n },\n browser: {\n default: 'agent-browser',\n },\n relay: {\n port: 8787,\n controlPlaneUrl: undefined,\n },\n git: {\n pushMode: 'auto',\n },\n vnc: {\n containerPort: 6080,\n },\n portless: {\n enabled: undefined,\n stateDir: '',\n },\n autopause: {\n enabled: true,\n maxRunningBoxes: 5,\n idleMinutes: 5,\n },\n queue: {\n enabled: true,\n maxConcurrent: 5,\n maxWorking: 0,\n idleGraceSeconds: 15,\n openIn: 'none',\n },\n cloud: {\n useCurrentBranch: false,\n },\n maintenance: {\n pruneProjectConfigs: true,\n pruneProjectConfigsEvery: 50,\n },\n update: {\n check: true,\n },\n integrations: {\n notion: { enabled: false },\n linear: { enabled: false },\n },\n};\n\nexport type KeyType = 'bool' | 'string' | 'int' | 'enum';\n\nexport interface KeyDescriptor {\n /** Dot-path, e.g. \"box.snapshot\". */\n key: string;\n type: KeyType;\n enumValues?: readonly string[];\n description: string;\n /** True for keys most users shouldn't touch (image, ports). Hidden from `list` by default. */\n advanced?: boolean;\n}\n\n/** Join blurbs into \"a, b, c, or d\" for the enum description. */\nfunction joinOr(items: readonly string[]): string {\n if (items.length <= 1) return items.join('');\n return `${items.slice(0, -1).join(', ')}, or ${items[items.length - 1]}`;\n}\n\n/**\n * Per-provider config-key descriptors generated from the `PROVIDERS` table so a\n * new provider gets its `box.defaultCheckpoint<P>` / `box.size<P>` /\n * `box.image<P>` entries automatically. The `size`/`image` descriptions come\n * from the table (they carry provider-specific detail); the checkpoint one is\n * uniform.\n */\nfunction perProviderCheckpointKeys(): KeyDescriptor[] {\n return PROVIDERS.map((p) => ({\n key: perProviderConfigKey('defaultCheckpoint', p.name),\n type: 'string',\n description: `Per-provider override of \\`box.defaultCheckpoint\\` for ${p.name}. Wins over the global when set; set via \\`agentbox checkpoint set-default --provider ${p.name}\\`.`,\n advanced: true,\n }));\n}\nfunction perProviderSizeKeys(): KeyDescriptor[] {\n return PROVIDERS.map((p) => ({\n key: perProviderConfigKey('size', p.name),\n type: 'string',\n description: p.sizeDesc,\n advanced: true,\n }));\n}\nfunction perProviderImageKeys(): KeyDescriptor[] {\n return PROVIDERS.map((p) => ({\n key: perProviderConfigKey('image', p.name),\n type: 'string',\n description: p.imageDesc,\n advanced: true,\n }));\n}\n\n/**\n * Single source of truth for which keys are addressable from the CLI. The\n * parser, `set`/`unset`, and `list` all walk this. Adding a key here is the\n * one place a new field has to be registered (plus the type interface above\n * and the JSON schema). Per-provider `box.{image,size,defaultCheckpoint}<P>`\n * keys are generated from the `PROVIDERS` table (see `providers.ts`).\n */\nexport const KEY_REGISTRY: readonly KeyDescriptor[] = [\n {\n key: 'box.provider',\n type: 'enum',\n enumValues: PROVIDER_NAMES,\n description: `Sandbox backend new boxes are created on: ${joinOr(PROVIDERS.map((p) => p.blurb))}.`,\n },\n {\n key: 'box.hostSnapshot',\n type: 'bool',\n description:\n 'Use a frozen APFS clone of the host workspace as the overlay lower (default: prompt). Was box.snapshot.',\n },\n {\n key: 'box.defaultCheckpoint',\n type: 'string',\n description:\n 'Checkpoint ref new boxes in this project start from when --snapshot is not given (set via `agentbox checkpoint set-default`). Used as fallback when no per-provider override is set.',\n },\n ...perProviderCheckpointKeys(),\n {\n key: 'box.size',\n type: 'string',\n description:\n 'Default VM size for cloud providers. Provider-interpreted: hetzner = server type (e.g. `cx33`); daytona = `cpu-memory-disk` GB (e.g. `4-8-20`); vercel = vCPU count (1, 2, 4, 8); e2b = `cpu-memory` GB (e.g. `4-8`). Used as fallback when no per-provider override is set. Docker ignores it.',\n },\n ...perProviderSizeKeys(),\n {\n key: 'checkpoint.maxLayers',\n type: 'int',\n description:\n 'Max stacked checkpoint layers before a new checkpoint is materialized merged (flattened) instead of layered.',\n advanced: true,\n },\n {\n key: 'box.withPlaywright',\n type: 'bool',\n description: 'Install @playwright/cli@latest in the box at create time.',\n },\n {\n key: 'box.claudeInstall',\n type: 'enum',\n enumValues: ['native', 'npm'] as const,\n description:\n \"How `agentbox prepare` installs Claude Code into the base image/snapshot: `native` (Anthropic's installer, the default) or `npm` (@anthropic-ai/claude-code). A fallback for cloud egress IPs the native installer's CDN 403s. Bake-time only — change it, then re-run `agentbox prepare --provider <name>`.\",\n },\n {\n key: 'box.withEnv',\n type: 'bool',\n description:\n 'Copy host env/config files (.env*, secrets.toml, agentbox.yaml, ...) into /workspace at box create time (gitignore-bypassing).',\n },\n {\n key: 'box.resyncOnStart',\n type: 'bool',\n description:\n \"Merge the host's current branch into the box and overlay the host's uncommitted/untracked changes when starting an agent session (keeps the box's version on conflict and warns the agent).\",\n },\n {\n key: 'box.vnc',\n type: 'bool',\n description: 'Run the per-box Xvnc + noVNC stack.',\n },\n {\n key: 'box.autoApproveHostActions',\n type: 'bool',\n description:\n 'Auto-approve host-action confirmations (git push, cp host<->box, gh PR writes, checkpoint) for this box without an interactive prompt. Off by default; intended for unattended orchestration of trusted boxes. Each auto-approval is recorded as a relay event (visible in `agentbox agent` / the dashboard).',\n },\n {\n key: 'box.autoApproveSafeHostActions',\n type: 'bool',\n description:\n 'Auto-approve the SAFE subset of host actions without a prompt: opening a PR, PR/review comments, re-running CI, pushing to the box\\'s scratch or host-sanctioned branch, checkpoints, integration writes, and file copy/download that stays inside the box project folder (non-secret). Uncontained or secret file transfers, non-sanctioned-branch pushes, and PR merge/checkout still prompt. On by default; set false to prompt for every host action (the pre-relax behavior). Superseded by box.autoApproveHostActions, which approves everything. Each auto-approval is recorded as a relay event.',\n },\n {\n key: 'box.isolateClaudeConfig',\n type: 'bool',\n description: 'Use a per-box ~/.claude volume instead of the shared one.',\n },\n {\n key: 'box.isolateCodexConfig',\n type: 'bool',\n description: 'Use a per-box ~/.codex volume instead of the shared one.',\n },\n {\n key: 'box.isolateOpencodeConfig',\n type: 'bool',\n description: 'Use a per-box OpenCode config/data volume instead of the shared one.',\n },\n {\n key: 'box.image',\n type: 'string',\n description: 'Generic box image ref (fallback). Used as fallback when no per-provider override is set; the default `agentbox/box:dev` is treated as a sentinel by cloud backends (boot from their prepared base snapshot instead).',\n advanced: true,\n },\n ...perProviderImageKeys(),\n {\n key: 'box.imageRegistry',\n type: 'string',\n description:\n 'Registry repo to pull the prebuilt docker base image from before building locally. Empty = always build. Docker only (advanced).',\n advanced: true,\n },\n {\n key: 'box.dockerCacheShared',\n type: 'bool',\n description:\n \"Share the in-box docker image cache across boxes via the 'agentbox-docker-cache' volume (preserved on destroy/prune; only one box can run at a time when set).\",\n },\n {\n key: 'box.memory',\n type: 'int',\n description:\n 'Hard memory ceiling in MiB for new boxes (0 = unlimited). Use --memory on create/claude for byte/k/m/g strings.',\n },\n {\n key: 'box.cpus',\n type: 'int',\n description:\n 'CPU count cap for new boxes (0 = unlimited). Whole cores via config; use --cpus for fractional (e.g. 1.5).',\n },\n {\n key: 'box.pidsLimit',\n type: 'int',\n description: 'Max process count (PIDs cgroup) for new boxes (0 = unlimited).',\n },\n {\n key: 'box.disk',\n type: 'string',\n description:\n \"Best-effort writable-layer size for new boxes, e.g. '10G'. No-op on overlay2 / the macOS engines.\",\n advanced: true,\n },\n {\n key: 'box.bundleDepth',\n type: 'int',\n description:\n 'Cap git bundle history shipped to cloud sandboxes (daytona, hetzner). 0 = full history. Unset = adaptive default (last 200 commits; re-bundle at 100 if the bundle exceeds 20 MB). Ignored for docker (which bind-mounts .git/).',\n },\n {\n key: 'box.hetznerLocation',\n type: 'string',\n description:\n 'Hetzner datacenter location new --provider hetzner boxes are created in (e.g. `nbg1`, `fsn1`, `hel1`, `ash`). Default `nbg1`. Overridable per-create with `--location`. Hetzner-only; ignored by other providers.',\n },\n {\n key: 'box.digitaloceanRegion',\n type: 'string',\n description:\n 'DigitalOcean region new --provider digitalocean boxes are created in (e.g. `nyc3`, `nyc1`, `sfo3`, `ams3`, `fra1`). Default `nyc3`. Overridable per-create with `--location`. DigitalOcean-only; ignored by other providers.',\n },\n {\n key: 'box.vercelTimeoutMs',\n type: 'int',\n description:\n 'Max session length (ms) for new --provider vercel boxes before the VM auto-snapshots; persistent mode auto-resumes on the next call. Default 2700000 (45 min, the Hobby ceiling). Vercel-only.',\n },\n {\n key: 'box.e2bTimeoutMs',\n type: 'int',\n description:\n 'Session timeout (ms) a new --provider e2b box is created with, before E2B auto-pauses it on inactivity. The host keepalive loop pushes this forward while the agent is working. Default 2700000 (45 min); the Hobby tier caps total session at ~1 h regardless. E2B-only.',\n },\n {\n key: 'box.cpMaxBytes',\n type: 'int',\n description:\n 'Max bytes a single host→box copy may transfer after excludes, shared by `agentbox cp` (blocked with a size breakdown unless --yes) and each `carry:` entry (rejected at resolve time). Default 104857600 (100 MiB).',\n advanced: true,\n },\n {\n key: 'box.credentialSync',\n type: 'bool',\n description:\n 'Automatically sync refreshed agent credentials (claude/codex/opencode) from boxes to the host backup and out to all other running boxes. Claude OAuth refresh rotates the refresh token, so without this every other copy 401s after any box refreshes. Default true; --no-credential-sync at create disables the in-box watcher for that box.',\n },\n {\n key: 'box.inbound',\n type: 'string',\n description:\n \"Inbound-access policy for VPS boxes (hetzner, digitalocean per-box firewall). `locked` (default) = SSH reachable only from your host's egress IP; `open` = SSH reachable from anywhere (0.0.0.0/0, key-only — to drive a box from a phone with the laptop off); a CIDR list (e.g. `203.0.113.5/32`) = host egress plus those. Override per box with `--inbound` or after create with `agentbox inbound <box>`. Ignored by non-VPS providers.\",\n },\n {\n key: 'box.vercelNetworkPolicy',\n type: 'string',\n description:\n \"Egress lock for new --provider vercel boxes: 'allow-all' (default, unset), 'deny-all', or a comma-separated domain allowlist (e.g. 'github.com,*.npmjs.org') that denies everything else. Vercel-only; ignored by other providers.\",\n },\n {\n key: 'claude.sessionName',\n type: 'string',\n description: 'tmux session name for `agentbox claude`.',\n },\n {\n key: 'claude.dangerouslySkipPermissions',\n type: 'bool',\n description:\n 'Launch claude in new boxes with --dangerously-skip-permissions (auto-accept tool use). Safe because boxes are isolated; on by default. Override per-box with --no-dangerously-skip-permissions.',\n },\n {\n key: 'codex.sessionName',\n type: 'string',\n description: 'tmux session name for `agentbox codex`.',\n },\n {\n key: 'codex.dangerouslySkipPermissions',\n type: 'bool',\n description:\n 'Launch codex in new boxes with --dangerously-bypass-approvals-and-sandbox (never prompt for approval). Safe because boxes are isolated; on by default. Override per-box with --no-dangerously-skip-permissions.',\n },\n {\n key: 'opencode.sessionName',\n type: 'string',\n description: 'tmux session name for `agentbox opencode`.',\n },\n {\n key: 'attach.openIn',\n type: 'enum',\n enumValues: ['split', 'window', 'tab', 'same'] as const,\n description:\n 'Where `agentbox claude|codex|opencode` opens the attached session when run from tmux, cmux, Herdr, or iTerm2: `split` (tmux split-window / cmux new-split / Herdr pane.split / iTerm2 vertical split, default — same workspace), `window` (tmux new-window / cmux new-workspace / Herdr workspace.create / new iTerm2 window), `tab` (tmux new-window / cmux new-surface / Herdr tab.create in the current workspace / new iTerm2 tab), or `same` (attach inline in the current terminal). Outside tmux/cmux/Herdr/iTerm2 every value behaves like `same`.',\n },\n {\n key: 'attach.cmuxStatus',\n type: 'bool',\n description:\n \"When attached inside cmux, reflect the box agent's live activity on its cmux workspace (colour + description: blue=working, amber=needs input, idle clears; restored on detach) and, when the agent needs input, flag the box's own tab via a cmux notification (tab badge + reorder + desktop notification) so it stands out among sibling tabs. cmux only; no-op in other terminals.\",\n },\n {\n key: 'attach.herdrStatus',\n type: 'bool',\n description:\n \"When attached inside Herdr, report the box agent's live activity to its Herdr pane (pane.report_agent: working / blocked / idle) so it looks like a normal agent pane and Herdr handles needs-input natively, and fire a Herdr notification for AgentBox's own host-relay approval prompts (git push / PR / checkpoint …) which Herdr can't otherwise see. Herdr only; no-op in other terminals.\",\n },\n {\n key: 'code.ide',\n type: 'enum',\n enumValues: ['vscode', 'cursor', 'auto'] as const,\n description: 'Which IDE `agentbox code` launches; \"auto\" prefers code, falls back to cursor.',\n },\n {\n key: 'code.wait',\n type: 'bool',\n description: 'Block on agentbox-ctl wait-ready before opening the IDE.',\n },\n {\n key: 'code.timeoutMs',\n type: 'int',\n description: 'wait-ready timeout in milliseconds.',\n },\n {\n key: 'code.autoTerminals',\n type: 'bool',\n description: 'Generate /workspace/.vscode/tasks.json so the IDE auto-opens log panels.',\n },\n {\n key: 'shell.user',\n type: 'string',\n description: 'Default in-container user for `agentbox shell`.',\n },\n {\n key: 'shell.login',\n type: 'bool',\n description: 'Pass `-l` to bash so the login profile loads.',\n },\n {\n key: 'shell.tmux',\n type: 'bool',\n description: 'Run `agentbox shell` inside a detachable tmux session (Ctrl+a d to detach).',\n },\n {\n key: 'ssh.autoConfig',\n type: 'bool',\n description:\n 'Automatically write a `~/.agentbox/ssh/config` entry (Include\\'d from `~/.ssh/config`) for SSH-capable cloud boxes on create and start/resume, so `ssh <box>` just works. On by default; set false if you manage `~/.ssh/config` yourself. Explicit `agentbox shell --ssh-config`/`code`/`open` still write on demand regardless.',\n },\n {\n key: 'engine.kind',\n type: 'enum',\n enumValues: ['orbstack', 'docker-desktop', 'other', 'auto'] as const,\n description: 'Override the docker-engine auto-detection (used for OrbStack-only optimisations).',\n },\n {\n key: 'browser.default',\n type: 'enum',\n enumValues: ['agent-browser', 'playwright', 'both'] as const,\n description: 'Default browser stack inside the box. \"playwright\" or \"both\" implies box.withPlaywright.',\n },\n {\n key: 'relay.port',\n type: 'int',\n description: 'Host relay TCP port (advanced).',\n advanced: true,\n },\n {\n key: 'relay.controlPlaneUrl',\n type: 'string',\n description:\n 'Public HTTPS URL of a deployed control plane (hosted Next.js + Postgres app). When set, new cloud boxes point at it for git-token leasing, permission state, and the box registry/events, and push to GitHub directly with a leased token so they keep working with the laptop off. Set via `agentbox control-plane set-url`.',\n },\n {\n key: 'git.pushMode',\n type: 'enum',\n enumValues: ['auto', 'relay', 'lease', 'direct'] as const,\n description:\n \"How a box's `git push` reaches GitHub: `relay` (the host relay pushes with your host credentials — they never enter the box), `lease` (the relay/plane leases a short-lived GitHub-App token and the box pushes directly, so it works with the laptop off), `direct` (the box holds a COPY of your git credentials and pushes/pulls/signs entirely on its own — needs no host or hub, but the credentials live inside the box and its snapshots; set via `--with-credentials`, which copies them in behind a confirmation), or `auto` (default — lease when `relay.controlPlaneUrl` is set for the box, else relay). Only affects cloud boxes; docker boxes always use `relay`. Forcing `relay` needs a reachable host relay for the box; forcing `lease` needs a reachable relay/plane with a GitHub App; `direct` needs credentials to have been copied into the box at create time.\",\n },\n {\n key: 'vnc.containerPort',\n type: 'int',\n description: 'Container-side noVNC port (advanced).',\n advanced: true,\n },\n {\n key: 'portless.enabled',\n type: 'bool',\n description:\n 'Map each box web app to a https://<box-name>.localhost URL via the Portless proxy (Docker Desktop only; OrbStack already has .orb.local). Default: prompt.',\n },\n {\n key: 'portless.stateDir',\n type: 'string',\n description:\n 'Host Portless state directory to share into boxes (advanced; default: Portless’s own location).',\n advanced: true,\n },\n {\n key: 'autopause.enabled',\n type: 'bool',\n description:\n 'Let the host relay periodically pause idle boxes when more than autopause.maxRunningBoxes are running.',\n },\n {\n key: 'autopause.maxRunningBoxes',\n type: 'int',\n description:\n 'Target maximum number of simultaneously-running boxes before idle ones get auto-paused.',\n },\n {\n key: 'autopause.idleMinutes',\n type: 'int',\n description:\n 'Minutes a box must be continuously idle (claude state) before it is eligible for auto-pause.',\n },\n {\n key: 'queue.enabled',\n type: 'bool',\n description:\n 'Run `agentbox claude|codex|opencode -i <prompt>` jobs through the host-wide background queue (FIFO, capped by queue.maxConcurrent).',\n },\n {\n key: 'queue.maxConcurrent',\n type: 'int',\n description:\n 'Max number of simultaneously-running boxes (across providers) before background `-i` jobs queue up instead of starting immediately. Per-invocation override: `--max-running <n>`.',\n },\n {\n key: 'queue.maxWorking',\n type: 'int',\n description:\n 'Max agents actively working/thinking (quota-consuming) at once before background `-i` jobs queue. 0 = disabled (use the queue.maxConcurrent running-box gate). Counts all boxes, foreground + queued. Per-invocation override: `--max-working <n>`.',\n },\n {\n key: 'queue.idleGraceSeconds',\n type: 'int',\n description:\n 'Seconds an agent must stay non-working before it frees its working slot (debounce against brief idle flaps between turns). Only used when queue.maxWorking > 0.',\n },\n {\n key: 'queue.openIn',\n type: 'enum',\n enumValues: ['none', 'split', 'window', 'tab'] as const,\n description:\n 'When a background `-i` job finishes creating its box, where the host relay opens an attached terminal onto it: `none` (default — open nothing, just queue), `split`, `window`, or `tab`. Honored only when the submitting shell runs inside tmux, cmux, Herdr, or iTerm2 (the targeting is captured at submit time). Under cmux, `split` splits the pane you submitted from (falling back to the parent workspace, then a new workspace), `tab` adds a tab in the parent workspace, and `window` opens a separate workspace; under Herdr, `split` splits the pane you submitted from, `tab` adds a tab in the parent workspace, and `window` opens a separate workspace; iTerm2 opens relative to the frontmost window. Unlike `attach.openIn` there is no `same` mode — the box is created asynchronously, so it is always a fresh terminal.',\n },\n {\n key: 'cloud.useCurrentBranch',\n type: 'bool',\n description:\n \"On cloud providers (daytona/hetzner), start new boxes on the host's current branch instead of forking a new agentbox/<box-name> branch. Overridden by an explicit --use-branch / --from-branch.\",\n },\n {\n key: 'maintenance.pruneProjectConfigs',\n type: 'bool',\n description:\n 'Periodically delete ~/.agentbox/projects/<hash>/ dirs whose source workspace folder no longer exists.',\n },\n {\n key: 'maintenance.pruneProjectConfigsEvery',\n type: 'int',\n description: 'Run the orphan project-config sweep every N successful `agentbox create`.',\n },\n {\n key: 'update.check',\n type: 'bool',\n description:\n 'Daily background check for a newer published agentbox (npm registry) and menu-bar app (release sha sidecar), plus the \"newer version available\" nudge. At most one network probe per 24h; false disables both.',\n },\n {\n key: 'integrations.notion.enabled',\n type: 'bool',\n description:\n 'Enable the in-box Notion integration shim (`ntn`/`notion` commands routed via the host relay). When false (default), the relay refuses dispatch with a clear \"disabled\" error and no host process is touched.',\n },\n {\n key: 'integrations.linear.enabled',\n type: 'bool',\n description:\n 'Enable the in-box Linear integration shim (`linear` commands routed via the host relay; backed by `@schpet/linear-cli`). When false (default), the relay refuses dispatch with a clear \"disabled\" error and no host process is touched.',\n },\n];\n\nconst REGISTRY_BY_KEY = new Map<string, KeyDescriptor>(KEY_REGISTRY.map((d) => [d.key, d]));\n\nexport function lookupKey(key: string): KeyDescriptor | undefined {\n return REGISTRY_BY_KEY.get(key);\n}\n\nexport class UserConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'UserConfigError';\n }\n}\n\nexport type ConfigScope = 'global' | 'project';\n","import { parse as parseYaml } from 'yaml';\nimport {\n KEY_REGISTRY,\n type KeyDescriptor,\n type UserConfig,\n UserConfigError,\n} from './types.js';\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** Keys removed in a rename. Surfaced with a migration hint instead of a bare \"unknown key\". */\nconst RENAMED_KEYS: ReadonlyMap<string, string> = new Map([['box.snapshot', 'box.hostSnapshot']]);\n\ninterface BranchSpec {\n name: string;\n /** Map of leaf-key (dot-suffix) → descriptor whose `key` starts with this branch. */\n leaves: Map<string, KeyDescriptor>;\n}\n\nconst BRANCHES: Map<string, BranchSpec> = (() => {\n const out = new Map<string, BranchSpec>();\n for (const desc of KEY_REGISTRY) {\n const idx = desc.key.indexOf('.');\n if (idx < 0) {\n throw new Error(`KEY_REGISTRY entry ${desc.key} must use dot-path form (branch.leaf)`);\n }\n const branch = desc.key.slice(0, idx);\n const leaf = desc.key.slice(idx + 1);\n let entry = out.get(branch);\n if (!entry) {\n entry = { name: branch, leaves: new Map() };\n out.set(branch, entry);\n }\n entry.leaves.set(leaf, desc);\n }\n return out;\n})();\n\n/**\n * Coerce a typed YAML scalar (already typed by the YAML parser) into the\n * descriptor's expected type. Strings from the CLI go through `coerceFromString`\n * instead — that path accepts e.g. \"true\" or \"120000\".\n */\nfunction coerceTypedValue(raw: unknown, desc: KeyDescriptor, where: string): unknown {\n if (raw === null) {\n throw new UserConfigError(`${where} must not be null (use \\`agentbox config unset\\` to clear)`);\n }\n switch (desc.type) {\n case 'bool':\n if (typeof raw !== 'boolean') {\n throw new UserConfigError(`${where} must be a boolean (got ${typeof raw})`);\n }\n return raw;\n case 'string':\n if (typeof raw !== 'string') {\n throw new UserConfigError(`${where} must be a string (got ${typeof raw})`);\n }\n if (raw.length === 0) {\n throw new UserConfigError(`${where} must not be empty`);\n }\n return raw;\n case 'int':\n if (typeof raw !== 'number' || !Number.isInteger(raw)) {\n throw new UserConfigError(`${where} must be an integer (got ${String(raw)})`);\n }\n return raw;\n case 'enum':\n if (typeof raw !== 'string' || !desc.enumValues!.includes(raw)) {\n throw new UserConfigError(\n `${where} must be one of: ${desc.enumValues!.join(', ')} (got ${String(raw)})`,\n );\n }\n return raw;\n }\n}\n\n/**\n * Parse a UserConfig document text (YAML). Strict: unknown branches and\n * unknown leaves throw UserConfigError so typos surface early.\n *\n * `where` is the human-readable origin for error messages, e.g. the file path.\n * Empty / whitespace-only input parses to `{}`.\n */\nexport function parseUserConfig(text: string, where: string): Partial<UserConfig> {\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch (err) {\n throw new UserConfigError(\n `${where}: yaml parse error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (doc === null || doc === undefined) return {};\n if (!isPlainObject(doc)) {\n throw new UserConfigError(`${where}: top-level must be a mapping`);\n }\n return parseUserConfigObject(doc, where);\n}\n\n/**\n * Same validation as `parseUserConfig` but starting from an already-decoded\n * object. Used when the caller has the YAML parsed (e.g. agentbox.yaml's\n * `defaults:` block).\n */\nexport function parseUserConfigObject(doc: unknown, where: string): Partial<UserConfig> {\n if (doc === null || doc === undefined) return {};\n if (!isPlainObject(doc)) {\n throw new UserConfigError(`${where}: must be a mapping`);\n }\n\n const out: Partial<UserConfig> = {};\n for (const [branchName, branchRaw] of Object.entries(doc)) {\n // Top-level `schema` is a metadata stamp written by the loader on first\n // save (future-proofs migrations). It's not a config section and never\n // appears in `EffectiveConfig`; carry it through so writers preserve it\n // round-trip, but skip the \"must be a mapping\" / leaf checks below.\n if (branchName === 'schema') {\n if (branchRaw !== undefined && branchRaw !== null) {\n if (typeof branchRaw !== 'number' || !Number.isInteger(branchRaw)) {\n throw new UserConfigError(`${where}.schema: must be an integer (got ${String(branchRaw)})`);\n }\n out.schema = branchRaw;\n }\n continue;\n }\n const branchSpec = BRANCHES.get(branchName);\n if (!branchSpec) {\n throw new UserConfigError(\n `${where}: unknown config section \"${branchName}\" (known: ${[...BRANCHES.keys()].join(', ')})`,\n );\n }\n if (branchRaw === null || branchRaw === undefined) continue;\n if (!isPlainObject(branchRaw)) {\n throw new UserConfigError(`${where}.${branchName}: must be a mapping`);\n }\n const branchOut = parseBranchObject(branchSpec, branchName, branchRaw, '', where);\n if (Object.keys(branchOut).length > 0) {\n // We've validated that each branch matches one of UserConfig's known\n // sub-objects; the indexed write keeps the union type happy.\n (out as Record<string, unknown>)[branchName] = branchOut;\n }\n }\n return out;\n}\n\n/**\n * Validate a YAML branch sub-tree against `branchSpec`'s registered leaf paths.\n * Handles nested keys like `integrations.notion.enabled` — the branch is\n * `integrations`, the leaf path is `notion.enabled`, so the YAML can be\n * written as a nested mapping. `qualifiedPrefix` is the dotted path walked so\n * far within the branch (empty at top level).\n */\nfunction parseBranchObject(\n branchSpec: BranchSpec,\n branchName: string,\n raw: Record<string, unknown>,\n qualifiedPrefix: string,\n where: string,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(raw)) {\n if (value === undefined) continue;\n const qualified = qualifiedPrefix ? `${qualifiedPrefix}.${name}` : name;\n const desc = branchSpec.leaves.get(qualified);\n if (desc) {\n out[name] = coerceTypedValue(value, desc, `${where}.${desc.key}`);\n continue;\n }\n // Not a leaf — descend if it's a mapping AND a deeper leaf is registered\n // beneath this path. Otherwise the key is unknown / not in the registry.\n if (isPlainObject(value) && branchHasLeafBelow(branchSpec, qualified)) {\n const sub = parseBranchObject(branchSpec, branchName, value, qualified, where);\n if (Object.keys(sub).length > 0) out[name] = sub;\n continue;\n }\n const renamedTo = RENAMED_KEYS.get(`${branchName}.${qualified}`);\n if (renamedTo) {\n throw new UserConfigError(\n `${where}.${branchName}.${qualified} was renamed to ${renamedTo} — update your config`,\n );\n }\n throw new UserConfigError(\n `${where}.${branchName}: unknown key \"${qualified}\" (known: ${[...branchSpec.leaves.keys()].join(', ')})`,\n );\n }\n return out;\n}\n\nfunction branchHasLeafBelow(branchSpec: BranchSpec, prefix: string): boolean {\n const needle = `${prefix}.`;\n for (const leaf of branchSpec.leaves.keys()) {\n if (leaf.startsWith(needle)) return true;\n }\n return false;\n}\n\n/**\n * Coerce a string (e.g. typed at the CLI by `agentbox config set`) into the\n * declared type for `key`. Booleans accept true/false/yes/no/1/0 (case\n * insensitive). Returns the typed value or throws UserConfigError.\n */\nexport function coerceFromString(key: string, raw: string): unknown {\n const desc = lookupKeyOrThrow(key);\n switch (desc.type) {\n case 'bool': {\n const v = raw.trim().toLowerCase();\n if (v === 'true' || v === 'yes' || v === '1' || v === 'on') return true;\n if (v === 'false' || v === 'no' || v === '0' || v === 'off') return false;\n throw new UserConfigError(`${key}: expected a boolean (true/false), got \"${raw}\"`);\n }\n case 'string':\n if (raw.length === 0) throw new UserConfigError(`${key}: must not be empty`);\n return raw;\n case 'int': {\n const n = Number(raw);\n if (!Number.isFinite(n) || !Number.isInteger(n)) {\n throw new UserConfigError(`${key}: expected an integer, got \"${raw}\"`);\n }\n return n;\n }\n case 'enum':\n if (!desc.enumValues!.includes(raw)) {\n throw new UserConfigError(\n `${key}: expected one of ${desc.enumValues!.join(', ')}, got \"${raw}\"`,\n );\n }\n return raw;\n }\n}\n\nfunction lookupKeyOrThrow(key: string): KeyDescriptor {\n const renamedTo = RENAMED_KEYS.get(key);\n if (renamedTo) {\n throw new UserConfigError(`${key} was renamed to ${renamedTo} — use ${renamedTo} instead`);\n }\n const idx = key.indexOf('.');\n if (idx < 0) {\n throw new UserConfigError(`unknown key \"${key}\" (must be in branch.leaf form)`);\n }\n const branch = BRANCHES.get(key.slice(0, idx));\n if (!branch) {\n throw new UserConfigError(\n `unknown config section \"${key.slice(0, idx)}\" (known: ${[...BRANCHES.keys()].join(', ')})`,\n );\n }\n const desc = branch.leaves.get(key.slice(idx + 1));\n if (!desc) {\n throw new UserConfigError(\n `unknown key \"${key}\" (known in ${branch.name}: ${[...branch.leaves.keys()].join(', ')})`,\n );\n }\n return desc;\n}\n","import { createHash } from 'node:crypto';\nimport { realpath, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport type { ConfigScope } from './types.js';\n\nexport const STATE_DIR = join(homedir(), '.agentbox');\nexport const GLOBAL_CONFIG_FILE = join(STATE_DIR, 'config.yaml');\nexport const PROJECTS_DIR = join(STATE_DIR, 'projects');\nexport const WORKSPACE_CONFIG_BASENAME = 'agentbox.yaml';\n\nexport interface ProjectRoot {\n /** Absolute path to the resolved project root (host filesystem). */\n root: string;\n hasAgentboxYaml: boolean;\n}\n\n/**\n * Walk up from `cwd` until we find an `agentbox.yaml`. That dir is the\n * \"project\". If no ancestor has one, we fall back to `cwd` (per spec) so\n * `agentbox config` still does something sane in dirs without a workspace\n * file. The returned path is always absolute and **symlink-canonicalised**\n * via `realpath` — without this, macOS's `/tmp` symlink to `/private/tmp`\n * makes `findProjectRoot('/tmp/x')` (at create time, --workspace) and\n * `findProjectRoot(process.cwd())` (at resolve time, the same dir) return\n * different roots, breaking the per-project box index match.\n */\nexport async function findProjectRoot(cwd: string): Promise<ProjectRoot> {\n const start = await canonicalize(cwd);\n let dir = start;\n // Defensive cap on iterations: filesystem roots end with `dirname(x) === x`.\n for (let i = 0; i < 64; i++) {\n if (await fileExists(join(dir, WORKSPACE_CONFIG_BASENAME))) {\n return { root: dir, hasAgentboxYaml: true };\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return { root: start, hasAgentboxYaml: false };\n}\n\nasync function canonicalize(p: string): Promise<string> {\n const abs = resolve(p);\n // realpath only works for paths that exist. cwd and create-time\n // workspaces always do; fall back to the resolved (non-canonicalised)\n // path for anything else (e.g. config get from a deleted dir).\n try {\n return await realpath(abs);\n } catch {\n return abs;\n }\n}\n\nasync function fileExists(p: string): Promise<boolean> {\n try {\n const st = await stat(p);\n return st.isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * SHA-1 (first 16 hex chars) of the *normalised* absolute path. We strip a\n * single trailing slash so `/foo/` and `/foo` hash identically. Case is\n * preserved — macOS APFS is case-preserving and so is the user's intent.\n */\nexport function hashProjectPath(absPath: string): string {\n const normalised = absPath.length > 1 && absPath.endsWith('/')\n ? absPath.slice(0, -1)\n : absPath;\n return createHash('sha1').update(normalised).digest('hex').slice(0, 16);\n}\n\n/**\n * Make `raw` safe to embed as the mnemonic half of an on-disk dir segment or a\n * Docker tag repo. Lowercased so docker tag repos stay valid; `-` collapses to\n * `_` so the single `-` between hash and mnemonic remains the only one (which\n * is what `listProjectsConfigured` parses on). Bounded length, never empty.\n */\nexport function sanitizeMnemonic(raw: string): string {\n return (\n raw\n .toLowerCase()\n .replace(/-/g, '_')\n .replace(/[^a-z0-9_]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_+|_+$/g, '')\n .slice(0, 32) || 'unnamed'\n );\n}\n\n/**\n * On-disk dir segment for a project under `~/.agentbox/projects/` and\n * `~/.agentbox/checkpoints/`: `<hash>-<mnemonic>`. The hash stays the\n * canonical key; the trailing mnemonic is decorative — readers parse the hash\n * as the leading 16 hex chars and ignore the suffix.\n */\nexport function projectDirSegment(absPath: string): string {\n return `${hashProjectPath(absPath)}-${sanitizeMnemonic(basename(absPath))}`;\n}\n\nexport function projectConfigDir(absPath: string): string {\n return join(PROJECTS_DIR, projectDirSegment(absPath));\n}\n\nexport function projectConfigFile(absPath: string): string {\n return join(projectConfigDir(absPath), 'config.yaml');\n}\n\nexport function projectMetaFile(absPath: string): string {\n return join(projectConfigDir(absPath), 'meta.json');\n}\n\nexport function workspaceConfigFile(workspacePath: string): string {\n return join(workspacePath, WORKSPACE_CONFIG_BASENAME);\n}\n\n/**\n * Resolve a file path for a given scope. For `global`, no cwd is needed;\n * for `project`, `cwd` selects which project hash. Workspace path uses the\n * resolved project root (the dir holding `agentbox.yaml`, or cwd as fallback).\n */\nexport async function configPathFor(\n scope: ConfigScope | 'workspace',\n cwd: string,\n): Promise<string> {\n if (scope === 'global') return GLOBAL_CONFIG_FILE;\n const root = await findProjectRoot(cwd);\n if (scope === 'project') return projectConfigFile(root.root);\n return workspaceConfigFile(root.root);\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport {\n findProjectRoot,\n GLOBAL_CONFIG_FILE,\n hashProjectPath,\n projectConfigFile,\n workspaceConfigFile,\n} from './paths.js';\nimport { parseUserConfig, parseUserConfigObject } from './parse.js';\nimport {\n BUILT_IN_DEFAULTS,\n type ConfigSource,\n type EffectiveConfig,\n KEY_REGISTRY,\n type LoadedConfig,\n type UserConfig,\n} from './types.js';\n\n/**\n * ENOENT-tolerant read of a UserConfig file. Anything else propagates.\n */\nasync function loadOptionalUserConfig(path: string): Promise<Partial<UserConfig>> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw err;\n }\n return parseUserConfig(text, path);\n}\n\n/**\n * Read the `defaults:` block from `<workspacePath>/agentbox.yaml`. Returns\n * `{}` if the file is missing or has no `defaults:` key. Throws on YAML\n * parse errors or invalid `defaults:` content (so typos surface as soon as\n * the user runs anything in the workspace).\n *\n * The rest of `agentbox.yaml` is owned by `@agentbox/ctl` — we don't validate\n * it here and we don't depend on that package.\n */\nexport async function loadProjectAgentboxDefaults(\n workspacePath: string,\n): Promise<Partial<UserConfig>> {\n const path = workspaceConfigFile(workspacePath);\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw err;\n }\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch {\n // The ctl parser will surface its own error on the next box action; we\n // only throw if defaults: is present and broken (validated below).\n return {};\n }\n if (doc === null || doc === undefined || typeof doc !== 'object' || Array.isArray(doc)) {\n return {};\n }\n const defaults = (doc as Record<string, unknown>)['defaults'];\n if (defaults === undefined || defaults === null) return {};\n return parseUserConfigObject(defaults, `${path} defaults`);\n}\n\nexport interface LoadEffectiveConfigOptions {\n /** Highest-precedence layer; values supplied by command-line flags. */\n cliOverrides?: Partial<UserConfig>;\n}\n\n/**\n * Load and merge all four config sources for the cwd. Per-leaf precedence\n * (highest wins): cli > workspace > project > global > built-in defaults.\n *\n * The returned `sources` map has one entry per leaf in the registry — useful\n * for `agentbox config get --all` to show provenance.\n */\nexport async function loadEffectiveConfig(\n cwd: string,\n opts: LoadEffectiveConfigOptions = {},\n): Promise<LoadedConfig> {\n const projectRoot = await findProjectRoot(cwd);\n const projectPath = projectConfigFile(projectRoot.root);\n const workspacePath = projectRoot.hasAgentboxYaml ? workspaceConfigFile(projectRoot.root) : null;\n\n const [globalValues, projectValues, workspaceValues] = await Promise.all([\n loadOptionalUserConfig(GLOBAL_CONFIG_FILE),\n loadOptionalUserConfig(projectPath),\n workspacePath ? loadProjectAgentboxDefaults(projectRoot.root) : Promise.resolve({}),\n ]);\n\n const cliValues = opts.cliOverrides ?? {};\n\n const { effective, sources } = mergeLayers({\n cli: cliValues,\n workspace: workspaceValues,\n project: projectValues,\n global: globalValues,\n });\n\n return {\n effective,\n layers: {\n cli: { values: cliValues },\n workspace: { path: workspacePath, values: workspaceValues },\n project: { path: projectPath, values: projectValues },\n global: { path: GLOBAL_CONFIG_FILE, values: globalValues },\n defaults: BUILT_IN_DEFAULTS,\n },\n sources,\n projectRoot: projectRoot.root,\n projectHash: hashProjectPath(projectRoot.root),\n hasAgentboxYaml: projectRoot.hasAgentboxYaml,\n };\n}\n\ninterface MergeInput {\n cli: Partial<UserConfig>;\n workspace: Partial<UserConfig>;\n project: Partial<UserConfig>;\n global: Partial<UserConfig>;\n}\n\n/**\n * Walk every key in KEY_REGISTRY, pick the highest-precedence layer that has\n * a leaf value, and record the source. Lower-precedence layers never\n * overwrite a higher-precedence definition; absent leaves don't shadow.\n */\nfunction mergeLayers(input: MergeInput): {\n effective: EffectiveConfig;\n sources: Record<string, ConfigSource>;\n} {\n // Deep-clone the defaults; we'll overwrite leaves in place.\n const effective: EffectiveConfig = JSON.parse(JSON.stringify(BUILT_IN_DEFAULTS)) as EffectiveConfig;\n const sources: Record<string, ConfigSource> = {};\n\n const layerOrder: Array<{ source: ConfigSource; values: Partial<UserConfig> }> = [\n { source: 'cli', values: input.cli },\n { source: 'workspace', values: input.workspace },\n { source: 'project', values: input.project },\n { source: 'global', values: input.global },\n ];\n\n for (const desc of KEY_REGISTRY) {\n const idx = desc.key.indexOf('.');\n const branch = desc.key.slice(0, idx);\n const leaf = desc.key.slice(idx + 1);\n\n let chosen: { source: ConfigSource; value: unknown } | null = null;\n for (const layer of layerOrder) {\n const v = readLeaf(layer.values, branch, leaf);\n if (v !== undefined) {\n chosen = { source: layer.source, value: v };\n break;\n }\n }\n\n if (chosen) {\n writeLeaf(effective, branch, leaf, chosen.value);\n sources[desc.key] = chosen.source;\n } else {\n sources[desc.key] = 'default';\n }\n }\n\n return { effective, sources };\n}\n\nfunction readLeaf(\n obj: Partial<UserConfig>,\n branch: string,\n leaf: string,\n): unknown {\n let cur: unknown = (obj as Record<string, unknown>)[branch];\n for (const seg of leaf.split('.')) {\n if (cur === undefined || cur === null || typeof cur !== 'object') return undefined;\n cur = (cur as Record<string, unknown>)[seg];\n }\n return cur;\n}\n\nfunction writeLeaf(\n obj: EffectiveConfig,\n branch: string,\n leaf: string,\n value: unknown,\n): void {\n let cur: Record<string, unknown> | undefined =\n (obj as unknown as Record<string, Record<string, unknown>>)[branch];\n if (!cur) return; // BUILT_IN_DEFAULTS guarantees the branch exists\n const segs = leaf.split('.');\n for (let i = 0; i < segs.length - 1; i++) {\n const seg = segs[i]!;\n const next = cur[seg];\n if (next === undefined || next === null || typeof next !== 'object') {\n // BUILT_IN_DEFAULTS guarantees nested sub-objects exist for every\n // registered key path, so this is unreachable in practice; defaulting\n // to a fresh sub-object keeps the function total.\n cur[seg] = {};\n }\n cur = cur[seg] as Record<string, unknown>;\n }\n cur[segs[segs.length - 1]!] = value;\n}\n","/**\n * Resolve the effective box image ref for a given provider.\n *\n * Precedence (highest wins):\n * 1. `box.image<Provider>` — per-provider override\n * (`imageDocker` / `imageDaytona` / `imageHetzner` / `imageVercel`).\n * 2. `box.image` — generic fallback (defaults to `agentbox/box:dev`,\n * which cloud backends recognize as a sentinel meaning \"boot from\n * the provider's prepared base snapshot\").\n *\n * Each `agentbox prepare --provider X` writes its result into its own\n * per-provider key, so cross-provider prepares can no longer poison\n * creates on other providers.\n */\nimport type { EffectiveConfig, ProviderKind } from './types.js';\nimport { isProviderKind, perProviderConfigKey } from './providers.js';\n\n/**\n * Read a per-provider `box.<base><P>` string field off the effective config.\n * Only BUILT-IN providers have such a key; any other name — a stray value, or\n * an external plugin provider — returns '' so the caller falls through to the\n * generic `box.<base>`. For a plugin that generic is the image sentinel\n * (`agentbox/box:dev`), which the plugin's own backend maps to its prepared\n * snapshot — so a plugin never accidentally reads docker's per-provider value.\n */\nfunction perProviderValue(\n cfg: EffectiveConfig,\n base: 'image' | 'size' | 'defaultCheckpoint',\n provider: ProviderKind | string,\n): string {\n if (!isProviderKind(provider)) return '';\n const field = perProviderConfigKey(base, provider).slice('box.'.length);\n const val = (cfg.box as Record<string, unknown>)[field];\n return typeof val === 'string' ? val : '';\n}\n\nexport function resolveBoxImage(cfg: EffectiveConfig, provider: ProviderKind | string): string {\n // Unknown provider names fall back to the generic `box.image` — a stray\n // value in argv or config shouldn't crash before the validation layer.\n const perProvider = perProviderValue(cfg, 'image', provider);\n if (perProvider.length > 0) return perProvider;\n return cfg.box.image;\n}\n\nexport { perProviderValue };\n\n/**\n * Flat KEY_REGISTRY key for `agentbox prepare --provider X` to pin the\n * resulting image into the right per-provider slot; mirrors\n * `defaultCheckpointConfigKey`. Unknown provider → generic `box.image`\n * (legacy callers).\n */\nexport function boxImageConfigKey(provider: ProviderKind | string | undefined): string {\n if (provider && isProviderKind(provider)) return perProviderConfigKey('image', provider);\n return 'box.image';\n}\n","/**\n * Resolve the effective default checkpoint ref for a given provider.\n *\n * Precedence (highest wins):\n * 1. `box.defaultCheckpoint<Provider>` — per-provider override\n * (`defaultCheckpointDocker` / `defaultCheckpointDaytona` /\n * `defaultCheckpointHetzner`).\n * 2. `box.defaultCheckpoint` — global fallback (back-compat shape: every\n * pre-cloud config has this; no flag was needed).\n * 3. '' — no default.\n *\n * Returning the empty string (instead of undefined) matches the\n * `EffectiveConfig.box.defaultCheckpoint` shape so call sites that already\n * test `.length > 0` keep working unchanged.\n */\nimport type { EffectiveConfig, ProviderKind } from './types.js';\nimport { isProviderKind, perProviderConfigKey } from './providers.js';\nimport { perProviderValue } from './image.js';\n\nexport function resolveDefaultCheckpoint(\n cfg: EffectiveConfig,\n provider: ProviderKind | string,\n): string {\n // Unknown provider names fall back to the global default — a stray value in\n // config or argv shouldn't crash before the validation layer.\n const perProvider = perProviderValue(cfg, 'defaultCheckpoint', provider);\n if (perProvider.length > 0) return perProvider;\n return cfg.box.defaultCheckpoint;\n}\n\n/**\n * Config key (one of the flat KEY_REGISTRY entries) used by `agentbox\n * checkpoint set-default [--provider X]` to write the right field. Passing\n * an unknown provider falls back to the global key (legacy callers).\n */\nexport function defaultCheckpointConfigKey(provider: ProviderKind | string | undefined): string {\n if (provider && isProviderKind(provider)) {\n return perProviderConfigKey('defaultCheckpoint', provider);\n }\n return 'box.defaultCheckpoint';\n}\n","/**\n * Resolve the effective default VM size for a given cloud provider.\n *\n * Precedence (highest wins):\n * 1. `box.size<Provider>` — per-provider override\n * (`sizeDocker` / `sizeDaytona` / `sizeHetzner` / `sizeVercel`).\n * 2. `box.size` — generic fallback.\n * 3. '' — no preference; backend uses its built-in default.\n *\n * Interpretation is provider-specific:\n * - hetzner: server type string (e.g. `cx33`).\n * - daytona: `cpu-memory-disk` GB spec (e.g. `4-8-20`), baked at prepare time\n * on the snapshot path.\n * - vercel: vCPU count — `1`, `2`, `4` or `8` (RAM is coupled at 2 GB/vCPU).\n * - e2b: `cpu-memory` GB spec (e.g. `4-8`), baked at prepare time.\n * - docker: reserved (docker uses memory/cpus/disk). The key exists for\n * surface uniformity.\n *\n * Returning '' (rather than undefined) mirrors how `resolveDefaultCheckpoint`\n * shapes its result, so call sites can `.length > 0` test uniformly.\n */\nimport type { EffectiveConfig, ProviderKind } from './types.js';\nimport { perProviderValue } from './image.js';\n\nexport function resolveBoxSize(cfg: EffectiveConfig, provider: ProviderKind | string): string {\n // Unknown provider names fall back to the generic `box.size` — a stray value\n // in argv or config shouldn't crash before the validation layer.\n const perProvider = perProviderValue(cfg, 'size', provider);\n if (perProvider.length > 0) return perProvider;\n return cfg.box.size;\n}\n","import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport { stringify as stringifyYaml } from 'yaml';\nimport {\n configPathFor,\n findProjectRoot,\n hashProjectPath,\n PROJECTS_DIR,\n projectConfigFile,\n projectMetaFile,\n} from './paths.js';\nimport { coerceFromString, parseUserConfig } from './parse.js';\nimport { type ConfigScope, lookupKey, type UserConfig, UserConfigError } from './types.js';\nimport { readdir } from 'node:fs/promises';\n\ninterface WriteResult {\n path: string;\n /** The value we coerced and stored, after string→typed conversion. */\n coerced: unknown;\n}\n\ninterface SetOptions {\n /**\n * When true (the CLI `set` path), accept a string and coerce. When false\n * (programmatic), accept any typed value and write it through after a\n * round-trip parse for validation.\n */\n raw?: boolean;\n}\n\n/**\n * Write a single key into the chosen scope's config file. Creates parent\n * dirs and (for project scope) the meta.json sidecar. Atomic via tmp-rename.\n */\nexport async function setConfigValue(\n scope: ConfigScope,\n key: string,\n value: unknown,\n cwd: string,\n opts: SetOptions = {},\n): Promise<WriteResult> {\n if (!lookupKey(key)) {\n throw new UserConfigError(`unknown key \"${key}\"`);\n }\n\n const coerced = opts.raw && typeof value === 'string'\n ? coerceFromString(key, value)\n : value;\n\n const path = await configPathFor(scope, cwd);\n const current = await readExistingDoc(path);\n setLeaf(current, key, coerced);\n stampSchema(current);\n // Re-parse to validate the merged document; any change that produces an\n // invalid file (shouldn't be possible here, but defence-in-depth) throws.\n parseUserConfig(stringifyYaml(current), path);\n await atomicWriteYaml(path, current);\n\n if (scope === 'project') {\n const root = (await findProjectRoot(cwd)).root;\n await touchProjectMeta(root);\n }\n\n return { path, coerced };\n}\n\n/**\n * Remove a key from the chosen scope's config file. Empty parent objects are\n * pruned so the file stays tidy. ENOENT is treated as success.\n */\nexport async function unsetConfigValue(\n scope: ConfigScope,\n key: string,\n cwd: string,\n): Promise<{ path: string; existed: boolean }> {\n if (!lookupKey(key)) {\n throw new UserConfigError(`unknown key \"${key}\"`);\n }\n const path = await configPathFor(scope, cwd);\n const current = await readExistingDoc(path);\n const existed = unsetLeaf(current, key);\n if (!existed) return { path, existed: false };\n stampSchema(current);\n await atomicWriteYaml(path, current);\n if (scope === 'project') {\n const root = (await findProjectRoot(cwd)).root;\n await touchProjectMeta(root);\n }\n return { path, existed: true };\n}\n\nexport interface ProjectEntry {\n /** SHA-1 (first 16 hex chars) of `originalPath` — the canonical key. */\n hash: string;\n /**\n * On-disk dir name under `PROJECTS_DIR`. Equal to the hash for legacy\n * pre-rename dirs; `<hash>-<mnemonic>` for new dirs. Used directly when we\n * need to `rm` the dir so the call works regardless of which shape happens\n * to be on disk.\n */\n dirName: string;\n originalPath: string;\n createdAt: string | null;\n lastSeenAt: string | null;\n configPath: string;\n hasConfigFile: boolean;\n}\n\n/**\n * Enumerate per-project config dirs. The meta.json's recorded\n * `originalPath` is what we report — the hash on disk is opaque.\n */\nexport async function listProjectsConfigured(): Promise<ProjectEntry[]> {\n let entries: string[];\n try {\n entries = await readdir(PROJECTS_DIR);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const out: ProjectEntry[] = [];\n for (const dirName of entries) {\n // Dir shape is `<sha1-16>` (legacy) or `<sha1-16>-<mnemonic>` (current);\n // either way the leading 16 hex chars are the canonical key.\n const m = /^([0-9a-f]{16})(?:-.+)?$/.exec(dirName);\n if (!m) continue;\n const hash = m[1]!;\n const meta = await readMeta(dirName);\n if (!meta) continue;\n const cfgPath = projectConfigFile(meta.originalPath);\n const hasConfig = await fileExists(cfgPath);\n out.push({\n hash,\n dirName,\n originalPath: meta.originalPath,\n createdAt: meta.createdAt,\n lastSeenAt: meta.lastSeenAt,\n configPath: cfgPath,\n hasConfigFile: hasConfig,\n });\n }\n out.sort((a, b) => a.originalPath.localeCompare(b.originalPath));\n return out;\n}\n\nexport interface PruneOrphanProjectConfigsOptions {\n dryRun?: boolean;\n /** Absolute project roots of live boxes — kept even if the folder is gone. */\n protectedPaths?: string[];\n}\n\nexport interface PruneOrphanProjectConfigsResult {\n removed: { hash: string; originalPath: string }[];\n dryRun: boolean;\n}\n\n/**\n * Delete `~/.agentbox/projects/<hash>/` dirs whose recorded `originalPath`\n * workspace folder no longer exists on disk. Conservative by construction:\n * only an ENOENT on `originalPath` counts as orphaned (a transient/permission\n * error is never treated as \"deleted\"), and any path in `protectedPaths` (the\n * project roots of still-live boxes) is left alone. Best-effort and\n * idempotent — a failed `rm` is swallowed.\n */\nexport async function pruneOrphanProjectConfigs(\n opts: PruneOrphanProjectConfigsOptions = {},\n): Promise<PruneOrphanProjectConfigsResult> {\n const dryRun = opts.dryRun ?? false;\n const keep = new Set(opts.protectedPaths ?? []);\n const removed: { hash: string; originalPath: string }[] = [];\n for (const entry of await listProjectsConfigured()) {\n if (!isAbsolute(entry.originalPath) || keep.has(entry.originalPath)) continue;\n let missing = false;\n try {\n await stat(entry.originalPath);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') missing = true;\n }\n if (!missing) continue;\n removed.push({ hash: entry.hash, originalPath: entry.originalPath });\n if (!dryRun) {\n try {\n // Remove by the on-disk dir name (originalPath is gone, so recomputing\n // the segment from it would be pointless; entry.dirName preserves\n // whichever shape — legacy `<hash>` or new `<hash>-<mnemonic>` —\n // happens to be on disk).\n await rm(join(PROJECTS_DIR, entry.dirName), { recursive: true, force: true });\n } catch {\n /* best-effort */\n }\n }\n }\n return { removed, dryRun };\n}\n\n/**\n * Sidecar counter for the periodic create-time sweep. Lives inside\n * `PROJECTS_DIR` but `listProjectsConfigured` only reads 16-hex-named dirs, so\n * a dotfile here is invisible to it.\n */\nconst PROJECT_GC_COUNTER_FILE = join(PROJECTS_DIR, '.gc.json');\n\n/** Read `{creates}` (0 if missing/corrupt), increment, atomic-write, return new value. */\nexport async function bumpProjectGcCounter(): Promise<number> {\n let prior = 0;\n try {\n const parsed = JSON.parse(await readFile(PROJECT_GC_COUNTER_FILE, 'utf8')) as {\n creates?: unknown;\n };\n if (typeof parsed.creates === 'number' && Number.isFinite(parsed.creates)) {\n prior = parsed.creates;\n }\n } catch {\n /* missing or corrupt -> start from 0 */\n }\n const next = prior + 1;\n await mkdir(PROJECTS_DIR, { recursive: true });\n const tmp = `${PROJECT_GC_COUNTER_FILE}.tmp-${process.pid.toString()}-${Date.now().toString(36)}`;\n await writeFile(tmp, JSON.stringify({ creates: next }) + '\\n', { encoding: 'utf8', mode: 0o644 });\n await rename(tmp, PROJECT_GC_COUNTER_FILE);\n return next;\n}\n\nasync function readMeta(\n dirName: string,\n): Promise<{ originalPath: string; createdAt: string | null; lastSeenAt: string | null } | null> {\n const metaPath = `${PROJECTS_DIR}/${dirName}/meta.json`;\n try {\n const text = await readFile(metaPath, 'utf8');\n const parsed = JSON.parse(text) as Record<string, unknown>;\n if (typeof parsed['originalPath'] !== 'string') return null;\n return {\n originalPath: parsed['originalPath'],\n createdAt: typeof parsed['createdAt'] === 'string' ? parsed['createdAt'] : null,\n lastSeenAt: typeof parsed['lastSeenAt'] === 'string' ? parsed['lastSeenAt'] : null,\n };\n } catch {\n return null;\n }\n}\n\nasync function fileExists(p: string): Promise<boolean> {\n try {\n const st = await stat(p);\n return st.isFile();\n } catch {\n return false;\n }\n}\n\nasync function readExistingDoc(path: string): Promise<Partial<UserConfig>> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw err;\n }\n return parseUserConfig(text, path);\n}\n\n/**\n * Stamp `schema: 1` on a doc that hasn't been stamped yet. Idempotent — a\n * doc already carrying any `schema` value is left alone. Future schema\n * bumps live here.\n */\nconst CURRENT_CONFIG_SCHEMA = 1;\nfunction stampSchema(doc: Partial<UserConfig>): void {\n if (typeof doc.schema !== 'number') {\n doc.schema = CURRENT_CONFIG_SCHEMA;\n }\n}\n\nfunction setLeaf(doc: Partial<UserConfig>, key: string, value: unknown): void {\n const segs = key.split('.');\n let cur = doc as unknown as Record<string, unknown>;\n for (let i = 0; i < segs.length - 1; i++) {\n const seg = segs[i]!;\n const next = cur[seg];\n if (!next || typeof next !== 'object') {\n cur[seg] = {};\n }\n cur = cur[seg] as Record<string, unknown>;\n }\n cur[segs[segs.length - 1]!] = value;\n}\n\nfunction unsetLeaf(doc: Partial<UserConfig>, key: string): boolean {\n const segs = key.split('.');\n const path: Record<string, unknown>[] = [doc as unknown as Record<string, unknown>];\n for (let i = 0; i < segs.length - 1; i++) {\n const seg = segs[i]!;\n const next = path[path.length - 1]![seg];\n if (!next || typeof next !== 'object') return false;\n path.push(next as Record<string, unknown>);\n }\n const leafSeg = segs[segs.length - 1]!;\n const leafContainer = path[path.length - 1]!;\n if (!(leafSeg in leafContainer)) return false;\n delete leafContainer[leafSeg];\n // Prune empty parent objects from leaf-most up so the YAML stays tidy.\n for (let i = path.length - 1; i > 0; i--) {\n if (Object.keys(path[i]!).length > 0) break;\n delete path[i - 1]![segs[i - 1]!];\n }\n return true;\n}\n\nasync function atomicWriteYaml(path: string, doc: Partial<UserConfig>): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n // YAML serialises empty objects as `{}` which is correct but ugly; if the\n // doc is empty we still want a usable placeholder file.\n const text = Object.keys(doc).length === 0\n ? '# managed by agentbox config — empty\\n'\n : stringifyYaml(doc);\n const tmp = `${path}.tmp-${process.pid.toString()}-${Date.now().toString(36)}`;\n await writeFile(tmp, text, { encoding: 'utf8', mode: 0o644 });\n await rename(tmp, path);\n}\n\n/**\n * Register a project (a folder on the PC) in the on-disk registry so it is\n * enumerable via {@link listProjectsConfigured} even before it has any config\n * value or any box. Idempotent: creates `~/.agentbox/projects/<hash>/meta.json`\n * on first call and refreshes `lastSeenAt` (preserving `createdAt`) after.\n *\n * `absPath` should be a canonical project root (e.g. `findProjectRoot(cwd).root`).\n * Callers that start from an arbitrary user path should canonicalize first.\n */\nexport async function registerProject(absPath: string): Promise<void> {\n await touchProjectMeta(absPath);\n}\n\n/**\n * Remove a project from the on-disk registry by its {@link hashProjectPath}\n * hash — deletes `~/.agentbox/projects/<hash>-<mnemonic>/`, i.e. its `meta.json`\n * and any project-scoped `config.yaml` the user set for that folder. Does NOT\n * touch the workspace folder/files, its git repo, or checkpoints (a separate\n * `~/.agentbox/checkpoints/` tree). Idempotent: returns `false` when the hash\n * isn't registered (nothing to remove). Mirrors the delete\n * {@link pruneOrphanProjectConfigs} does (rm by the on-disk `dirName`).\n */\nexport async function unregisterProject(hash: string): Promise<boolean> {\n const entry = (await listProjectsConfigured()).find((e) => e.hash === hash);\n if (!entry) return false;\n await rm(join(PROJECTS_DIR, entry.dirName), { recursive: true, force: true });\n return true;\n}\n\nasync function touchProjectMeta(absPath: string): Promise<void> {\n const dir = dirname(projectMetaFile(absPath));\n await mkdir(dir, { recursive: true });\n const metaPath = projectMetaFile(absPath);\n let prior: { originalPath?: string; createdAt?: string } = {};\n try {\n prior = JSON.parse(await readFile(metaPath, 'utf8')) as typeof prior;\n } catch {\n /* fresh file */\n }\n const now = new Date().toISOString();\n const next = {\n originalPath: absPath,\n hash: hashProjectPath(absPath),\n createdAt: prior.createdAt ?? now,\n lastSeenAt: now,\n };\n const tmp = `${metaPath}.tmp-${process.pid.toString()}-${Date.now().toString(36)}`;\n await writeFile(tmp, JSON.stringify(next, null, 2) + '\\n', { encoding: 'utf8', mode: 0o644 });\n await rename(tmp, metaPath);\n}\n\n// Re-export for ergonomics; same path resolution as the loader uses.\nexport { configPathFor };\n"],"mappings":";;;AEAA,SAAS,SAAS,iBAAiB;ACAnC,SAAS,kBAAkB;AAC3B,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,MAAM,eAAe;ACHjD,SAAS,gBAAgB;AACzB,SAAS,SAASA,kBAAiB;AIDnC,SAAS,OAAO,YAAAC,WAAU,QAAQ,IAAI,QAAAC,OAAM,iBAAiB;AAC7D,SAAS,WAAAC,UAAS,YAAY,QAAAC,aAAY;AAC1C,SAAS,aAAa,qBAAqB;AAW3C,SAAS,eAAe;ARwBjB,IAAM,YAAY;EACvB;IACE,MAAM;IACN,MAAM;IACN,OAAO;IACP,WAAW;IACX,gBAAgB;IAChB,OAAO;IACP,UACE;IACF,WACE;EACJ;EACA;IACE,MAAM;IACN,MAAM;IACN,OAAO;IACP,WAAW;IACX,gBAAgB;IAChB,OAAO;IACP,UACE;IACF,WACE;EACJ;EACA;IACE,MAAM;IACN,MAAM;IACN,OAAO;IACP,WAAW;IACX,gBAAgB;IAChB,OAAO;IACP,UACE;IACF,WACE;EACJ;EACA;IACE,MAAM;IACN,MAAM;IACN,OAAO;IACP,WAAW;IACX,gBAAgB;IAChB,OAAO;IACP,UACE;IACF,WACE;EACJ;EACA;IACE,MAAM;IACN,MAAM;IACN,OAAO;IACP,WAAW;IACX,gBAAgB;IAChB,OAAO;IACP,UACE;IACF,WACE;EACJ;EACA;IACE,MAAM;IACN,MAAM;IACN,OAAO;IACP,WAAW;IACX,gBAAgB;IAChB,OAAO;IACP,UACE;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AM;IACN,aACE;IACF,UAAU;EACZ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;IACF,UAAU;EACZ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;IACF,UAAU;EACZ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,YAAY,CAAC,SAAS,UAAU,OAAO,MAAM;IAC7C,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,YAAY,CAAC,UAAU,UAAU,MAAM;IACvC,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,YAAY,CAAC,YAAY,kBAAkB,SAAS,MAAM;IAC1D,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,YAAY,CAAC,iBAAiB,cAAc,MAAM;IAClD,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;IACb,UAAU;EACZ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,YAAY,CAAC,QAAQ,SAAS,SAAS,QAAQ;IAC/C,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;IACb,UAAU;EACZ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;IACF,UAAU;EACZ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,YAAY,CAAC,QAAQ,SAAS,UAAU,KAAK;IAC7C,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IACL,MAAM;IACN,aAAa;EACf;EACA;IACE,KAAK;IACL,MAAM;IACN,aACE;EACJ;EACA;IACE,KAAK;IAC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,CAAC;AAC5D,MAAI;AACF,YAAQ,KAAK,MAAM,MAAMF,UAAS,UAAU,MAAM,CAAC;EACrD,QAAQ;EAER;AACA,QAAM,OAAM,oBAAI,KAAK,GAAE,YAAY;AACnC,QAAM,OAAO;IACX,cAAc;IACd,MAAM,gBAAgB,OAAO;IAC7B,WAAW,MAAM,aAAa;IAC9B,YAAY;EACd;AACA,QAAM,MAAM,GAAG,QAAQ,QAAQ,QAAQ,IAAI,SAAS,CAAC,IAAI,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC;AAChF,QAAM,UAAU,KAAK,KAAK,UAAU,MAAM,MAAM,CAAC,IAAI,MAAM,EAAE,UAAU,QAAQ,MAAM,IAAM,CAAC;AAC5F,QAAM,OAAO,KAAK,QAAQ;AAC5B;","names":["parseYaml","readFile","stat","dirname","join","fileExists"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/sandbox-digitalocean/src/env-loader.ts","../../../packages/sandbox-digitalocean/src/client.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 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 /** 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 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","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 spinner,\n} from '@clack/prompts';\nimport { makeDigitalOceanClient } from './client.js';\nimport { ensureDigitalOceanEnvLoaded } from './env-loader.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 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\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 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;AEFxB,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;OACK;AINP,SAAS,cAAAH,mBAAkB;AAC3B,SAAS,WAAAI,UAAS,WAAAD,gBAAe;AACjC,SAAS,qBAAqB;ANI9B,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,CAA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,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","dirname","opts","existsSync","readFileSync","resolve","homedir","log","raceTimeout","dirname"]}
|