@madarco/agentbox 0.20.0 → 0.20.1
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 +21 -0
- package/dist/{_cloud-attach-THTN4CFZ.js → _cloud-attach-MH7NKIZY.js} +3 -3
- package/dist/{chunk-ZX6DTA4X.js → chunk-3465NDRZ.js} +95 -7
- package/dist/chunk-3465NDRZ.js.map +1 -0
- package/dist/{chunk-7RWFYLF3.js → chunk-4ATVA3RM.js} +7 -7
- package/dist/{chunk-3VFY3N4A.js → chunk-5N7GA2X7.js} +58 -76
- package/dist/chunk-5N7GA2X7.js.map +1 -0
- package/dist/{dist-3PLT2EK2.js → dist-AJWL4WLW.js} +4 -2
- package/dist/{dist-3WFNXXPE.js → dist-CTTTHG6U.js} +5 -4
- package/dist/{dist-3WFNXXPE.js.map → dist-CTTTHG6U.js.map} +1 -1
- package/dist/{dist-7ELDXBAG.js → dist-G5PDFWKH.js} +7 -4
- package/dist/{dist-7ELDXBAG.js.map → dist-G5PDFWKH.js.map} +1 -1
- package/dist/{dist-CZ6CRADC.js → dist-LUEH7MER.js} +3 -3
- package/dist/dist-LUEH7MER.js.map +1 -0
- package/dist/{dist-C3YRC3PP.js → dist-T3JIYHCA.js} +3 -3
- package/dist/index.js +29 -29
- package/package.json +5 -5
- package/runtime/docker/Dockerfile.box +13 -0
- package/runtime/e2b/attach-helper.cjs +4 -1
- package/runtime/e2b/scripts/build-template.sh +10 -0
- package/runtime/hetzner/scripts/install-box.sh +9 -0
- package/runtime/vercel/scripts/provision.sh +20 -0
- package/dist/chunk-3VFY3N4A.js.map +0 -1
- package/dist/chunk-ZX6DTA4X.js.map +0 -1
- package/dist/dist-CZ6CRADC.js.map +0 -1
- /package/dist/{_cloud-attach-THTN4CFZ.js.map → _cloud-attach-MH7NKIZY.js.map} +0 -0
- /package/dist/{chunk-7RWFYLF3.js.map → chunk-4ATVA3RM.js.map} +0 -0
- /package/dist/{dist-3PLT2EK2.js.map → dist-AJWL4WLW.js.map} +0 -0
- /package/dist/{dist-C3YRC3PP.js.map → dist-T3JIYHCA.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/sandbox-e2b/src/index.ts","../../../packages/sandbox-e2b/src/backend.ts","../../../packages/sandbox-e2b/src/retry.ts","../../../packages/sandbox-e2b/src/prepare.ts","../../../packages/sandbox-e2b/src/build-attach.ts"],"sourcesContent":["/**\n * The E2B sandbox provider. A thin `CloudBackend` over the `e2b` v2 SDK,\n * composed via `@agentbox/sandbox-cloud`'s `createCloudProvider` for\n * everything provider-agnostic (workspace seeding, ctl launch, state, relay\n * polling).\n *\n * Three capabilities are overridden on top of the cloud scaffold:\n * - `prepare` — bake the custom base template via Template.build\n * (`agentbox prepare --provider e2b`).\n * - `buildAttach` — SDK-streaming PTY bridge (E2B has no SSH).\n * - `checkpoint` — store the E2B snapshot id (template id) in the manifest\n * so restore boots from it (`Sandbox.createSnapshot` produces an\n * id-addressed reusable snapshot, same shape as Vercel).\n *\n * `launchDockerd: true` — E2B microVMs DO support nested containers (full root\n * + cap_sys_admin + working namespaces, verified 2026-06-23), so the base\n * template bakes the docker engine and the cloud scaffold auto-starts dockerd\n * on every create/resume (same as the vercel/hetzner/daytona providers).\n */\n\nimport type { BoxRecord, Provider, ProviderCheckpoint } from '@agentbox/core';\nimport {\n createCloudProvider,\n currentCloudBaseFingerprint,\n listCloudCheckpoints,\n removeCloudCheckpointDir,\n resolveCloudCheckpoint,\n writeCloudCheckpointManifest,\n} from '@agentbox/sandbox-cloud';\nimport { readCliStamp, recordBox } from '@agentbox/sandbox-core';\nimport { e2bBackend, DEFAULT_BOX_IMAGE_REF } from './backend.js';\nimport { Sandbox, resolveApiKey } from './sdk.js';\nimport { withE2bRetry } from './retry.js';\nimport { prepareE2bProvider } from './prepare.js';\nimport { buildE2bAttach } from './build-attach.js';\nimport { currentE2bBaseFingerprintLive } from './prepared-state.js';\n\nconst BACKEND_NAME = 'e2b';\n\nconst cloudProvider = createCloudProvider(e2bBackend, {\n // E2B applies resources at the template level (Template.build({ cpuCount,\n // memoryMB }) — `prepare` sets these). The numbers below are advisory\n // metadata for BoxRecord stats / the dashboard pane; per-create overrides\n // aren't honored by the SDK.\n defaultResources: { cpu: 2, memory: 4, disk: 8 },\n launchDockerd: true,\n});\n\n/**\n * Create a reusable, named E2B snapshot from a running sandbox.\n * `Sandbox.createSnapshot` pauses the source while capturing, then returns a\n * persistent `snapshotId` (template id form: `name:tag` or `template-id:tag`)\n * usable with `Sandbox.create({ template })` — see SDK docs.\n */\nasync function createE2bSnapshot(sandboxId: string, name: string): Promise<string> {\n const apiKey = resolveApiKey();\n return withE2bRetry(\n { method: 'createSnapshot', retryOnAmbiguous: false, attemptTimeoutMs: 900_000, backoffMs: [] },\n async () => {\n const info = await Sandbox.createSnapshot(sandboxId, { apiKey, name });\n return info.snapshotId;\n },\n );\n}\n\n/** Delete a snapshot by id. Idempotent — a missing snapshot is success. */\nasync function deleteE2bSnapshot(snapshotId: string): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry({ method: 'deleteSnapshot', retryOnAmbiguous: true }, async () => {\n try {\n await Sandbox.deleteSnapshot(snapshotId, { apiKey });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (/not.?found|404/i.test(msg)) return; // idempotent\n throw err;\n }\n });\n}\n\n/**\n * Build a safe, unique E2B snapshot name. E2B names are global within a team\n * (`createSnapshot({ name })` reuses an existing name if it exists, growing\n * the build set). We stamp a per-create timestamp so each checkpoint gets its\n * own name → its own template id, never overwriting an earlier checkpoint.\n */\nfunction snapshotName(boxName: string, checkpointName: string): string {\n // E2B template names accept lower-case alnum + dashes/dots; coerce.\n const sanitize = (s: string): string =>\n s.toLowerCase().replace(/[^a-z0-9.-]+/g, '-').replace(/^-+|-+$/g, '');\n const ts = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').replace('Z', '');\n return `agentbox-${sanitize(boxName)}-${sanitize(checkpointName)}-${sanitize(ts)}`;\n}\n\n/**\n * E2B-specific checkpoint capability. Unlike the scaffold's default (which\n * stores a caller-chosen snapshot *name*), we capture the SDK-returned\n * opaque snapshot id and store THAT in the manifest's `snapshotName` field —\n * the cloud create flow passes `manifest.snapshotName` straight to\n * `provision({ snapshot })`, and the E2B backend boots from it as a template\n * id. (Same id-addressed shape as Vercel's checkpoint capability.)\n */\nconst e2bCheckpoint: ProviderCheckpoint = {\n async create(box: BoxRecord, name: string) {\n if (!box.projectRoot) {\n throw new Error(\n 'cloud checkpoint requires the box to have a project root (run `agentbox checkpoint` from inside the project)',\n );\n }\n if (!box.cloud?.sandboxId) {\n throw new Error(`e2b box ${box.name} has no sandboxId — record is malformed`);\n }\n // NOTE: createSnapshot pauses the source sandbox; agentbox-ctl-checkpoint\n // resumes it lazily on the next op (Sandbox.connect auto-resumes).\n const e2bSnapName = snapshotName(box.name, name);\n const snapshotId = await createE2bSnapshot(box.cloud.sandboxId, e2bSnapName);\n // The box is now paused — persist it so the fast `agentbox list` path\n // doesn't show a stale `running` after a checkpoint. Best-effort.\n try {\n await recordBox({ ...box, cloud: { ...box.cloud, lastState: 'paused' } });\n } catch {\n // not worth failing the checkpoint over a state-record write\n }\n const info = await writeCloudCheckpointManifest(box.projectRoot, BACKEND_NAME, name, {\n snapshotName: snapshotId,\n sourceBoxId: box.id,\n sourceBoxName: box.name,\n baseProvider: BACKEND_NAME,\n baseFingerprint: currentCloudBaseFingerprint(BACKEND_NAME),\n cliVersion: readCliStamp().cliVersion,\n });\n return { ref: info.name };\n },\n async list(projectRoot: string) {\n const entries = await listCloudCheckpoints(projectRoot, BACKEND_NAME);\n return entries.map((e) => ({ ref: e.name, createdAt: e.manifest.createdAt }));\n },\n async remove(projectRoot: string, ref: string) {\n const entry = await resolveCloudCheckpoint(projectRoot, BACKEND_NAME, ref);\n if (!entry) return;\n try {\n await deleteE2bSnapshot(entry.manifest.snapshotName);\n } catch {\n // best-effort: drop the local manifest even if the remote delete failed\n // (network/perms/already-gone) so the user isn't left with a dead pointer.\n }\n await removeCloudCheckpointDir(projectRoot, BACKEND_NAME, ref);\n },\n};\n\nexport const e2bProvider: Provider = {\n ...cloudProvider,\n prepare: prepareE2bProvider,\n buildAttach: buildE2bAttach,\n checkpoint: e2bCheckpoint,\n baseFingerprint: () => currentE2bBaseFingerprintLive(),\n};\n\nexport { e2bBackend, DEFAULT_BOX_IMAGE_REF };\nexport { ensureE2bEnvLoaded, reloadE2bEnv } from './env-loader.js';\nexport {\n ensureE2bCredentials,\n readE2bCredStatus,\n secretsPath,\n maskKey,\n type EnsureE2bCredentialsOptions,\n type E2bCredStatus,\n} from './credentials.js';\nexport {\n RUNTIME_ASSETS,\n candidatesFor,\n resolveRuntimeAssets,\n findStagedCliRuntimeRoot,\n type RuntimeAsset,\n type ResolvedAsset,\n} from './runtime-assets.js';\nexport {\n prepareE2b,\n prepareE2bProvider,\n type PrepareE2bOptions,\n type PrepareE2bResult,\n} from './prepare.js';\nexport {\n currentE2bBaseFingerprintLive,\n ensureE2bBaseTemplate,\n preparedStatePath,\n readPreparedState,\n writePreparedState,\n updatePreparedState,\n type PreparedE2bState,\n type PreparedE2bBase,\n} from './prepared-state.js';\nexport { buildE2bAttach } from './build-attach.js';\n","/**\n * E2B `CloudBackend` — maps the provider-neutral cloud primitives onto the\n * `e2b` v2 SDK (Firecracker microVMs + pause/resume persistence). Composed\n * into a full `Provider` by `@agentbox/sandbox-cloud`'s `createCloudProvider`.\n *\n * Platform shape this backend is built around:\n * - Boxes boot from the prepared base template baked by `agentbox prepare\n * --provider e2b` (Template.build → custom Debian image with agentbox-ctl,\n * the vscode user, /workspace, claude/codex/opencode, tmux, Chromium).\n * `backend.provision` gates on `ensureE2bBaseTemplate()` (mirrors the\n * hetzner/vercel pattern: `prepare` itself sidesteps the gate so a cold\n * install can bootstrap). A snapshot ref (cloud checkpoint) wins over\n * the prepared base.\n * - No nested containers (Firecracker microVM); the provider sets\n * `launchDockerd: false`.\n * - Preview URLs (`{port}-{sandboxId}.{E2B_DOMAIN}`) are public HTTPS by\n * default (allowPublicTraffic=true); no header token needed. We construct\n * the URL string locally so `previewUrl` doesn't have to `Sandbox.connect`\n * (which would auto-resume a paused box).\n * - `Sandbox.getInfo` is a NON-resuming static API; `state()`/`get()` use it\n * to check existence cheaply without waking a paused sandbox. Auto-resume\n * happens only inside `Sandbox.connect` (used by ops that need a live\n * handle: exec, file ops, pause, destroy).\n * - `Sandbox.pause` is the canonical pause API (`betaPause` is deprecated).\n * - `Sandbox.createSnapshot` is the reusable-snapshot primitive; the\n * provider overrides the whole `checkpoint` capability in index.ts to\n * store the resulting snapshot id (matching vercel's id-addressed shape).\n * - No SSH — the provider overrides `buildAttach` with an SDK-streaming\n * PTY bridge (`buildE2bAttach`); the legacy `attachArgv` slot stays\n * unset.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport type {\n CloudBackend,\n CloudExecOptions,\n CloudExecResult,\n CloudFileEntry,\n CloudHandle,\n CloudPreviewUrl,\n CloudProvisionRequest,\n CloudSandboxSummary,\n CloudState,\n} from '@agentbox/core';\nimport type { SandboxInfo, SandboxState } from './sdk.js';\nimport { Sandbox, Template, resolveApiKey } from './sdk.js';\nimport { withE2bRetry } from './retry.js';\nimport { ensureE2bBaseTemplate, readPreparedState } from './prepared-state.js';\n\n/**\n * Sentinel image ref the cloud-provider hands us when no --image was passed.\n * Mirrors docker's convention; the actual template id is read from the\n * prepared-state file by `provision`.\n */\nexport const DEFAULT_BOX_IMAGE_REF = 'agentbox/box:dev';\n\n/** Box user agentbox standardizes on (matches docker/vercel — created by build-template.sh). */\nconst BOX_USER = 'vscode';\nconst BOX_OWNER = 'vscode:vscode';\n\n/** Default E2B preview hostname. Override via the SDK's `E2B_DOMAIN` env. */\nconst DEFAULT_E2B_DOMAIN = 'e2b.app';\n\n/**\n * Per-box session timeout the SDK enforces at create. Past it, E2B\n * auto-terminates the sandbox. The host keepalive loop renews it while the\n * agent is active via `renewTimeout` (static `Sandbox.setTimeout`), so a\n * long-running session isn't killed mid-work. 45 min default mirrors vercel.\n */\nconst DEFAULT_TIMEOUT_MS = 45 * 60_000;\n\nconst E2B_WEB_PORT = 8080;\n\n/** Single-quote a string for safe embedding inside a `bash -lc '<…>'`. */\nfunction shq(s: string): string {\n return \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n\n/**\n * Convert a Node `Buffer` to a plain `ArrayBuffer` because E2B's `files.write`\n * `data:` field is `string | ArrayBuffer | Blob | ReadableStream` — Buffer is a\n * `Uint8Array` subclass and doesn't satisfy that union at the type level (even\n * though it works at runtime). Copy rather than slice the underlying buffer:\n * Buffers may share an underlying ArrayBuffer with a pooled allocator, so\n * `data.buffer` of a small Buffer can be a megabyte-long shared region.\n */\nfunction bufferToArrayBuffer(b: Buffer): ArrayBuffer {\n const ab = new ArrayBuffer(b.byteLength);\n new Uint8Array(ab).set(b);\n return ab;\n}\n\n/**\n * Map the SDK's nullable string state onto our 4-value `CloudState`.\n * E2B reports 'running' | 'paused' (per SDK types). Anything else (or absent)\n * → 'missing' so callers ping-pong the lifecycle into a clean state.\n */\nfunction mapState(s: SandboxState | undefined): CloudState {\n switch (s) {\n case 'running':\n return 'running';\n case 'paused':\n return 'paused';\n default:\n return 'missing';\n }\n}\n\n/** True when the error means \"sandbox doesn't exist\" (404). */\nfunction isNotFound(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false;\n const name = err instanceof Error ? err.name : '';\n if (name === 'SandboxNotFoundError' || name === 'NotFoundError') return true;\n const status = (err as { statusCode?: unknown; status?: unknown }).statusCode ?? (err as { status?: unknown }).status;\n return status === 404;\n}\n\n/**\n * Sanitize a box name for use as the `metadata.name` value. E2B accepts\n * arbitrary strings (probed) but we strip control chars defensively so a name\n * with embedded newlines can't break log parsing or response shapes.\n */\nfunction safeMetadataName(name: string): string {\n return name.replace(/[\\u0000-\\u001f]/g, '').slice(0, 200);\n}\n\nexport const e2bBackend: CloudBackend = {\n name: 'e2b',\n\n // The cloud scaffold's WebProxy binds whatever port we expose here, and\n // `agentbox url --kind=web` resolves via `getHost(port)`. 8080 matches the\n // non-privileged convention vercel uses — `getHost` accepts any port, but\n // staying on 8080 keeps the in-box ctl flag (AGENTBOX_WEB_PROXY_PORT)\n // identical across cloud providers.\n webProxyPort: E2B_WEB_PORT,\n\n async provision(req: CloudProvisionRequest): Promise<CloudHandle> {\n const apiKey = resolveApiKey();\n const log = req.onLog ?? (() => {});\n // Resolve the template to boot from: an explicit cloud-checkpoint snapshot\n // (req.snapshot) wins, else the prepared base template id. We don't fall\n // back to E2B's stock `base` template — every box must have the agentbox\n // runtime baked in. The gate throws an actionable \"run `agentbox prepare`\"\n // error when no template is recorded yet (mirrors the hetzner/vercel\n // pattern: `prepare` itself sidesteps the gate by calling `prepareE2b`\n // directly, never `provision`).\n if (req.snapshot === undefined) {\n ensureE2bBaseTemplate();\n }\n const template = req.snapshot ?? readPreparedState().base?.templateId;\n if (!template) {\n throw new Error(\n 'e2b provision: no template available — `agentbox prepare --provider e2b` must run first',\n );\n }\n\n // No-retry: Sandbox.create is billable and non-idempotent — a timeout\n // after the request reached the origin could leave a duplicate sandbox we\n // can't reference for cleanup.\n const sb = await withE2bRetry(\n { method: 'provision', retryOnAmbiguous: false, attemptTimeoutMs: 300_000, backoffMs: [] },\n async () =>\n Sandbox.create({\n apiKey,\n template,\n // Friendly name (so prune can see it) + the 'agentbox' marker so\n // `list()` can filter out sandboxes provisioned by other tooling.\n metadata: { agentbox: 'true', 'agentbox.name': safeMetadataName(req.name), name: safeMetadataName(req.name) },\n envs: req.env,\n timeoutMs: req.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n }),\n );\n log(`e2b: created sandbox ${sb.sandboxId} (template ${template})`);\n return { sandboxId: sb.sandboxId };\n },\n\n async get(sandboxId: string): Promise<CloudHandle | null> {\n const apiKey = resolveApiKey();\n return withE2bRetry({ method: 'get', retryOnAmbiguous: true }, async () => {\n try {\n // Static, NON-resuming — won't wake a paused sandbox just to confirm\n // it exists (per orchestrator review #1: connect would auto-resume).\n await Sandbox.getInfo(sandboxId, { apiKey });\n return { sandboxId };\n } catch (err) {\n if (isNotFound(err)) return null;\n throw err;\n }\n });\n },\n\n async list(): Promise<CloudSandboxSummary[]> {\n const apiKey = resolveApiKey();\n return withE2bRetry({ method: 'list', retryOnAmbiguous: true }, async () => {\n const summaries: CloudSandboxSummary[] = [];\n // Default query returns both running and paused sandboxes. We filter\n // client-side to the ones we created (metadata.agentbox === 'true').\n for (const state of ['running', 'paused'] as const) {\n const paginator = Sandbox.list({ apiKey, query: { state: [state] } });\n while (paginator.hasNext) {\n const page = await paginator.nextItems();\n for (const info of page) {\n if (info.metadata?.['agentbox'] !== 'true') continue;\n const friendly =\n info.metadata?.['agentbox.name'] ?? info.metadata?.['name'];\n const summary: CloudSandboxSummary = { sandboxId: info.sandboxId, state };\n if (friendly) summary.name = friendly;\n const startedAt = info.startedAt;\n if (startedAt instanceof Date) summary.createdAt = startedAt.toISOString();\n summaries.push(summary);\n }\n }\n }\n return summaries;\n });\n },\n\n // E2B has no separate stop primitive — sandboxes are either running or\n // paused. start is therefore a connect-and-resume (auto-resume inside\n // Sandbox.connect handles a paused box transparently).\n async start(h: CloudHandle): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry(\n { method: 'start', retryOnAmbiguous: true, attemptTimeoutMs: 120_000 },\n async () => {\n await Sandbox.connect(h.sandboxId, { apiKey });\n },\n );\n },\n\n // stop ≡ pause on E2B (the pause IS the cold-storage state).\n async stop(h: CloudHandle): Promise<void> {\n await this.pause(h);\n },\n\n async pause(h: CloudHandle): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry(\n { method: 'pause', retryOnAmbiguous: true, attemptTimeoutMs: 120_000 },\n async () => {\n await Sandbox.pause(h.sandboxId, { apiKey });\n },\n );\n },\n\n async resume(h: CloudHandle): Promise<void> {\n await this.start(h);\n },\n\n // E2B `setTimeout` SETS the TTL to N ms from now (absolute-from-now), so we\n // ignore the host's tracked deadline and use `target - now`. The static\n // `Sandbox.setTimeout` hits the API without `connect` (no resume of a paused\n // box). The host only calls when target > current, so this never shortens.\n async renewTimeout(h: CloudHandle, targetDeadlineEpochMs: number): Promise<void> {\n const ttlMs = Math.max(0, targetDeadlineEpochMs - Date.now());\n if (ttlMs === 0) return;\n const apiKey = resolveApiKey();\n await withE2bRetry({ method: 'renewTimeout', retryOnAmbiguous: true }, async () => {\n await Sandbox.setTimeout(h.sandboxId, ttlMs, { apiKey });\n });\n },\n\n async destroy(h: CloudHandle): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry(\n { method: 'destroy', retryOnAmbiguous: true, attemptTimeoutMs: 120_000 },\n async () => {\n try {\n await Sandbox.kill(h.sandboxId, { apiKey });\n } catch (err) {\n if (isNotFound(err)) return; // idempotent\n throw err;\n }\n },\n );\n },\n\n async state(h: CloudHandle): Promise<CloudState> {\n const apiKey = resolveApiKey();\n return withE2bRetry({ method: 'state', retryOnAmbiguous: true }, async () => {\n try {\n const info: SandboxInfo = await Sandbox.getInfo(h.sandboxId, { apiKey });\n return mapState(info.state);\n } catch (err) {\n if (isNotFound(err)) return 'missing';\n throw err;\n }\n });\n },\n\n async exec(h: CloudHandle, cmd: string, opts?: CloudExecOptions): Promise<CloudExecResult> {\n const apiKey = resolveApiKey();\n // Default per-attempt cap is 5 min — covers the cloud scaffold's\n // workspace-seed/carry extracts (tar of thousands of files, chown -R).\n // Callers can shorten with opts.attemptTimeoutMs for snappier probes.\n const timeoutMs = opts?.attemptTimeoutMs ?? 300_000;\n return withE2bRetry(\n {\n method: 'exec',\n retryOnAmbiguous: opts?.noRetry ? false : true,\n attemptTimeoutMs: timeoutMs,\n backoffMs: opts?.noRetry ? [] : undefined,\n },\n async () => {\n // Connect for the live handle — auto-resumes a paused box, which is\n // the correct semantics for exec (caller wants the command to run).\n const sb = await Sandbox.connect(h.sandboxId, { apiKey });\n // E2B's `commands.run` accepts only 'root' | 'user' | 'vscode'…; any\n // unix username we create in the fixup is valid. Pass through.\n const user = (opts?.user ?? BOX_USER) as 'root' | 'user';\n try {\n const r = await sb.commands.run(cmd, {\n ...(opts?.cwd !== undefined ? { cwd: opts.cwd } : {}),\n ...(opts?.env !== undefined ? { envs: opts.env } : {}),\n user,\n timeoutMs,\n });\n return { exitCode: r.exitCode, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };\n } catch (err) {\n // commands.run throws on non-zero exit; the CommandResult fields\n // (exitCode/stdout/stderr) hang off the error. Map back into our\n // CloudExecResult so callers see exit=1, not a thrown exception\n // (vercel/daytona/hetzner exec contract returns the result).\n if (err instanceof Error && err.name === 'CommandExitError') {\n const ce = err as unknown as {\n exitCode: number;\n stdout: string;\n stderr: string;\n };\n return { exitCode: ce.exitCode, stdout: ce.stdout ?? '', stderr: ce.stderr ?? '' };\n }\n throw err;\n }\n },\n );\n },\n\n async uploadFile(h: CloudHandle, localPath: string, remotePath: string): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry(\n { method: 'uploadFile', retryOnAmbiguous: true, attemptTimeoutMs: 300_000 },\n async () => {\n const data = await readFile(localPath);\n const sb = await Sandbox.connect(h.sandboxId, { apiKey });\n await sb.files.write([{ path: remotePath, data: bufferToArrayBuffer(data) }]);\n // files.write writes as the default user; chown to vscode so reads\n // from the scaffold's `sudo -u vscode …` exec calls succeed. Best-\n // effort — a chown failure on a world-readable file is harmless.\n try {\n await sb.commands.run(`sudo -n chown ${BOX_OWNER} ${shq(remotePath)}`, {\n user: 'root',\n timeoutMs: 10_000,\n });\n } catch {\n // ignore — file is at least present and readable\n }\n },\n );\n },\n\n async downloadFile(h: CloudHandle, remotePath: string, localPath: string): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry(\n { method: 'downloadFile', retryOnAmbiguous: true, attemptTimeoutMs: 300_000 },\n async () => {\n const sb = await Sandbox.connect(h.sandboxId, { apiKey });\n const bytes = await sb.files.read(remotePath, { format: 'bytes' });\n const { writeFile } = await import('node:fs/promises');\n await writeFile(localPath, Buffer.from(bytes));\n },\n );\n },\n\n async listFiles(h: CloudHandle, remoteDir: string): Promise<CloudFileEntry[]> {\n const apiKey = resolveApiKey();\n return withE2bRetry({ method: 'listFiles', retryOnAmbiguous: true }, async () => {\n const sb = await Sandbox.connect(h.sandboxId, { apiKey });\n const entries = await sb.files.list(remoteDir);\n return entries.map((e) => ({ name: e.name, isDir: e.type === 'dir' }));\n });\n },\n\n async previewUrl(h: CloudHandle, port: number): Promise<CloudPreviewUrl> {\n // E2B's `sandbox.getHost(port)` is just string interpolation of\n // `${port}-${sandboxId}.${sandboxDomain}` — calling it via Sandbox.connect\n // would auto-resume a paused box (the SDK's documented behavior). The\n // domain defaults to `e2b.app` with `E2B_DOMAIN` as the override (matches\n // the SDK's `ConnectionConfig` default), so we construct the URL locally\n // and never wake the box for a UI/dashboard URL fetch.\n const domain = process.env.E2B_DOMAIN ?? DEFAULT_E2B_DOMAIN;\n return { url: `https://${String(port)}-${h.sandboxId}.${domain}`, token: undefined };\n },\n\n // Fewer params than the interface's (h, port, expiresInSeconds) is fine —\n // E2B preview URLs are already public + browser-usable; no per-URL TTL.\n async signedPreviewUrl(h: CloudHandle, port: number): Promise<CloudPreviewUrl> {\n return this.previewUrl(h, port);\n },\n\n /**\n * Probe whether a snapshot (i.e. a template id) is still bootable. E2B's\n * snapshot ids look like `template-id:tag` or `team-slug/name:tag` — both\n * accepted by `Template.exists(name)`. Returns false on any lookup failure\n * (treated by the cloud-provider as \"gone\" so it falls back to a from-base\n * boot rather than 410ing the user).\n */\n async snapshotExists(snapshotName: string): Promise<boolean> {\n const apiKey = resolveApiKey();\n return withE2bRetry({ method: 'snapshotExists', retryOnAmbiguous: true }, async () => {\n try {\n return await Template.exists(snapshotName, { apiKey });\n } catch {\n return false;\n }\n });\n },\n};\n","/**\n * Bounded retry wrapper for E2B SDK calls — mirrors `withVercelRetry` /\n * `withHetznerRetry` in shape and intent. The E2B API rate-limits (429) and\n * can return transient 5xx during incidents; without bounded retries those\n * propagate as wedges in the calling lifecycle code.\n *\n * Non-idempotent ops (`provision`/`Sandbox.create`) pass `retryOnAmbiguous:\n * false` so a timeout after the request reached the origin doesn't create a\n * duplicate billable sandbox.\n */\n\nexport interface WithRetryOptions {\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 * Retry on errors where we can't be sure the server applied the request\n * (connection failures, per-attempt timeouts, 5xx). Set false for\n * non-idempotent operations where a retry could create a duplicate resource.\n */\n retryOnAmbiguous: boolean;\n /** Override the default 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(`e2b ${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/** HTTP status code dug out of whatever error shape the SDK throws. */\nfunction statusCodeOf(err: unknown): number | undefined {\n if (!err || typeof err !== 'object') return undefined;\n for (const key of ['statusCode', 'status', 'code'] as const) {\n const v = (err as Record<string, unknown>)[key];\n if (typeof v === 'number') return v;\n }\n const resp = (err as { response?: { status?: unknown } }).response;\n if (resp && typeof resp.status === 'number') return resp.status;\n return undefined;\n}\n\nexport function isRetriable(err: unknown, allowAmbiguous: boolean): boolean {\n if (err instanceof AttemptTimeoutError) return allowAmbiguous;\n\n // The SDK exposes a dedicated `SandboxNotFoundError` and `RateLimitError`.\n // Match by error name to avoid an import cycle (sdk.ts → retry → sdk).\n const name = err instanceof Error ? err.name : undefined;\n if (name === 'RateLimitError') return true;\n if (name === 'SandboxNotFoundError') return false;\n\n const status = statusCodeOf(err);\n if (status !== undefined) {\n if (status === 429) return true;\n if (status >= 500 && status <= 599) return allowAmbiguous;\n return false;\n }\n\n // Raw fetch / undici errors. Node wraps low-level errors in `{ cause }`.\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 return false;\n}\n\nexport async function withE2bRetry<T>(opts: WithRetryOptions, fn: () => Promise<T>): 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 `e2b ${opts.method}: attempt ${String(attempt)} failed (${errorSummary(err)}); retrying in ${String(delay)}ms`,\n );\n await sleep(delay);\n }\n }\n throw new Error(`withE2bRetry: exhausted attempts for ${opts.method}`);\n}\n\nfunction defaultRetryLog(line: string): void {\n process.stderr.write(`\\n[e2b-retry] ${line}\\n`);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, 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 Error) {\n const status = statusCodeOf(err);\n return status !== undefined\n ? `${err.name}(${String(status)}): ${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 * `agentbox prepare --provider e2b` — bake the E2B base template.\n *\n * Unlike Vercel/Hetzner, E2B can build templates from a build DSL (the SDK's\n * `Template` + `Template.build`). We mirror Vercel's `prepare` shape but drive\n * the build through the SDK builder API instead of booting a sandbox + running\n * `provision.sh`:\n *\n * 1. Resolve runtime assets + fingerprint the build context. Skip-fast when\n * an up-to-date template id is already recorded.\n * 2. Stage every resolved asset under a temp `fileContextPath` directory\n * with predictable relative names (E2B's `template.copy(src, dest)`\n * requires sources to be RELATIVE paths inside the context dir).\n * 3. `Template({ fileContextPath })` → `.fromBaseImage()` (E2B's default\n * Debian 12 + node 20 + git + sudo). `.copy(rel, dest)` for each asset,\n * `.runCmd('bash /tmp/agentbox-build-template.sh', { user: 'root' })`,\n * `.setReadyCmd('test -x /usr/local/bin/agentbox-ctl')`.\n * 4. `Template.build(t, 'agentbox-base:<tag>', { cpuCount, memoryMB,\n * onBuildLogs })` streams logs into the spinner; returns the BuildInfo\n * with the template id.\n * 5. Persist `{ schema:1, base: { templateId, contextSha256, cliVersion,\n * cliCommit, createdAt } }` to ~/.agentbox/e2b-prepared.json.\n *\n * Templates on E2B are reusable named resources addressed by id+tag. Re-running\n * with the same name reuses the existing template id (E2B's documented\n * behavior). Unlike Vercel snapshots there's no per-box eviction concern; one\n * template is reused for every create.\n *\n * vCPU / RAM are template-level on E2B — set them here so per-box `create`\n * doesn't try to override them (which E2B rejects).\n */\n\nimport { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport type { Provider } from '@agentbox/core';\nimport { computeContextSha256, readCliStamp } from '@agentbox/sandbox-core';\nimport { ensureE2bCredentials } from './credentials.js';\nimport { resolveApiKey, Template } from './sdk.js';\nimport {\n preparedStatePath,\n readPreparedState,\n writePreparedState,\n} from './prepared-state.js';\nimport {\n findStagedCliRuntimeRoot,\n resolveRuntimeAssets,\n type ResolvedAsset,\n} from './runtime-assets.js';\n\nexport interface PrepareE2bOptions {\n name?: string;\n hostWorkspace?: string;\n /** Force re-bake even when an up-to-date template id is recorded. */\n force?: boolean;\n /** vCPUs for the baked template (default 2). E2B applies this per-sandbox at boot. */\n cpuCount?: number;\n /** Memory in MiB for the baked template (default 4096). */\n memoryMB?: number;\n /** CLI runtime tree (set by the CLI to its dist neighbor). */\n cliRuntimeRoot?: string;\n /** Repo root for the dev fallback (defaults to a cwd-walk). */\n repoRoot?: string;\n onLog?: (line: string) => void;\n}\n\nexport interface PrepareE2bResult {\n snapshotName?: string;\n}\n\n/** Template name agentbox bakes under. E2B treats `name:tag` as a single addressable build. */\nconst TEMPLATE_NAME = 'agentbox-base:latest';\nconst DEFAULT_TAG = 'latest';\n\nconst DEFAULT_CPU = 2;\nconst DEFAULT_MEMORY_MB = 4096;\n\nexport async function prepareE2b(\n opts: PrepareE2bOptions = {},\n): Promise<PrepareE2bResult> {\n await ensureE2bCredentials();\n const apiKey = resolveApiKey();\n const log = opts.onLog ?? (() => {});\n const progress = (s: string) => log(`prepare-e2b: ${s}`);\n\n const assets = resolveRuntimeAssets({\n cliRuntimeRoot: opts.cliRuntimeRoot ?? findStagedCliRuntimeRoot(),\n repoRoot: opts.repoRoot,\n });\n const contextSha = await computeContextSha256(\n assets.map((a) => ({ rel: a.name, abs: a.localPath })),\n );\n\n // Skip-fast: existing template + matching fingerprint.\n //\n // Probe the persisted templateId itself, not TEMPLATE_NAME. If someone\n // (or another bake) rebuilt the alias under a different id, the name still\n // resolves but the stored id is stale and `Sandbox.create({ template: <stale id> })`\n // 404s. `Template.exists` accepts both `name:tag` and `template-id:tag`\n // forms, so we pass the exact id we'd later hand to `provision`.\n const existing = readPreparedState();\n if (!opts.force && existing.base) {\n if (existing.base.contextSha256 === contextSha) {\n const stillThere = await templateExists(existing.base.templateId, apiKey);\n if (stillThere) {\n progress(\n `template ${existing.base.templateId} already exists (fingerprint ${contextSha.slice(0, 12)} matches); skipping (pass --force to rebuild)`,\n );\n return { snapshotName: existing.base.templateId };\n }\n progress(`recorded template ${existing.base.templateId} is gone on E2B; rebuilding`);\n } else {\n progress(\n `build context changed (was ${existing.base.contextSha256?.slice(0, 12) ?? '<none>'}, now ${contextSha.slice(0, 12)}); rebuilding`,\n );\n }\n }\n\n // E2B's `template.copy(src, dest)` requires `src` to be a RELATIVE path\n // inside the Template's `fileContextPath`. Stage every resolved asset into\n // a temp dir under its logical name (asset.name) so the copy chain reads\n // from a single context root.\n const contextDir = await mkdtemp(join(tmpdir(), 'agentbox-e2b-build-'));\n try {\n progress(`staging build context at ${contextDir}`);\n await stageAssetsInto(contextDir, assets);\n\n // Build the Template via the SDK builder. fromBaseImage() starts from E2B's\n // own `e2bdev/base` (Debian 12 + node 20 + git + sudo), which halves the\n // install time vs starting from a vanilla Debian image.\n progress('assembling template build (fromBaseImage + asset copy + runCmd)');\n const template = Template({ fileContextPath: contextDir }).fromBaseImage();\n for (const a of assets) {\n progress(` copy ${a.name} -> ${a.remotePath}`);\n template.copy(a.name, a.remotePath, {\n forceUpload: true,\n mode: a.remoteMode,\n user: 'root',\n });\n }\n template.runCmd('bash /tmp/agentbox-build-template.sh 2>&1', { user: 'root' });\n // setReadyCmd flips the builder into TemplateFinal — required for build().\n // The check passes once the script's last `install` step lands the ctl bundle.\n const finalTemplate = template.setReadyCmd(\n 'test -x /usr/local/bin/agentbox-ctl',\n );\n\n const cpuCount = opts.cpuCount ?? DEFAULT_CPU;\n const memoryMB = opts.memoryMB ?? DEFAULT_MEMORY_MB;\n progress(\n `running Template.build('${TEMPLATE_NAME}', { cpuCount: ${String(cpuCount)}, memoryMB: ${String(memoryMB)} })`,\n );\n const info = await Template.build(finalTemplate, TEMPLATE_NAME, {\n apiKey,\n cpuCount,\n memoryMB,\n onBuildLogs: (entry: LogEntryLike) => {\n // LogEntry exposes timestamp / level / message; stream the human form.\n log(`[build] ${formatBuildLog(entry)}`);\n },\n });\n progress(`template built: id=${info.templateId} build=${info.buildId} name=${info.name}`);\n\n // Persist. `Sandbox.create({ template })` auto-appends `:default` when no\n // tag is given (and 404s if that tag wasn't built), so we MUST store the\n // tagged form. `info.templateId` is just the raw id with no tag; use the\n // first tag we built with (`latest`) or fall back to `info.tags[0]`.\n const tag = info.tags?.[0] ?? DEFAULT_TAG;\n const cliStamp = readCliStamp();\n const taggedId = `${info.templateId}:${tag}`;\n writePreparedState({\n schema: 1,\n base: {\n templateId: taggedId,\n // info.name is the full `name:tag` pair Template.build() was called\n // with (e.g. `agentbox-base:latest`). Earlier code re-appended `:${tag}`\n // and produced `agentbox-base:latest:latest` in the status display.\n templateName: info.name,\n contextSha256: contextSha,\n cliVersion: cliStamp.cliVersion,\n cliCommit: cliStamp.cliCommit,\n createdAt: new Date().toISOString(),\n },\n });\n progress(`wrote ${preparedStatePath()}`);\n\n progress(`prepare complete — base template ${taggedId}`);\n return { snapshotName: taggedId };\n } finally {\n await rm(contextDir, { recursive: true, force: true }).catch(() => {\n // best-effort: temp dir cleanup failures are noise, not errors.\n });\n }\n}\n\n/**\n * Copy every asset into `contextDir` under its logical `name`. Preserves the\n * source mode on the copy (E2B's `template.copy` also accepts a `mode`\n * override, but the on-disk mode keeps the local stage representative).\n */\nasync function stageAssetsInto(\n contextDir: string,\n assets: ResolvedAsset[],\n): Promise<void> {\n for (const a of assets) {\n const dest = resolve(contextDir, a.name);\n await mkdir(dirname(dest), { recursive: true });\n await copyFile(a.localPath, dest);\n }\n}\n\n/**\n * Check if a named template is bootable on E2B. Returns true on a 'ready'\n * build, false on anything else (deleted, errored, never built). Used by the\n * skip-fast path to detect a template that was deleted out-of-band.\n */\nasync function templateExists(name: string, apiKey: string): Promise<boolean> {\n try {\n return await Template.exists(name, { apiKey });\n } catch {\n return false;\n }\n}\n\n/**\n * E2B's `LogEntry` shape (timestamp, level, message). We treat the SDK's\n * type loosely here so the line-stream doesn't bind us to internal class\n * shapes — only the `.toString()` plus `.message` are documented.\n */\ninterface LogEntryLike {\n message?: string;\n level?: string;\n timestamp?: Date;\n toString(): string;\n}\n\nfunction formatBuildLog(entry: LogEntryLike): string {\n // The SDK's LogEntry.toString() emits a `[level] timestamp message` form.\n // For the spinner we only want the message — and clip overly long lines.\n const raw = typeof entry.message === 'string' ? entry.message : entry.toString();\n const cleaned = raw.replace(/\\r?\\n+$/, '');\n return cleaned.length > 200 ? cleaned.slice(0, 200) + '…' : cleaned;\n}\n\n/** Provider-level binding used by the CLI's `prepare` command. */\nexport const prepareE2bProvider: NonNullable<Provider['prepare']> = (req) =>\n prepareE2b({\n name: req.name,\n hostWorkspace: req.hostWorkspace ?? process.cwd(),\n force: req.force,\n onLog: req.onLog,\n });\n","/**\n * `buildE2bAttach` — the E2B provider's override of `Provider.buildAttach`.\n *\n * E2B has no SSH and no public PTY CLI like Vercel's `sbx exec -i`. We ship\n * our own attach helper (`attach-helper.cjs`) that connects to the sandbox via\n * the SDK and bridges the host PTY to an in-box `sandbox.pty.create()`.\n *\n * Argv shape:\n * node <attach-helper.cjs> --sandbox-id <id> --user vscode\n *\n * The inner bash command (`renderInnerCommand` output: tmux ensure + attach)\n * is passed through the environment as `AGENTBOX_E2B_INNER_CMD` so quoting\n * stays sane and it doesn't leak through `ps`. `E2B_API_KEY` is passed through\n * the env for the same reason. `node-pty` (the host PTY wrapper) is what\n * spawns this argv, so stdin/stdout/SIGWINCH all reach the helper unchanged.\n */\n\nimport { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n type AttachKind,\n type AttachSpec,\n type BoxRecord,\n type BuildAttachOptions,\n} from '@agentbox/core';\nimport { renderInnerCommand } from '@agentbox/sandbox-cloud';\nimport { resolveApiKey } from './sdk.js';\n\nconst SELF = dirname(fileURLToPath(import.meta.url));\n\n/**\n * Resolve the absolute path to `attach-helper.cjs`. In the published CLI it\n * lives at `runtime/e2b/attach-helper.cjs` (next to the staged provider\n * runtime tree); in dev it lives next to the package's `dist/`.\n */\nexport function resolveAttachHelperPath(): string {\n const candidates = [\n // dev: dist/index.js sibling\n resolve(SELF, 'attach-helper.cjs'),\n // dev: src compiled to dist/, while index.ts is in src/\n resolve(SELF, '..', 'dist', 'attach-helper.cjs'),\n // staged CLI: apps/cli/runtime/e2b/attach-helper.cjs\n resolve(SELF, '..', 'runtime', 'e2b', 'attach-helper.cjs'),\n resolve(SELF, '..', '..', 'runtime', 'e2b', 'attach-helper.cjs'),\n ];\n for (const p of candidates) {\n if (existsSync(p)) return p;\n }\n // Last-resort: still return the first candidate so the error message points\n // somewhere informative.\n return candidates[0]!;\n}\n\nexport async function buildE2bAttach(\n box: BoxRecord,\n kind: AttachKind,\n opts?: BuildAttachOptions,\n): Promise<AttachSpec> {\n const sandboxId = box.cloud?.sandboxId;\n if (!sandboxId) {\n throw new Error(`e2b box ${box.name} has no sandboxId — record is malformed`);\n }\n\n const helper = resolveAttachHelperPath();\n if (!existsSync(helper)) {\n throw new Error(\n `e2b attach helper not found at ${helper} — rebuild the CLI (\\`pnpm -w build\\`) ` +\n 'so packages/sandbox-e2b/dist/attach-helper.cjs is generated.',\n );\n }\n\n const apiKey = resolveApiKey();\n const inner = renderInnerCommand(kind, opts);\n\n const argv = [\n process.execPath,\n helper,\n '--sandbox-id',\n sandboxId,\n '--user',\n 'vscode',\n ];\n // Detached pre-start (new-tab attach / `-i` queue worker): the inner command\n // only creates the tmux session (no `exec tmux attach`). The helper must run\n // it once and EXIT rather than open a persistent interactive PTY that idles\n // forever — otherwise the host's `runDetached` await never resolves and\n // `agentbox <agent>` hangs after \"box ready\". See attach-helper.ts header.\n if (opts?.detached) argv.push('--detached');\n\n return {\n argv,\n env: {\n E2B_API_KEY: apiKey,\n AGENTBOX_E2B_INNER_CMD: inner,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACgCA,SAAS,gBAAgB;AEAzB,SAAS,UAAU,OAAO,SAAS,UAAU;AAC7C,SAAS,cAAc;AACvB,SAAS,SAAS,MAAM,eAAe;ACjBvC,SAAS,kBAAkB;AAC3B,SAAS,WAAAA,UAAS,WAAAC,gBAAe;AACjC,SAAS,qBAAqB;AFQ9B,IAAM,kBAAqC,CAAC,KAAM,KAAM,GAAI;AAC5D,IAAM,6BAA6B;AAEnC,IAAM,sBAAN,cAAkC,MAAM;EACtC,YAAY,QAAgB,IAAY;AACtC,UAAM,OAAO,MAAM,+BAA+B,OAAO,EAAE,CAAC,IAAI;AAChE,SAAK,OAAO;EACd;AACF;AAOA,SAAS,aAAa,KAAkC;AACtD,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,aAAW,OAAO,CAAC,cAAc,UAAU,MAAM,GAAY;AAC3D,UAAM,IAAK,IAAgC,GAAG;AAC9C,QAAI,OAAO,MAAM,SAAU,QAAO;EACpC;AACA,QAAM,OAAQ,IAA4C;AAC1D,MAAI,QAAQ,OAAO,KAAK,WAAW,SAAU,QAAO,KAAK;AACzD,SAAO;AACT;AAEO,SAAS,YAAY,KAAc,gBAAkC;AAC1E,MAAI,eAAe,oBAAqB,QAAO;AAI/C,QAAM,OAAO,eAAe,QAAQ,IAAI,OAAO;AAC/C,MAAI,SAAS,iBAAkB,QAAO;AACtC,MAAI,SAAS,uBAAwB,QAAO;AAE5C,QAAM,SAAS,aAAa,GAAG;AAC/B,MAAI,WAAW,QAAW;AACxB,QAAI,WAAW,IAAK,QAAO;AAC3B,QAAI,UAAU,OAAO,UAAU,IAAK,QAAO;AA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AI,MAAM,WAAW,WAAW;AAG3E,QAAI;AACF,YAAM,UAAU,EAAE,GAAG,KAAK,OAAO,EAAE,GAAG,IAAI,OAAO,WAAW,SAAS,EAAE,CAAC;IAC1E,QAAQ;IAER;AACA,UAAM,OAAO,MAAM,6BAA6B,IAAI,aAAa,cAAc,MAAM;MACnF,cAAc;MACd,aAAa,IAAI;MACjB,eAAe,IAAI;MACnB,cAAc;MACd,iBAAiB,4BAA4B,YAAY;MACzD,YAAYC,aAAa,EAAE;IAC7B,CAAC;AACD,WAAO,EAAE,KAAK,KAAK,KAAK;EAC1B;EACA,MAAM,KAAK,aAAqB;AAC9B,UAAM,UAAU,MAAM,qBAAqB,aAAa,YAAY;AACpE,WAAO,QAAQ,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,EAAE,SAAS,UAAU,EAAE;EAC9E;EACA,MAAM,OAAO,aAAqB,KAAa;AAC7C,UAAM,QAAQ,MAAM,uBAAuB,aAAa,cAAc,GAAG;AACzE,QAAI,CAAC,MAAO;AACZ,QAAI;AACF,YAAM,kBAAkB,MAAM,SAAS,YAAY;IACrD,QAAQ;IAGR;AACA,UAAM,yBAAyB,aAAa,cAAc,GAAG;EAC/D;AACF;AAEO,IAAM,cAAwB;EACnC,GAAG;EACH,SAAS;EACT,aAAa;EACb,YAAY;EACZ,iBAAiB,MAAM,8BAA8B;AACvD;","names":["dirname","resolve","snapshotName","dirname","resolve","readCliStamp"]}
|
|
1
|
+
{"version":3,"sources":["../../../packages/sandbox-e2b/src/index.ts","../../../packages/sandbox-e2b/src/backend.ts","../../../packages/sandbox-e2b/src/retry.ts","../../../packages/sandbox-e2b/src/prepare.ts","../../../packages/sandbox-e2b/src/build-attach.ts"],"sourcesContent":["/**\n * The E2B sandbox provider. A thin `CloudBackend` over the `e2b` v2 SDK,\n * composed via `@agentbox/sandbox-cloud`'s `createCloudProvider` for\n * everything provider-agnostic (workspace seeding, ctl launch, state, relay\n * polling).\n *\n * Three capabilities are overridden on top of the cloud scaffold:\n * - `prepare` — bake the custom base template via Template.build\n * (`agentbox prepare --provider e2b`).\n * - `buildAttach` — SDK-streaming PTY bridge (E2B has no SSH).\n * - `checkpoint` — store the E2B snapshot id (template id) in the manifest\n * so restore boots from it (`Sandbox.createSnapshot` produces an\n * id-addressed reusable snapshot, same shape as Vercel).\n *\n * `launchDockerd: true` — E2B microVMs DO support nested containers (full root\n * + cap_sys_admin + working namespaces, verified 2026-06-23), so the base\n * template bakes the docker engine and the cloud scaffold auto-starts dockerd\n * on every create/resume (same as the vercel/hetzner/daytona providers).\n */\n\nimport type { BoxRecord, Provider, ProviderCheckpoint } from '@agentbox/core';\nimport {\n createCloudProvider,\n currentCloudBaseFingerprint,\n listCloudCheckpoints,\n removeCloudCheckpointDir,\n resolveCloudCheckpoint,\n writeCloudCheckpointManifest,\n} from '@agentbox/sandbox-cloud';\nimport { readCliStamp, recordBox } from '@agentbox/sandbox-core';\nimport { e2bBackend, DEFAULT_BOX_IMAGE_REF } from './backend.js';\nimport { Sandbox, resolveApiKey } from './sdk.js';\nimport { withE2bRetry } from './retry.js';\nimport { prepareE2bProvider } from './prepare.js';\nimport { buildE2bAttach } from './build-attach.js';\nimport { currentE2bBaseFingerprintLive } from './prepared-state.js';\n\nconst BACKEND_NAME = 'e2b';\n\nconst cloudProvider = createCloudProvider(e2bBackend, {\n // E2B applies resources at the template level (Template.build({ cpuCount,\n // memoryMB }) — `prepare` sets these). The numbers below are advisory\n // metadata for BoxRecord stats / the dashboard pane; per-create overrides\n // aren't honored by the SDK.\n defaultResources: { cpu: 2, memory: 4, disk: 8 },\n launchDockerd: true,\n});\n\n/**\n * Create a reusable, named E2B snapshot from a running sandbox.\n * `Sandbox.createSnapshot` pauses the source while capturing, then returns a\n * persistent `snapshotId` (template id form: `name:tag` or `template-id:tag`)\n * usable with `Sandbox.create({ template })` — see SDK docs.\n */\nasync function createE2bSnapshot(sandboxId: string, name: string): Promise<string> {\n const apiKey = resolveApiKey();\n return withE2bRetry(\n { method: 'createSnapshot', retryOnAmbiguous: false, attemptTimeoutMs: 900_000, backoffMs: [] },\n async () => {\n const info = await Sandbox.createSnapshot(sandboxId, { apiKey, name });\n return info.snapshotId;\n },\n );\n}\n\n/** Delete a snapshot by id. Idempotent — a missing snapshot is success. */\nasync function deleteE2bSnapshot(snapshotId: string): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry({ method: 'deleteSnapshot', retryOnAmbiguous: true }, async () => {\n try {\n await Sandbox.deleteSnapshot(snapshotId, { apiKey });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (/not.?found|404/i.test(msg)) return; // idempotent\n throw err;\n }\n });\n}\n\n/**\n * Build a safe, unique E2B snapshot name. E2B names are global within a team\n * (`createSnapshot({ name })` reuses an existing name if it exists, growing\n * the build set). We stamp a per-create timestamp so each checkpoint gets its\n * own name → its own template id, never overwriting an earlier checkpoint.\n */\nfunction snapshotName(boxName: string, checkpointName: string): string {\n // E2B template names accept lower-case alnum + dashes/dots; coerce.\n const sanitize = (s: string): string =>\n s.toLowerCase().replace(/[^a-z0-9.-]+/g, '-').replace(/^-+|-+$/g, '');\n const ts = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').replace('Z', '');\n return `agentbox-${sanitize(boxName)}-${sanitize(checkpointName)}-${sanitize(ts)}`;\n}\n\n/**\n * E2B-specific checkpoint capability. Unlike the scaffold's default (which\n * stores a caller-chosen snapshot *name*), we capture the SDK-returned\n * opaque snapshot id and store THAT in the manifest's `snapshotName` field —\n * the cloud create flow passes `manifest.snapshotName` straight to\n * `provision({ snapshot })`, and the E2B backend boots from it as a template\n * id. (Same id-addressed shape as Vercel's checkpoint capability.)\n */\nconst e2bCheckpoint: ProviderCheckpoint = {\n async create(box: BoxRecord, name: string) {\n if (!box.projectRoot) {\n throw new Error(\n 'cloud checkpoint requires the box to have a project root (run `agentbox checkpoint` from inside the project)',\n );\n }\n if (!box.cloud?.sandboxId) {\n throw new Error(`e2b box ${box.name} has no sandboxId — record is malformed`);\n }\n // NOTE: createSnapshot pauses the source sandbox; agentbox-ctl-checkpoint\n // resumes it lazily on the next op (Sandbox.connect auto-resumes).\n const e2bSnapName = snapshotName(box.name, name);\n const snapshotId = await createE2bSnapshot(box.cloud.sandboxId, e2bSnapName);\n // The box is now paused — persist it so the fast `agentbox list` path\n // doesn't show a stale `running` after a checkpoint. Best-effort.\n try {\n await recordBox({ ...box, cloud: { ...box.cloud, lastState: 'paused' } });\n } catch {\n // not worth failing the checkpoint over a state-record write\n }\n const info = await writeCloudCheckpointManifest(box.projectRoot, BACKEND_NAME, name, {\n snapshotName: snapshotId,\n sourceBoxId: box.id,\n sourceBoxName: box.name,\n baseProvider: BACKEND_NAME,\n baseFingerprint: currentCloudBaseFingerprint(BACKEND_NAME),\n cliVersion: readCliStamp().cliVersion,\n });\n return { ref: info.name };\n },\n async list(projectRoot: string) {\n const entries = await listCloudCheckpoints(projectRoot, BACKEND_NAME);\n return entries.map((e) => ({ ref: e.name, createdAt: e.manifest.createdAt }));\n },\n async remove(projectRoot: string, ref: string) {\n const entry = await resolveCloudCheckpoint(projectRoot, BACKEND_NAME, ref);\n if (!entry) return;\n try {\n await deleteE2bSnapshot(entry.manifest.snapshotName);\n } catch {\n // best-effort: drop the local manifest even if the remote delete failed\n // (network/perms/already-gone) so the user isn't left with a dead pointer.\n }\n await removeCloudCheckpointDir(projectRoot, BACKEND_NAME, ref);\n },\n};\n\nexport const e2bProvider: Provider = {\n ...cloudProvider,\n prepare: prepareE2bProvider,\n buildAttach: buildE2bAttach,\n checkpoint: e2bCheckpoint,\n baseFingerprint: () => currentE2bBaseFingerprintLive(),\n};\n\nexport { e2bBackend, DEFAULT_BOX_IMAGE_REF };\nexport { ensureE2bEnvLoaded, reloadE2bEnv } from './env-loader.js';\nexport {\n ensureE2bCredentials,\n readE2bCredStatus,\n secretsPath,\n maskKey,\n type EnsureE2bCredentialsOptions,\n type E2bCredStatus,\n} from './credentials.js';\nexport {\n RUNTIME_ASSETS,\n candidatesFor,\n resolveRuntimeAssets,\n findStagedCliRuntimeRoot,\n type RuntimeAsset,\n type ResolvedAsset,\n} from './runtime-assets.js';\nexport {\n prepareE2b,\n prepareE2bProvider,\n type PrepareE2bOptions,\n type PrepareE2bResult,\n} from './prepare.js';\nexport {\n currentE2bBaseFingerprintLive,\n ensureE2bBaseTemplate,\n preparedStatePath,\n readPreparedState,\n writePreparedState,\n updatePreparedState,\n type PreparedE2bState,\n type PreparedE2bBase,\n} from './prepared-state.js';\nexport { buildE2bAttach } from './build-attach.js';\n","/**\n * E2B `CloudBackend` — maps the provider-neutral cloud primitives onto the\n * `e2b` v2 SDK (Firecracker microVMs + pause/resume persistence). Composed\n * into a full `Provider` by `@agentbox/sandbox-cloud`'s `createCloudProvider`.\n *\n * Platform shape this backend is built around:\n * - Boxes boot from the prepared base template baked by `agentbox prepare\n * --provider e2b` (Template.build → custom Debian image with agentbox-ctl,\n * the vscode user, /workspace, claude/codex/opencode, tmux, Chromium).\n * `backend.provision` gates on `ensureE2bBaseTemplate()` (mirrors the\n * hetzner/vercel pattern: `prepare` itself sidesteps the gate so a cold\n * install can bootstrap). A snapshot ref (cloud checkpoint) wins over\n * the prepared base.\n * - No nested containers (Firecracker microVM); the provider sets\n * `launchDockerd: false`.\n * - Preview URLs (`{port}-{sandboxId}.{E2B_DOMAIN}`) are public HTTPS by\n * default (allowPublicTraffic=true); no header token needed. We construct\n * the URL string locally so `previewUrl` doesn't have to `Sandbox.connect`\n * (which would auto-resume a paused box).\n * - `Sandbox.getInfo` is a NON-resuming static API; `state()`/`get()` use it\n * to check existence cheaply without waking a paused sandbox. Auto-resume\n * happens only inside `Sandbox.connect` (used by ops that need a live\n * handle: exec, file ops, pause, destroy).\n * - `Sandbox.pause` is the canonical pause API (`betaPause` is deprecated).\n * - `Sandbox.createSnapshot` is the reusable-snapshot primitive; the\n * provider overrides the whole `checkpoint` capability in index.ts to\n * store the resulting snapshot id (matching vercel's id-addressed shape).\n * - No SSH — the provider overrides `buildAttach` with an SDK-streaming\n * PTY bridge (`buildE2bAttach`); the legacy `attachArgv` slot stays\n * unset.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport type {\n CloudBackend,\n CloudExecOptions,\n CloudExecResult,\n CloudFileEntry,\n CloudHandle,\n CloudPreviewUrl,\n CloudProvisionRequest,\n CloudSandboxSummary,\n CloudState,\n} from '@agentbox/core';\nimport type { SandboxInfo, SandboxState } from './sdk.js';\nimport { Sandbox, Template, resolveApiKey } from './sdk.js';\nimport { withE2bRetry } from './retry.js';\nimport { ensureE2bBaseTemplate, readPreparedState } from './prepared-state.js';\n\n/**\n * Sentinel image ref the cloud-provider hands us when no --image was passed.\n * Mirrors docker's convention; the actual template id is read from the\n * prepared-state file by `provision`.\n */\nexport const DEFAULT_BOX_IMAGE_REF = 'agentbox/box:dev';\n\n/** Box user agentbox standardizes on (matches docker/vercel — created by build-template.sh). */\nconst BOX_USER = 'vscode';\nconst BOX_OWNER = 'vscode:vscode';\n\n/** Default E2B preview hostname. Override via the SDK's `E2B_DOMAIN` env. */\nconst DEFAULT_E2B_DOMAIN = 'e2b.app';\n\n/**\n * Per-box session timeout the SDK enforces at create. Past it, E2B\n * auto-terminates the sandbox. The host keepalive loop renews it while the\n * agent is active via `renewTimeout` (static `Sandbox.setTimeout`), so a\n * long-running session isn't killed mid-work. 45 min default mirrors vercel.\n */\nconst DEFAULT_TIMEOUT_MS = 45 * 60_000;\n\nconst E2B_WEB_PORT = 8080;\n\n/** Single-quote a string for safe embedding inside a `bash -lc '<…>'`. */\nfunction shq(s: string): string {\n return \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n\n/**\n * Convert a Node `Buffer` to a plain `ArrayBuffer` because E2B's `files.write`\n * `data:` field is `string | ArrayBuffer | Blob | ReadableStream` — Buffer is a\n * `Uint8Array` subclass and doesn't satisfy that union at the type level (even\n * though it works at runtime). Copy rather than slice the underlying buffer:\n * Buffers may share an underlying ArrayBuffer with a pooled allocator, so\n * `data.buffer` of a small Buffer can be a megabyte-long shared region.\n */\nfunction bufferToArrayBuffer(b: Buffer): ArrayBuffer {\n const ab = new ArrayBuffer(b.byteLength);\n new Uint8Array(ab).set(b);\n return ab;\n}\n\n/**\n * Map the SDK's nullable string state onto our 4-value `CloudState`.\n * E2B reports 'running' | 'paused' (per SDK types). Anything else (or absent)\n * → 'missing' so callers ping-pong the lifecycle into a clean state.\n */\nfunction mapState(s: SandboxState | undefined): CloudState {\n switch (s) {\n case 'running':\n return 'running';\n case 'paused':\n return 'paused';\n default:\n return 'missing';\n }\n}\n\n/** True when the error means \"sandbox doesn't exist\" (404). */\nfunction isNotFound(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false;\n const name = err instanceof Error ? err.name : '';\n if (name === 'SandboxNotFoundError' || name === 'NotFoundError') return true;\n const status = (err as { statusCode?: unknown; status?: unknown }).statusCode ?? (err as { status?: unknown }).status;\n return status === 404;\n}\n\n/**\n * Sanitize a box name for use as the `metadata.name` value. E2B accepts\n * arbitrary strings (probed) but we strip control chars defensively so a name\n * with embedded newlines can't break log parsing or response shapes.\n */\nfunction safeMetadataName(name: string): string {\n return name.replace(/[\\u0000-\\u001f]/g, '').slice(0, 200);\n}\n\nexport const e2bBackend: CloudBackend = {\n name: 'e2b',\n\n // The cloud scaffold's WebProxy binds whatever port we expose here, and\n // `agentbox url --kind=web` resolves via `getHost(port)`. 8080 matches the\n // non-privileged convention vercel uses — `getHost` accepts any port, but\n // staying on 8080 keeps the in-box ctl flag (AGENTBOX_WEB_PROXY_PORT)\n // identical across cloud providers.\n webProxyPort: E2B_WEB_PORT,\n\n async provision(req: CloudProvisionRequest): Promise<CloudHandle> {\n const apiKey = resolveApiKey();\n const log = req.onLog ?? (() => {});\n // Resolve the template to boot from: an explicit cloud-checkpoint snapshot\n // (req.snapshot) wins, else the prepared base template id. We don't fall\n // back to E2B's stock `base` template — every box must have the agentbox\n // runtime baked in. The gate throws an actionable \"run `agentbox prepare`\"\n // error when no template is recorded yet (mirrors the hetzner/vercel\n // pattern: `prepare` itself sidesteps the gate by calling `prepareE2b`\n // directly, never `provision`).\n if (req.snapshot === undefined) {\n ensureE2bBaseTemplate();\n }\n const template = req.snapshot ?? readPreparedState().base?.templateId;\n if (!template) {\n throw new Error(\n 'e2b provision: no template available — `agentbox prepare --provider e2b` must run first',\n );\n }\n\n // No-retry: Sandbox.create is billable and non-idempotent — a timeout\n // after the request reached the origin could leave a duplicate sandbox we\n // can't reference for cleanup.\n const sb = await withE2bRetry(\n { method: 'provision', retryOnAmbiguous: false, attemptTimeoutMs: 300_000, backoffMs: [] },\n async () =>\n Sandbox.create({\n apiKey,\n template,\n // Friendly name (so prune can see it) + the 'agentbox' marker so\n // `list()` can filter out sandboxes provisioned by other tooling.\n metadata: { agentbox: 'true', 'agentbox.name': safeMetadataName(req.name), name: safeMetadataName(req.name) },\n envs: req.env,\n timeoutMs: req.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n }),\n );\n log(`e2b: created sandbox ${sb.sandboxId} (template ${template})`);\n return { sandboxId: sb.sandboxId };\n },\n\n async get(sandboxId: string): Promise<CloudHandle | null> {\n const apiKey = resolveApiKey();\n return withE2bRetry({ method: 'get', retryOnAmbiguous: true }, async () => {\n try {\n // Static, NON-resuming — won't wake a paused sandbox just to confirm\n // it exists (per orchestrator review #1: connect would auto-resume).\n await Sandbox.getInfo(sandboxId, { apiKey });\n return { sandboxId };\n } catch (err) {\n if (isNotFound(err)) return null;\n throw err;\n }\n });\n },\n\n async list(): Promise<CloudSandboxSummary[]> {\n const apiKey = resolveApiKey();\n return withE2bRetry({ method: 'list', retryOnAmbiguous: true }, async () => {\n const summaries: CloudSandboxSummary[] = [];\n // Default query returns both running and paused sandboxes. We filter\n // client-side to the ones we created (metadata.agentbox === 'true').\n for (const state of ['running', 'paused'] as const) {\n const paginator = Sandbox.list({ apiKey, query: { state: [state] } });\n while (paginator.hasNext) {\n const page = await paginator.nextItems();\n for (const info of page) {\n if (info.metadata?.['agentbox'] !== 'true') continue;\n const friendly =\n info.metadata?.['agentbox.name'] ?? info.metadata?.['name'];\n const summary: CloudSandboxSummary = { sandboxId: info.sandboxId, state };\n if (friendly) summary.name = friendly;\n const startedAt = info.startedAt;\n if (startedAt instanceof Date) summary.createdAt = startedAt.toISOString();\n summaries.push(summary);\n }\n }\n }\n return summaries;\n });\n },\n\n // E2B has no separate stop primitive — sandboxes are either running or\n // paused. start is therefore a connect-and-resume (auto-resume inside\n // Sandbox.connect handles a paused box transparently).\n async start(h: CloudHandle): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry(\n { method: 'start', retryOnAmbiguous: true, attemptTimeoutMs: 120_000 },\n async () => {\n await Sandbox.connect(h.sandboxId, { apiKey });\n },\n );\n },\n\n // stop ≡ pause on E2B (the pause IS the cold-storage state).\n async stop(h: CloudHandle): Promise<void> {\n await this.pause(h);\n },\n\n async pause(h: CloudHandle): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry(\n { method: 'pause', retryOnAmbiguous: true, attemptTimeoutMs: 120_000 },\n async () => {\n await Sandbox.pause(h.sandboxId, { apiKey });\n },\n );\n },\n\n async resume(h: CloudHandle): Promise<void> {\n await this.start(h);\n },\n\n // E2B `setTimeout` SETS the TTL to N ms from now (absolute-from-now), so we\n // ignore the host's tracked deadline and use `target - now`. The static\n // `Sandbox.setTimeout` hits the API without `connect` (no resume of a paused\n // box). The host only calls when target > current, so this never shortens.\n async renewTimeout(h: CloudHandle, targetDeadlineEpochMs: number): Promise<void> {\n const ttlMs = Math.max(0, targetDeadlineEpochMs - Date.now());\n if (ttlMs === 0) return;\n const apiKey = resolveApiKey();\n await withE2bRetry({ method: 'renewTimeout', retryOnAmbiguous: true }, async () => {\n await Sandbox.setTimeout(h.sandboxId, ttlMs, { apiKey });\n });\n },\n\n async destroy(h: CloudHandle): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry(\n { method: 'destroy', retryOnAmbiguous: true, attemptTimeoutMs: 120_000 },\n async () => {\n try {\n await Sandbox.kill(h.sandboxId, { apiKey });\n } catch (err) {\n if (isNotFound(err)) return; // idempotent\n throw err;\n }\n },\n );\n },\n\n async state(h: CloudHandle): Promise<CloudState> {\n const apiKey = resolveApiKey();\n return withE2bRetry({ method: 'state', retryOnAmbiguous: true }, async () => {\n try {\n const info: SandboxInfo = await Sandbox.getInfo(h.sandboxId, { apiKey });\n return mapState(info.state);\n } catch (err) {\n if (isNotFound(err)) return 'missing';\n throw err;\n }\n });\n },\n\n async exec(h: CloudHandle, cmd: string, opts?: CloudExecOptions): Promise<CloudExecResult> {\n const apiKey = resolveApiKey();\n // Default per-attempt cap is 5 min — covers the cloud scaffold's\n // workspace-seed/carry extracts (tar of thousands of files, chown -R).\n // Callers can shorten with opts.attemptTimeoutMs for snappier probes.\n const timeoutMs = opts?.attemptTimeoutMs ?? 300_000;\n return withE2bRetry(\n {\n method: 'exec',\n retryOnAmbiguous: opts?.noRetry ? false : true,\n attemptTimeoutMs: timeoutMs,\n backoffMs: opts?.noRetry ? [] : undefined,\n },\n async () => {\n // Connect for the live handle — auto-resumes a paused box, which is\n // the correct semantics for exec (caller wants the command to run).\n const sb = await Sandbox.connect(h.sandboxId, { apiKey });\n // E2B's `commands.run` accepts only 'root' | 'user' | 'vscode'…; any\n // unix username we create in the fixup is valid. Pass through.\n const user = (opts?.user ?? BOX_USER) as 'root' | 'user';\n try {\n const r = await sb.commands.run(cmd, {\n ...(opts?.cwd !== undefined ? { cwd: opts.cwd } : {}),\n ...(opts?.env !== undefined ? { envs: opts.env } : {}),\n user,\n timeoutMs,\n });\n return { exitCode: r.exitCode, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };\n } catch (err) {\n // commands.run throws on non-zero exit; the CommandResult fields\n // (exitCode/stdout/stderr) hang off the error. Map back into our\n // CloudExecResult so callers see exit=1, not a thrown exception\n // (vercel/daytona/hetzner exec contract returns the result).\n if (err instanceof Error && err.name === 'CommandExitError') {\n const ce = err as unknown as {\n exitCode: number;\n stdout: string;\n stderr: string;\n };\n return { exitCode: ce.exitCode, stdout: ce.stdout ?? '', stderr: ce.stderr ?? '' };\n }\n throw err;\n }\n },\n );\n },\n\n async uploadFile(h: CloudHandle, localPath: string, remotePath: string): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry(\n { method: 'uploadFile', retryOnAmbiguous: true, attemptTimeoutMs: 300_000 },\n async () => {\n const data = await readFile(localPath);\n const sb = await Sandbox.connect(h.sandboxId, { apiKey });\n await sb.files.write([{ path: remotePath, data: bufferToArrayBuffer(data) }]);\n // files.write writes as the default user; chown to vscode so reads\n // from the scaffold's `sudo -u vscode …` exec calls succeed. Best-\n // effort — a chown failure on a world-readable file is harmless.\n try {\n await sb.commands.run(`sudo -n chown ${BOX_OWNER} ${shq(remotePath)}`, {\n user: 'root',\n timeoutMs: 10_000,\n });\n } catch {\n // ignore — file is at least present and readable\n }\n },\n );\n },\n\n async downloadFile(h: CloudHandle, remotePath: string, localPath: string): Promise<void> {\n const apiKey = resolveApiKey();\n await withE2bRetry(\n { method: 'downloadFile', retryOnAmbiguous: true, attemptTimeoutMs: 300_000 },\n async () => {\n const sb = await Sandbox.connect(h.sandboxId, { apiKey });\n const bytes = await sb.files.read(remotePath, { format: 'bytes' });\n const { writeFile } = await import('node:fs/promises');\n await writeFile(localPath, Buffer.from(bytes));\n },\n );\n },\n\n async listFiles(h: CloudHandle, remoteDir: string): Promise<CloudFileEntry[]> {\n const apiKey = resolveApiKey();\n return withE2bRetry({ method: 'listFiles', retryOnAmbiguous: true }, async () => {\n const sb = await Sandbox.connect(h.sandboxId, { apiKey });\n const entries = await sb.files.list(remoteDir);\n return entries.map((e) => ({ name: e.name, isDir: e.type === 'dir' }));\n });\n },\n\n async previewUrl(h: CloudHandle, port: number): Promise<CloudPreviewUrl> {\n // E2B's `sandbox.getHost(port)` is just string interpolation of\n // `${port}-${sandboxId}.${sandboxDomain}` — calling it via Sandbox.connect\n // would auto-resume a paused box (the SDK's documented behavior). The\n // domain defaults to `e2b.app` with `E2B_DOMAIN` as the override (matches\n // the SDK's `ConnectionConfig` default), so we construct the URL locally\n // and never wake the box for a UI/dashboard URL fetch.\n const domain = process.env.E2B_DOMAIN ?? DEFAULT_E2B_DOMAIN;\n return { url: `https://${String(port)}-${h.sandboxId}.${domain}`, token: undefined };\n },\n\n // Fewer params than the interface's (h, port, expiresInSeconds) is fine —\n // E2B preview URLs are already public + browser-usable; no per-URL TTL.\n async signedPreviewUrl(h: CloudHandle, port: number): Promise<CloudPreviewUrl> {\n return this.previewUrl(h, port);\n },\n\n /**\n * Probe whether a snapshot (i.e. a template id) is still bootable. E2B's\n * snapshot ids look like `template-id:tag` or `team-slug/name:tag` — both\n * accepted by `Template.exists(name)`. Returns false on any lookup failure\n * (treated by the cloud-provider as \"gone\" so it falls back to a from-base\n * boot rather than 410ing the user).\n */\n async snapshotExists(snapshotName: string): Promise<boolean> {\n const apiKey = resolveApiKey();\n return withE2bRetry({ method: 'snapshotExists', retryOnAmbiguous: true }, async () => {\n try {\n return await Template.exists(snapshotName, { apiKey });\n } catch {\n return false;\n }\n });\n },\n};\n","/**\n * Bounded retry wrapper for E2B SDK calls — mirrors `withVercelRetry` /\n * `withHetznerRetry` in shape and intent. The E2B API rate-limits (429) and\n * can return transient 5xx during incidents; without bounded retries those\n * propagate as wedges in the calling lifecycle code.\n *\n * Non-idempotent ops (`provision`/`Sandbox.create`) pass `retryOnAmbiguous:\n * false` so a timeout after the request reached the origin doesn't create a\n * duplicate billable sandbox.\n */\n\nexport interface WithRetryOptions {\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 * Retry on errors where we can't be sure the server applied the request\n * (connection failures, per-attempt timeouts, 5xx). Set false for\n * non-idempotent operations where a retry could create a duplicate resource.\n */\n retryOnAmbiguous: boolean;\n /** Override the default 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(`e2b ${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/** HTTP status code dug out of whatever error shape the SDK throws. */\nfunction statusCodeOf(err: unknown): number | undefined {\n if (!err || typeof err !== 'object') return undefined;\n for (const key of ['statusCode', 'status', 'code'] as const) {\n const v = (err as Record<string, unknown>)[key];\n if (typeof v === 'number') return v;\n }\n const resp = (err as { response?: { status?: unknown } }).response;\n if (resp && typeof resp.status === 'number') return resp.status;\n return undefined;\n}\n\nexport function isRetriable(err: unknown, allowAmbiguous: boolean): boolean {\n if (err instanceof AttemptTimeoutError) return allowAmbiguous;\n\n // The SDK exposes a dedicated `SandboxNotFoundError` and `RateLimitError`.\n // Match by error name to avoid an import cycle (sdk.ts → retry → sdk).\n const name = err instanceof Error ? err.name : undefined;\n if (name === 'RateLimitError') return true;\n if (name === 'SandboxNotFoundError') return false;\n\n const status = statusCodeOf(err);\n if (status !== undefined) {\n if (status === 429) return true;\n if (status >= 500 && status <= 599) return allowAmbiguous;\n return false;\n }\n\n // Raw fetch / undici errors. Node wraps low-level errors in `{ cause }`.\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 return false;\n}\n\nexport async function withE2bRetry<T>(opts: WithRetryOptions, fn: () => Promise<T>): 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 `e2b ${opts.method}: attempt ${String(attempt)} failed (${errorSummary(err)}); retrying in ${String(delay)}ms`,\n );\n await sleep(delay);\n }\n }\n throw new Error(`withE2bRetry: exhausted attempts for ${opts.method}`);\n}\n\nfunction defaultRetryLog(line: string): void {\n process.stderr.write(`\\n[e2b-retry] ${line}\\n`);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, 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 Error) {\n const status = statusCodeOf(err);\n return status !== undefined\n ? `${err.name}(${String(status)}): ${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 * `agentbox prepare --provider e2b` — bake the E2B base template.\n *\n * Unlike Vercel/Hetzner, E2B can build templates from a build DSL (the SDK's\n * `Template` + `Template.build`). We mirror Vercel's `prepare` shape but drive\n * the build through the SDK builder API instead of booting a sandbox + running\n * `provision.sh`:\n *\n * 1. Resolve runtime assets + fingerprint the build context. Skip-fast when\n * an up-to-date template id is already recorded.\n * 2. Stage every resolved asset under a temp `fileContextPath` directory\n * with predictable relative names (E2B's `template.copy(src, dest)`\n * requires sources to be RELATIVE paths inside the context dir).\n * 3. `Template({ fileContextPath })` → `.fromBaseImage()` (E2B's default\n * Debian 12 + node 20 + git + sudo). `.copy(rel, dest)` for each asset,\n * `.runCmd('bash /tmp/agentbox-build-template.sh', { user: 'root' })`,\n * `.setReadyCmd('test -x /usr/local/bin/agentbox-ctl')`.\n * 4. `Template.build(t, 'agentbox-base:<tag>', { cpuCount, memoryMB,\n * onBuildLogs })` streams logs into the spinner; returns the BuildInfo\n * with the template id.\n * 5. Persist `{ schema:1, base: { templateId, contextSha256, cliVersion,\n * cliCommit, createdAt } }` to ~/.agentbox/e2b-prepared.json.\n *\n * Templates on E2B are reusable named resources addressed by id+tag. Re-running\n * with the same name reuses the existing template id (E2B's documented\n * behavior). Unlike Vercel snapshots there's no per-box eviction concern; one\n * template is reused for every create.\n *\n * vCPU / RAM are template-level on E2B — set them here so per-box `create`\n * doesn't try to override them (which E2B rejects).\n */\n\nimport { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport type { Provider } from '@agentbox/core';\nimport { computeContextSha256, readCliStamp } from '@agentbox/sandbox-core';\nimport { ensureE2bCredentials } from './credentials.js';\nimport { resolveApiKey, Template } from './sdk.js';\nimport {\n preparedStatePath,\n readPreparedState,\n writePreparedState,\n} from './prepared-state.js';\nimport {\n findStagedCliRuntimeRoot,\n resolveRuntimeAssets,\n type ResolvedAsset,\n} from './runtime-assets.js';\n\nexport interface PrepareE2bOptions {\n name?: string;\n hostWorkspace?: string;\n /** Force re-bake even when an up-to-date template id is recorded. */\n force?: boolean;\n /** vCPUs for the baked template (default 2). E2B applies this per-sandbox at boot. */\n cpuCount?: number;\n /** Memory in MiB for the baked template (default 4096). */\n memoryMB?: number;\n /** CLI runtime tree (set by the CLI to its dist neighbor). */\n cliRuntimeRoot?: string;\n /** Repo root for the dev fallback (defaults to a cwd-walk). */\n repoRoot?: string;\n onLog?: (line: string) => void;\n}\n\nexport interface PrepareE2bResult {\n snapshotName?: string;\n}\n\n/** Template name agentbox bakes under. E2B treats `name:tag` as a single addressable build. */\nconst TEMPLATE_NAME = 'agentbox-base:latest';\nconst DEFAULT_TAG = 'latest';\n\nconst DEFAULT_CPU = 2;\nconst DEFAULT_MEMORY_MB = 4096;\n\nexport async function prepareE2b(\n opts: PrepareE2bOptions = {},\n): Promise<PrepareE2bResult> {\n await ensureE2bCredentials();\n const apiKey = resolveApiKey();\n const log = opts.onLog ?? (() => {});\n const progress = (s: string) => log(`prepare-e2b: ${s}`);\n\n const assets = resolveRuntimeAssets({\n cliRuntimeRoot: opts.cliRuntimeRoot ?? findStagedCliRuntimeRoot(),\n repoRoot: opts.repoRoot,\n });\n const contextSha = await computeContextSha256(\n assets.map((a) => ({ rel: a.name, abs: a.localPath })),\n );\n\n // Skip-fast: existing template + matching fingerprint.\n //\n // Probe the persisted templateId itself, not TEMPLATE_NAME. If someone\n // (or another bake) rebuilt the alias under a different id, the name still\n // resolves but the stored id is stale and `Sandbox.create({ template: <stale id> })`\n // 404s. `Template.exists` accepts both `name:tag` and `template-id:tag`\n // forms, so we pass the exact id we'd later hand to `provision`.\n const existing = readPreparedState();\n if (!opts.force && existing.base) {\n if (existing.base.contextSha256 === contextSha) {\n const stillThere = await templateExists(existing.base.templateId, apiKey);\n if (stillThere) {\n progress(\n `template ${existing.base.templateId} already exists (fingerprint ${contextSha.slice(0, 12)} matches); skipping (pass --force to rebuild)`,\n );\n return { snapshotName: existing.base.templateId };\n }\n progress(`recorded template ${existing.base.templateId} is gone on E2B; rebuilding`);\n } else {\n progress(\n `build context changed (was ${existing.base.contextSha256?.slice(0, 12) ?? '<none>'}, now ${contextSha.slice(0, 12)}); rebuilding`,\n );\n }\n }\n\n // E2B's `template.copy(src, dest)` requires `src` to be a RELATIVE path\n // inside the Template's `fileContextPath`. Stage every resolved asset into\n // a temp dir under its logical name (asset.name) so the copy chain reads\n // from a single context root.\n const contextDir = await mkdtemp(join(tmpdir(), 'agentbox-e2b-build-'));\n try {\n progress(`staging build context at ${contextDir}`);\n await stageAssetsInto(contextDir, assets);\n\n // Build the Template via the SDK builder. fromBaseImage() starts from E2B's\n // own `e2bdev/base` (Debian 12 + node 20 + git + sudo), which halves the\n // install time vs starting from a vanilla Debian image.\n progress('assembling template build (fromBaseImage + asset copy + runCmd)');\n const template = Template({ fileContextPath: contextDir }).fromBaseImage();\n for (const a of assets) {\n progress(` copy ${a.name} -> ${a.remotePath}`);\n template.copy(a.name, a.remotePath, {\n forceUpload: true,\n mode: a.remoteMode,\n user: 'root',\n });\n }\n template.runCmd('bash /tmp/agentbox-build-template.sh 2>&1', { user: 'root' });\n // setReadyCmd flips the builder into TemplateFinal — required for build().\n // The check passes once the script's last `install` step lands the ctl bundle.\n const finalTemplate = template.setReadyCmd(\n 'test -x /usr/local/bin/agentbox-ctl',\n );\n\n const cpuCount = opts.cpuCount ?? DEFAULT_CPU;\n const memoryMB = opts.memoryMB ?? DEFAULT_MEMORY_MB;\n progress(\n `running Template.build('${TEMPLATE_NAME}', { cpuCount: ${String(cpuCount)}, memoryMB: ${String(memoryMB)} })`,\n );\n const info = await Template.build(finalTemplate, TEMPLATE_NAME, {\n apiKey,\n cpuCount,\n memoryMB,\n onBuildLogs: (entry: LogEntryLike) => {\n // LogEntry exposes timestamp / level / message; stream the human form.\n log(`[build] ${formatBuildLog(entry)}`);\n },\n });\n progress(`template built: id=${info.templateId} build=${info.buildId} name=${info.name}`);\n\n // Persist. `Sandbox.create({ template })` auto-appends `:default` when no\n // tag is given (and 404s if that tag wasn't built), so we MUST store the\n // tagged form. `info.templateId` is just the raw id with no tag; use the\n // first tag we built with (`latest`) or fall back to `info.tags[0]`.\n const tag = info.tags?.[0] ?? DEFAULT_TAG;\n const cliStamp = readCliStamp();\n const taggedId = `${info.templateId}:${tag}`;\n writePreparedState({\n schema: 1,\n base: {\n templateId: taggedId,\n // info.name is the full `name:tag` pair Template.build() was called\n // with (e.g. `agentbox-base:latest`). Earlier code re-appended `:${tag}`\n // and produced `agentbox-base:latest:latest` in the status display.\n templateName: info.name,\n contextSha256: contextSha,\n cliVersion: cliStamp.cliVersion,\n cliCommit: cliStamp.cliCommit,\n createdAt: new Date().toISOString(),\n },\n });\n progress(`wrote ${preparedStatePath()}`);\n\n progress(`prepare complete — base template ${taggedId}`);\n return { snapshotName: taggedId };\n } finally {\n await rm(contextDir, { recursive: true, force: true }).catch(() => {\n // best-effort: temp dir cleanup failures are noise, not errors.\n });\n }\n}\n\n/**\n * Copy every asset into `contextDir` under its logical `name`. Preserves the\n * source mode on the copy (E2B's `template.copy` also accepts a `mode`\n * override, but the on-disk mode keeps the local stage representative).\n */\nasync function stageAssetsInto(\n contextDir: string,\n assets: ResolvedAsset[],\n): Promise<void> {\n for (const a of assets) {\n const dest = resolve(contextDir, a.name);\n await mkdir(dirname(dest), { recursive: true });\n await copyFile(a.localPath, dest);\n }\n}\n\n/**\n * Check if a named template is bootable on E2B. Returns true on a 'ready'\n * build, false on anything else (deleted, errored, never built). Used by the\n * skip-fast path to detect a template that was deleted out-of-band.\n */\nasync function templateExists(name: string, apiKey: string): Promise<boolean> {\n try {\n return await Template.exists(name, { apiKey });\n } catch {\n return false;\n }\n}\n\n/**\n * E2B's `LogEntry` shape (timestamp, level, message). We treat the SDK's\n * type loosely here so the line-stream doesn't bind us to internal class\n * shapes — only the `.toString()` plus `.message` are documented.\n */\ninterface LogEntryLike {\n message?: string;\n level?: string;\n timestamp?: Date;\n toString(): string;\n}\n\nfunction formatBuildLog(entry: LogEntryLike): string {\n // The SDK's LogEntry.toString() emits a `[level] timestamp message` form.\n // For the spinner we only want the message — and clip overly long lines.\n const raw = typeof entry.message === 'string' ? entry.message : entry.toString();\n const cleaned = raw.replace(/\\r?\\n+$/, '');\n return cleaned.length > 200 ? cleaned.slice(0, 200) + '…' : cleaned;\n}\n\n/** Provider-level binding used by the CLI's `prepare` command. */\nexport const prepareE2bProvider: NonNullable<Provider['prepare']> = (req) =>\n prepareE2b({\n name: req.name,\n hostWorkspace: req.hostWorkspace ?? process.cwd(),\n force: req.force,\n onLog: req.onLog,\n });\n","/**\n * `buildE2bAttach` — the E2B provider's override of `Provider.buildAttach`.\n *\n * E2B has no SSH and no public PTY CLI like Vercel's `sbx exec -i`. We ship\n * our own attach helper (`attach-helper.cjs`) that connects to the sandbox via\n * the SDK and bridges the host PTY to an in-box `sandbox.pty.create()`.\n *\n * Argv shape:\n * node <attach-helper.cjs> --sandbox-id <id> --user vscode\n *\n * The inner bash command (`renderInnerCommand` output: tmux ensure + attach)\n * is passed through the environment as `AGENTBOX_E2B_INNER_CMD` so quoting\n * stays sane and it doesn't leak through `ps`. `E2B_API_KEY` is passed through\n * the env for the same reason. `node-pty` (the host PTY wrapper) is what\n * spawns this argv, so stdin/stdout/SIGWINCH all reach the helper unchanged.\n */\n\nimport { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n type AttachKind,\n type AttachSpec,\n type BoxRecord,\n type BuildAttachOptions,\n} from '@agentbox/core';\nimport { hostTermForCloud, renderInnerCommand } from '@agentbox/sandbox-cloud';\nimport { resolveApiKey } from './sdk.js';\n\nconst SELF = dirname(fileURLToPath(import.meta.url));\n\n/**\n * Resolve the absolute path to `attach-helper.cjs`. In the published CLI it\n * lives at `runtime/e2b/attach-helper.cjs` (next to the staged provider\n * runtime tree); in dev it lives next to the package's `dist/`.\n */\nexport function resolveAttachHelperPath(): string {\n const candidates = [\n // dev: dist/index.js sibling\n resolve(SELF, 'attach-helper.cjs'),\n // dev: src compiled to dist/, while index.ts is in src/\n resolve(SELF, '..', 'dist', 'attach-helper.cjs'),\n // staged CLI: apps/cli/runtime/e2b/attach-helper.cjs\n resolve(SELF, '..', 'runtime', 'e2b', 'attach-helper.cjs'),\n resolve(SELF, '..', '..', 'runtime', 'e2b', 'attach-helper.cjs'),\n ];\n for (const p of candidates) {\n if (existsSync(p)) return p;\n }\n // Last-resort: still return the first candidate so the error message points\n // somewhere informative.\n return candidates[0]!;\n}\n\nexport async function buildE2bAttach(\n box: BoxRecord,\n kind: AttachKind,\n opts?: BuildAttachOptions,\n): Promise<AttachSpec> {\n const sandboxId = box.cloud?.sandboxId;\n if (!sandboxId) {\n throw new Error(`e2b box ${box.name} has no sandboxId — record is malformed`);\n }\n\n const helper = resolveAttachHelperPath();\n if (!existsSync(helper)) {\n throw new Error(\n `e2b attach helper not found at ${helper} — rebuild the CLI (\\`pnpm -w build\\`) ` +\n 'so packages/sandbox-e2b/dist/attach-helper.cjs is generated.',\n );\n }\n\n const apiKey = resolveApiKey();\n const inner = renderInnerCommand(kind, opts);\n // Forward the host's TERM (the helper has no host env once node-pty spawns\n // it, so pass it explicitly). The helper sets it on the in-box PTY; the\n // renderInnerCommand TERM guard downgrades to xterm-256color when the box's\n // terminfo doesn't carry it (e.g. xterm-ghostty), matching the docker path.\n const hostTerm = hostTermForCloud();\n\n const argv = [\n process.execPath,\n helper,\n '--sandbox-id',\n sandboxId,\n '--user',\n 'vscode',\n ];\n // Detached pre-start (new-tab attach / `-i` queue worker): the inner command\n // only creates the tmux session (no `exec tmux attach`). The helper must run\n // it once and EXIT rather than open a persistent interactive PTY that idles\n // forever — otherwise the host's `runDetached` await never resolves and\n // `agentbox <agent>` hangs after \"box ready\". See attach-helper.ts header.\n if (opts?.detached) argv.push('--detached');\n\n return {\n argv,\n env: {\n E2B_API_KEY: apiKey,\n AGENTBOX_E2B_INNER_CMD: inner,\n AGENTBOX_HOST_TERM: hostTerm,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACgCA,SAAS,g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M;MACnF,cAAc;MACd,aAAa,IAAI;MACjB,eAAe,IAAI;MACnB,cAAc;MACd,iBAAiB,4BAA4B,YAAY;MACzD,YAAYC,aAAa,EAAE;IAC7B,CAAC;AACD,WAAO,EAAE,KAAK,KAAK,KAAK;EAC1B;EACA,MAAM,KAAK,aAAqB;AAC9B,UAAM,UAAU,MAAM,qBAAqB,aAAa,YAAY;AACpE,WAAO,QAAQ,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,EAAE,SAAS,UAAU,EAAE;EAC9E;EACA,MAAM,OAAO,aAAqB,KAAa;AAC7C,UAAM,QAAQ,MAAM,uBAAuB,aAAa,cAAc,GAAG;AACzE,QAAI,CAAC,MAAO;AACZ,QAAI;AACF,YAAM,kBAAkB,MAAM,SAAS,YAAY;IACrD,QAAQ;IAGR;AACA,UAAM,yBAAyB,aAAa,cAAc,GAAG;EAC/D;AACF;AAEO,IAAM,cAAwB;EACnC,GAAG;EACH,SAAS;EACT,aAAa;EACb,YAAY;EACZ,iBAAiB,MAAM,8BAA8B;AACvD;","names":["dirname","resolve","snapshotName","dirname","resolve","readCliStamp"]}
|
|
@@ -15,13 +15,13 @@ import {
|
|
|
15
15
|
} from "./chunk-NXX3KQZ6.js";
|
|
16
16
|
import {
|
|
17
17
|
createCloudProvider
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-3465NDRZ.js";
|
|
19
19
|
import {
|
|
20
20
|
stageAgentsStaticForUpload,
|
|
21
21
|
stageClaudeStaticForUpload,
|
|
22
22
|
stageCodexStaticForUpload,
|
|
23
23
|
stageOpencodeStaticForUpload
|
|
24
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-5N7GA2X7.js";
|
|
25
25
|
import "./chunk-7K2A3NLE.js";
|
|
26
26
|
import "./chunk-G3H2L3O2.js";
|
|
27
27
|
import "./chunk-WJFZJZIM.js";
|
|
@@ -247,4 +247,4 @@ export {
|
|
|
247
247
|
getDaytonaStatus,
|
|
248
248
|
resolveDockerfileContext
|
|
249
249
|
};
|
|
250
|
-
//# sourceMappingURL=dist-
|
|
250
|
+
//# sourceMappingURL=dist-LUEH7MER.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../packages/sandbox-daytona/src/index.ts","../../../packages/sandbox-daytona/src/prepare.ts","../../../packages/sandbox-daytona/src/status.ts"],"sourcesContent":["/**\n * The Daytona Cloud sandbox provider. A thin `CloudBackend` over\n * `@daytonaio/sdk`, composed via `@agentbox/sandbox-cloud`'s `createCloudProvider`\n * for everything provider-agnostic (workspace seeding, ctl launch, state).\n */\n\nimport type { Provider } from '@agentbox/core';\nimport { createCloudProvider } from '@agentbox/sandbox-cloud';\nimport { daytonaBackend, DEFAULT_BOX_IMAGE_REF } from './backend.js';\nimport { prepareDaytona } from './prepare.js';\nimport { currentDaytonaBaseFingerprintLive } from './prepared-state.js';\n\nconst cloudProvider = createCloudProvider(daytonaBackend, {\n defaultResources: { cpu: 2, memory: 4, disk: 8 },\n});\n\nexport const daytonaProvider: Provider = {\n ...cloudProvider,\n prepare: prepareDaytona,\n baseFingerprint: () => currentDaytonaBaseFingerprintLive(),\n};\n\nexport { daytonaBackend, DEFAULT_BOX_IMAGE_REF };\nexport { resolveDockerfileContext, type DockerfileContext } from './dockerfile-context.js';\nexport { ensureDaytonaEnvLoaded } from './env-loader.js';\nexport { currentDaytonaBaseFingerprintLive } from './prepared-state.js';\n// Called by the CLI provider registry to gate first-run interactive setup.\n// Plain async function — no commander surface — so adding it here doesn't\n// pull commander/clack into consumers' type graphs. The full CLI command\n// lives at the `./cli` subpath export.\nexport { ensureDaytonaCredentials } from './credentials.js';\nexport type { EnsureDaytonaCredentialsOptions } from './credentials.js';\nexport {\n getDaytonaStatus,\n type DaytonaStatus,\n type DaytonaSnapshotSummary,\n type DaytonaVolumeSummary,\n} from './status.js';\n","/**\n * Daytona-side implementation of the `Provider.prepare` hook (`agentbox\n * prepare --provider daytona`). One-time, user-triggered:\n *\n * 1. Stage filtered tarballs of the host's `~/.claude`, `~/.codex`, and\n * `~/.local/share/opencode` static config (no auth tokens — those go on\n * the per-org `agentbox-credentials` volume at create time).\n * 2. Build a layered Daytona `Image`: start from `Dockerfile.box`, then\n * `.addLocalFile()` each staged tarball + `.runCommands()` to extract\n * them into the right paths inside the image.\n * 3. Call `daytona.snapshot.create({ name, image }, { onLogs })` — Daytona\n * runs the build server-side, registers the result as an org-scoped\n * named snapshot, and returns when it's `active`.\n *\n * Replaces the old `agentbox daytona publish-snapshot` flow that\n * provisioned a sandbox + ran an in-sandbox bake + called the broken\n * `_experimental_createSnapshot`. The new path never provisions a sandbox.\n *\n * Source of truth for the public API:\n * https://www.daytona.io/docs/en/snapshots/\n */\n\nimport { Image } from '@daytonaio/sdk';\nimport type { PrepareOptions, PrepareResult } from '@agentbox/core';\nimport {\n stageClaudeStaticForUpload,\n stageCodexStaticForUpload,\n stageAgentsStaticForUpload,\n stageOpencodeStaticForUpload,\n type StageResult,\n} from '@agentbox/sandbox-cloud';\nimport { getClient } from './backend.js';\nimport { resolveDaytonaCustomClaudeMd, resolveDockerfileContext } from './dockerfile-context.js';\nimport { ensureDaytonaEnvLoaded } from './env-loader.js';\nimport {\n computeDaytonaContextFingerprint,\n preparedMatches,\n readPreparedDaytonaState,\n writePreparedDaytonaState,\n} from './prepared-state.js';\n\n/**\n * Default snapshot name. Keyed on the first 12 chars of the build-context\n * fingerprint so identical content produces the same snapshot name across\n * machines / CLI runs (idempotent): if the named snapshot already exists\n * on Daytona, prepare can short-circuit without uploading the build\n * context again. Falls back to a timestamp when fingerprinting fails\n * (partial dev rebuild).\n */\nfunction defaultSnapshotName(fingerprint: string | null): string {\n if (fingerprint) return `agentbox-base-${fingerprint.slice(0, 12)}`;\n return `agentbox-base-${Math.floor(Date.now() / 1000).toString()}`;\n}\n\ninterface AgentStage {\n kind: 'claude' | 'codex' | 'opencode' | 'agents';\n /** Path inside the image build that the tarball is uploaded to. */\n remoteTar: string;\n /** Path the image build extracts the tarball into. */\n extractDir: string;\n staged: StageResult;\n}\n\n/**\n * Stage the three agents' static tarballs in parallel. Each `StageResult`'s\n * `cleanup()` must be called by the caller, after the image build picks the\n * file up.\n */\nasync function stageAllAgentStatic(opts: { hostWorkspace?: string }): Promise<AgentStage[]> {\n const [claudeStaged, codexStaged, opencodeStaged, agentsStaged] = await Promise.all([\n stageClaudeStaticForUpload({ hostWorkspace: opts.hostWorkspace }),\n stageCodexStaticForUpload(),\n stageOpencodeStaticForUpload(),\n stageAgentsStaticForUpload(),\n ]);\n return [\n {\n kind: 'claude',\n remoteTar: '/tmp/agentbox-seed-claude.tar.gz',\n extractDir: '/home/vscode/.claude',\n staged: claudeStaged,\n },\n {\n kind: 'codex',\n remoteTar: '/tmp/agentbox-seed-codex.tar.gz',\n extractDir: '/home/vscode/.codex',\n staged: codexStaged,\n },\n {\n kind: 'opencode',\n remoteTar: '/tmp/agentbox-seed-opencode.tar.gz',\n extractDir: '/home/vscode/.local/share/opencode',\n staged: opencodeStaged,\n },\n {\n kind: 'agents',\n remoteTar: '/tmp/agentbox-seed-agents.tar.gz',\n extractDir: '/home/vscode/.agents',\n staged: agentsStaged,\n },\n ];\n}\n\n/**\n * Run `agentbox prepare --provider daytona`. Returns `{ snapshotName }` on\n * success so the CLI can pin it into the project config.\n */\nexport async function prepareDaytona(opts: PrepareOptions): Promise<PrepareResult> {\n ensureDaytonaEnvLoaded();\n const log = opts.onLog ?? (() => {});\n\n // Fingerprint the build context first so we can (a) name the snapshot\n // deterministically and (b) detect cache hits against the recorded\n // prepared state. Computed before staging so an early `null` (partial\n // dev rebuild) doesn't waste a tar staging cycle.\n const fingerprint = await computeDaytonaContextFingerprint();\n const snapshotName =\n opts.name ?? defaultSnapshotName(fingerprint?.contextSha256 ?? null);\n\n const prepared = readPreparedDaytonaState();\n if (\n !opts.force &&\n fingerprint &&\n preparedMatches(prepared, fingerprint.contextSha256)\n ) {\n // Confirm the snapshot still exists on Daytona before short-circuiting.\n // A \"yes locally, no on the server\" mismatch must rebuild.\n try {\n const existing = await getClient().snapshot.get(\n prepared?.base?.imageRef ?? snapshotName,\n );\n if (existing?.name) {\n log(\n `daytona snapshot '${existing.name}' up to date ` +\n `(fingerprint ${fingerprint.contextSha256.slice(0, 12)}) — skipping rebuild ` +\n `(pass --force to override)`,\n );\n return { snapshotName: existing.name };\n }\n log(\n `recorded snapshot '${prepared?.base?.imageRef ?? snapshotName}' not found on Daytona; rebuilding`,\n );\n } catch {\n log(\n `recorded snapshot lookup failed; rebuilding (pass --force to silence)`,\n );\n }\n } else if (!opts.force && fingerprint && prepared?.base?.contextSha256) {\n log(\n `daytona build context changed (was ${prepared.base.contextSha256.slice(0, 12)}, ` +\n `now ${fingerprint.contextSha256.slice(0, 12)}); rebuilding snapshot`,\n );\n }\n\n const ctx = resolveDockerfileContext();\n if (!ctx) {\n throw new Error(\n 'could not locate AgentBox Dockerfile.box build context for the Daytona snapshot. ' +\n 'Set AGENTBOX_DOCKER_CONTEXT to the directory containing Dockerfile.box.',\n );\n }\n\n const daytonaClaudeMd = resolveDaytonaCustomClaudeMd();\n if (!daytonaClaudeMd) {\n throw new Error(\n 'could not locate packages/sandbox-daytona/scripts/custom-system-CLAUDE.md ' +\n '(or its staged runtime/daytona/ copy). Ensure `pnpm -w build` ran so the ' +\n 'CLI staging populated runtime/daytona/.',\n );\n }\n\n const stages = await stageAllAgentStatic({ hostWorkspace: opts.hostWorkspace });\n // Surface staging warnings (codex Keychain landmine, etc.) before the\n // longer build kicks off.\n for (const s of stages) {\n for (const w of s.staged.warnings) log(w);\n }\n\n try {\n // git-lfs (binary + `git lfs install --system`) is inherited for free from\n // Dockerfile.box, so an in-box checkout of an LFS repo smudges real content.\n // No daytona-specific overlay step is needed; the host-side object seeding\n // lives in sandbox-cloud's workspace-seed (seedCloneLfsObjects).\n let image: Image = Image.fromDockerfile(ctx.dockerfile);\n\n // Overlay the daytona-specific /etc/claude-code/CLAUDE.md on top of the\n // docker-shaped one baked by Dockerfile.box. Daytona boxes have no host\n // .git/ bind-mount, so the in-box hint needs daytona-specific git wording.\n image = image.addLocalFile(daytonaClaudeMd, '/tmp/agentbox-custom-CLAUDE.md');\n const extractCmds: string[] = [\n 'install -m 0644 /tmp/agentbox-custom-CLAUDE.md /etc/claude-code/CLAUDE.md',\n 'rm -f /tmp/agentbox-custom-CLAUDE.md',\n ];\n\n // For each agent whose stage produced a tarball, add the file to the\n // image build context and append a single tar-extract + chown.\n const usable = stages.filter((s) => s.staged.tarballPath !== null);\n for (const s of usable) {\n image = image.addLocalFile(s.staged.tarballPath as string, s.remoteTar);\n extractCmds.push(`mkdir -p ${s.extractDir}`);\n extractCmds.push(`tar -xzf ${s.remoteTar} -C ${s.extractDir}`);\n }\n if (usable.length > 0) {\n // One final pass: own the extracted trees as the box user, then drop the\n // staging tarballs (no point shipping them twice in the image layer).\n extractCmds.push(\n 'chown -R vscode:vscode /home/vscode/.claude /home/vscode/.codex /home/vscode/.local',\n );\n // ~/.agents is only present when the host had one (skills dir); guard it.\n extractCmds.push(\n '[ -d /home/vscode/.agents ] && chown -R vscode:vscode /home/vscode/.agents || true',\n );\n extractCmds.push('rm -f /tmp/agentbox-seed-*.tar.gz');\n }\n // Dockerfile.box ends with `USER vscode`. Switch to root for the\n // install/tar/chown/rm pass — COPYed files are root-owned in /tmp (sticky\n // bit), chown -R on /home/vscode/.* only works as root, and\n // /etc/claude-code is root-owned. Switch back to vscode so the image\n // keeps its default-user invariant.\n image = image\n .dockerfileCommands(['USER root'])\n .runCommands(...extractCmds)\n .dockerfileCommands(['USER vscode']);\n\n const client = getClient();\n log(`creating Daytona snapshot '${snapshotName}'…`);\n const snapshot = await client.snapshot.create(\n { name: snapshotName, image },\n {\n onLogs: (chunk: string) => log(String(chunk).split('\\n').filter(Boolean).join(' ')),\n },\n );\n log(`snapshot '${snapshot.name}' is ${snapshot.state ?? 'created'}`);\n if (fingerprint) {\n writePreparedDaytonaState({\n snapshotName: snapshot.name ?? snapshotName,\n contextSha256: fingerprint.contextSha256,\n });\n log(\n `recorded daytona-prepared.json (fingerprint ${fingerprint.contextSha256.slice(0, 12)})`,\n );\n }\n return { snapshotName: snapshot.name ?? snapshotName };\n } finally {\n await Promise.all(stages.map((s) => s.staged.cleanup()));\n }\n}\n","/**\n * Read-only status helpers for `agentbox prepare` (no-args mode). Surfaces\n * the user-facing inventory of agentbox-owned base images / snapshots /\n * volumes on the configured Daytona org so the user can see at a glance\n * what's already prepared and what isn't.\n *\n * Daytona-side state lives in two places:\n * - **Snapshots** — built by `agentbox prepare --provider daytona`. Listed\n * filtered to `agentbox*` so we don't surface unrelated org snapshots.\n * - **Volumes** — the per-org `agentbox-credentials` volume created lazily\n * by `ensureAgentVolumesForCloud` on first `agentbox create --provider\n * daytona`.\n *\n * All calls swallow auth/network errors and return an empty section — the\n * status command must work for users who don't have Daytona configured.\n */\n\nimport { ensureDaytonaEnvLoaded } from './env-loader.js';\nimport { getClient } from './backend.js';\n\nexport interface DaytonaSnapshotSummary {\n name: string;\n state?: string;\n /** Snapshot size in GB, as reported by Daytona (may be undefined for non-`active` states). */\n sizeGb?: number;\n createdAt?: string;\n errorReason?: string;\n}\n\nexport interface DaytonaVolumeSummary {\n name: string;\n id: string;\n state?: string;\n createdAt?: string;\n lastUsedAt?: string;\n}\n\nexport interface DaytonaStatus {\n /** True when Daytona credentials are present + the SDK could connect. */\n configured: boolean;\n /** Snapshots whose name starts with `agentbox` (case-insensitive). */\n snapshots: DaytonaSnapshotSummary[];\n /** Volumes whose name starts with `agentbox` (case-insensitive). */\n volumes: DaytonaVolumeSummary[];\n /** Non-fatal explanation when `configured` is false. */\n reason?: string;\n}\n\nfunction isAgentboxName(name: unknown): boolean {\n return typeof name === 'string' && name.toLowerCase().startsWith('agentbox');\n}\n\n/**\n * Collect a read-only summary of agentbox-owned snapshots + volumes on the\n * Daytona org. Never throws — failure paths return `configured: false` with\n * a one-line reason.\n */\nexport async function getDaytonaStatus(): Promise<DaytonaStatus> {\n try {\n ensureDaytonaEnvLoaded();\n } catch (err) {\n return {\n configured: false,\n snapshots: [],\n volumes: [],\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n\n let client;\n try {\n client = getClient();\n } catch (err) {\n return {\n configured: false,\n snapshots: [],\n volumes: [],\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n\n const snapshots: DaytonaSnapshotSummary[] = [];\n const volumes: DaytonaVolumeSummary[] = [];\n let reason: string | undefined;\n\n try {\n const list = await client.snapshot.list();\n const items = (list as { items?: unknown[] }).items ?? (Array.isArray(list) ? list : []);\n for (const s of items) {\n const dto = s as { name?: unknown; state?: unknown; size?: unknown; createdAt?: unknown; errorReason?: unknown };\n if (!isAgentboxName(dto.name)) continue;\n snapshots.push({\n name: dto.name as string,\n state: typeof dto.state === 'string' ? dto.state : undefined,\n sizeGb: typeof dto.size === 'number' ? dto.size : undefined,\n createdAt: typeof dto.createdAt === 'string' ? dto.createdAt : undefined,\n errorReason: typeof dto.errorReason === 'string' ? dto.errorReason : undefined,\n });\n }\n } catch (err) {\n reason = `snapshot list failed: ${err instanceof Error ? err.message.split('\\n')[0] : String(err)}`;\n }\n\n try {\n const list = await client.volume.list();\n const items: unknown[] = Array.isArray(list)\n ? list\n : ((list as { items?: unknown[] }).items ?? []);\n for (const v of items) {\n const dto = v as { name?: unknown; id?: unknown; state?: unknown; createdAt?: unknown; lastUsedAt?: unknown };\n if (!isAgentboxName(dto.name)) continue;\n volumes.push({\n name: dto.name as string,\n id: typeof dto.id === 'string' ? dto.id : '',\n state: typeof dto.state === 'string' ? dto.state : undefined,\n createdAt: typeof dto.createdAt === 'string' ? dto.createdAt : undefined,\n lastUsedAt: typeof dto.lastUsedAt === 'string' ? dto.lastUsedAt : undefined,\n });\n }\n } catch (err) {\n const msg = `volume list failed: ${err instanceof Error ? err.message.split('\\n')[0] : String(err)}`;\n reason = reason ? `${reason}; ${msg}` : msg;\n }\n\n return {\n configured: true,\n snapshots: snapshots.sort((a, b) => (b.createdAt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AQ,KAAK,CAAC,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;IAC5D;EACF;AACF;AFtHA,IAAM,gBAAgB,oBAAoB,gBAAgB;EACxD,kBAAkB,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,EAAE;AACjD,CAAC;AAEM,IAAM,kBAA4B;EACvC,GAAG;EACH,SAAS;EACT,iBAAiB,MAAM,kCAAkC;AAC3D;","names":[]}
|
|
@@ -29,13 +29,13 @@ import {
|
|
|
29
29
|
} from "./chunk-P6UT5XGE.js";
|
|
30
30
|
import {
|
|
31
31
|
createCloudProvider
|
|
32
|
-
} from "./chunk-
|
|
32
|
+
} from "./chunk-3465NDRZ.js";
|
|
33
33
|
import {
|
|
34
34
|
stageAgentsStaticForUpload,
|
|
35
35
|
stageClaudeStaticForUpload,
|
|
36
36
|
stageCodexStaticForUpload,
|
|
37
37
|
stageOpencodeStaticForUpload
|
|
38
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-5N7GA2X7.js";
|
|
39
39
|
import {
|
|
40
40
|
UserFacingError,
|
|
41
41
|
computeContextSha256,
|
|
@@ -1234,4 +1234,4 @@ export {
|
|
|
1234
1234
|
withHetznerRetry,
|
|
1235
1235
|
writePreparedState
|
|
1236
1236
|
};
|
|
1237
|
-
//# sourceMappingURL=dist-
|
|
1237
|
+
//# sourceMappingURL=dist-T3JIYHCA.js.map
|
package/dist/index.js
CHANGED
|
@@ -38,7 +38,7 @@ import {
|
|
|
38
38
|
stripTitleGlyph,
|
|
39
39
|
subscribePrompts,
|
|
40
40
|
uploadImageFileToBox
|
|
41
|
-
} from "./chunk-
|
|
41
|
+
} from "./chunk-4ATVA3RM.js";
|
|
42
42
|
import {
|
|
43
43
|
daytonaBackend,
|
|
44
44
|
ensureDaytonaCredentials,
|
|
@@ -83,7 +83,7 @@ import {
|
|
|
83
83
|
probeCloudCheckpoint,
|
|
84
84
|
resolveCloudCheckpoint,
|
|
85
85
|
seedAgentVolumesIfFresh
|
|
86
|
-
} from "./chunk-
|
|
86
|
+
} from "./chunk-3465NDRZ.js";
|
|
87
87
|
import {
|
|
88
88
|
ALL_CONNECTORS,
|
|
89
89
|
BOX_STATUS_EVENT,
|
|
@@ -240,7 +240,7 @@ import {
|
|
|
240
240
|
waitForTmuxPaneContent,
|
|
241
241
|
warmUpClaudeCredentials,
|
|
242
242
|
writeJob
|
|
243
|
-
} from "./chunk-
|
|
243
|
+
} from "./chunk-5N7GA2X7.js";
|
|
244
244
|
import {
|
|
245
245
|
AmbiguousBoxError,
|
|
246
246
|
BoxNotFoundError,
|
|
@@ -266,8 +266,8 @@ import {
|
|
|
266
266
|
} from "./chunk-WJFZJZIM.js";
|
|
267
267
|
|
|
268
268
|
// src/version.ts
|
|
269
|
-
var AGENTBOX_VERSION = true ? "0.20.
|
|
270
|
-
var AGENTBOX_COMMIT = true ? "
|
|
269
|
+
var AGENTBOX_VERSION = true ? "0.20.1" : "0.0.0-dev";
|
|
270
|
+
var AGENTBOX_COMMIT = true ? "5c78d7dfd" : "dev";
|
|
271
271
|
|
|
272
272
|
// src/index.ts
|
|
273
273
|
import { Command as Command52 } from "commander";
|
|
@@ -2779,13 +2779,13 @@ import { basename as basename2 } from "path";
|
|
|
2779
2779
|
async function cloudBackendForProvider(provider) {
|
|
2780
2780
|
switch (provider) {
|
|
2781
2781
|
case "daytona":
|
|
2782
|
-
return (await import("./dist-
|
|
2782
|
+
return (await import("./dist-LUEH7MER.js")).daytonaBackend;
|
|
2783
2783
|
case "hetzner":
|
|
2784
|
-
return (await import("./dist-
|
|
2784
|
+
return (await import("./dist-T3JIYHCA.js")).hetznerBackend;
|
|
2785
2785
|
case "vercel":
|
|
2786
|
-
return (await import("./dist-
|
|
2786
|
+
return (await import("./dist-CTTTHG6U.js")).vercelBackend;
|
|
2787
2787
|
case "e2b":
|
|
2788
|
-
return (await import("./dist-
|
|
2788
|
+
return (await import("./dist-G5PDFWKH.js")).e2bBackend;
|
|
2789
2789
|
default:
|
|
2790
2790
|
return null;
|
|
2791
2791
|
}
|
|
@@ -2793,13 +2793,13 @@ async function cloudBackendForProvider(provider) {
|
|
|
2793
2793
|
async function currentCloudBaseFingerprintLive(provider) {
|
|
2794
2794
|
switch (provider) {
|
|
2795
2795
|
case "daytona":
|
|
2796
|
-
return (await import("./dist-
|
|
2796
|
+
return (await import("./dist-LUEH7MER.js")).currentDaytonaBaseFingerprintLive();
|
|
2797
2797
|
case "hetzner":
|
|
2798
|
-
return (await import("./dist-
|
|
2798
|
+
return (await import("./dist-T3JIYHCA.js")).currentHetznerBaseFingerprintLive();
|
|
2799
2799
|
case "vercel":
|
|
2800
|
-
return (await import("./dist-
|
|
2800
|
+
return (await import("./dist-CTTTHG6U.js")).currentVercelBaseFingerprintLive();
|
|
2801
2801
|
case "e2b":
|
|
2802
|
-
return (await import("./dist-
|
|
2802
|
+
return (await import("./dist-G5PDFWKH.js")).currentE2bBaseFingerprintLive();
|
|
2803
2803
|
default:
|
|
2804
2804
|
return void 0;
|
|
2805
2805
|
}
|
|
@@ -3138,7 +3138,7 @@ async function renderDocker(status) {
|
|
|
3138
3138
|
}
|
|
3139
3139
|
async function daytonaStatus() {
|
|
3140
3140
|
try {
|
|
3141
|
-
const mod = await import("./dist-
|
|
3141
|
+
const mod = await import("./dist-LUEH7MER.js");
|
|
3142
3142
|
return await mod.getDaytonaStatus();
|
|
3143
3143
|
} catch (err) {
|
|
3144
3144
|
return {
|
|
@@ -3149,7 +3149,7 @@ async function daytonaStatus() {
|
|
|
3149
3149
|
}
|
|
3150
3150
|
async function e2bStatus() {
|
|
3151
3151
|
try {
|
|
3152
|
-
const mod = await import("./dist-
|
|
3152
|
+
const mod = await import("./dist-G5PDFWKH.js");
|
|
3153
3153
|
const cred = mod.readE2bCredStatus();
|
|
3154
3154
|
if (cred.auth === "none") {
|
|
3155
3155
|
return { configured: false, reason: "not configured \u2014 run `agentbox e2b login`" };
|
|
@@ -6154,13 +6154,13 @@ var CLOUD_BACKENDS = ["daytona", "hetzner", "vercel", "e2b"];
|
|
|
6154
6154
|
async function cloudProviderFor(backend) {
|
|
6155
6155
|
switch (backend) {
|
|
6156
6156
|
case "daytona":
|
|
6157
|
-
return (await import("./dist-
|
|
6157
|
+
return (await import("./dist-LUEH7MER.js")).daytonaProvider;
|
|
6158
6158
|
case "hetzner":
|
|
6159
|
-
return (await import("./dist-
|
|
6159
|
+
return (await import("./dist-T3JIYHCA.js")).hetznerProvider;
|
|
6160
6160
|
case "vercel":
|
|
6161
|
-
return (await import("./dist-
|
|
6161
|
+
return (await import("./dist-CTTTHG6U.js")).vercelProvider;
|
|
6162
6162
|
case "e2b":
|
|
6163
|
-
return (await import("./dist-
|
|
6163
|
+
return (await import("./dist-G5PDFWKH.js")).e2bProvider;
|
|
6164
6164
|
}
|
|
6165
6165
|
}
|
|
6166
6166
|
var CHECKPOINT_NOTICE = "Checkpoint in progress \u2014 the box will be unresponsive for a moment";
|
|
@@ -7587,7 +7587,7 @@ var createCommand = new Command11("create").description(
|
|
|
7587
7587
|
}
|
|
7588
7588
|
outro5("done");
|
|
7589
7589
|
if (attachClaudeAfter) {
|
|
7590
|
-
const { cloudAgentAttach: cloudAgentAttach2 } = await import("./_cloud-attach-
|
|
7590
|
+
const { cloudAgentAttach: cloudAgentAttach2 } = await import("./_cloud-attach-MH7NKIZY.js");
|
|
7591
7591
|
await cloudAgentAttach2({
|
|
7592
7592
|
box: result.record,
|
|
7593
7593
|
binary: "claude",
|
|
@@ -11068,7 +11068,7 @@ async function dockerChecks() {
|
|
|
11068
11068
|
];
|
|
11069
11069
|
}
|
|
11070
11070
|
const daemonRes = { label: "docker daemon", status: "ok", detail: "reachable" };
|
|
11071
|
-
const mod = await import("./dist-
|
|
11071
|
+
const mod = await import("./dist-AJWL4WLW.js");
|
|
11072
11072
|
let imgRes;
|
|
11073
11073
|
try {
|
|
11074
11074
|
const img = await mod.imageInfo(mod.DEFAULT_BOX_IMAGE);
|
|
@@ -11099,7 +11099,7 @@ async function dockerChecks() {
|
|
|
11099
11099
|
}
|
|
11100
11100
|
async function daytonaChecks() {
|
|
11101
11101
|
try {
|
|
11102
|
-
const mod = await import("./dist-
|
|
11102
|
+
const mod = await import("./dist-LUEH7MER.js");
|
|
11103
11103
|
const status = await mod.getDaytonaStatus();
|
|
11104
11104
|
if (!status.configured) {
|
|
11105
11105
|
return [
|
|
@@ -11135,7 +11135,7 @@ async function daytonaChecks() {
|
|
|
11135
11135
|
}
|
|
11136
11136
|
async function hetznerChecks() {
|
|
11137
11137
|
try {
|
|
11138
|
-
const mod = await import("./dist-
|
|
11138
|
+
const mod = await import("./dist-T3JIYHCA.js");
|
|
11139
11139
|
const cred = mod.readHetznerCredStatus();
|
|
11140
11140
|
const credRes = cred.source === "none" ? {
|
|
11141
11141
|
label: "credentials",
|
|
@@ -11167,7 +11167,7 @@ async function hetznerChecks() {
|
|
|
11167
11167
|
}
|
|
11168
11168
|
async function vercelChecks() {
|
|
11169
11169
|
try {
|
|
11170
|
-
const mod = await import("./dist-
|
|
11170
|
+
const mod = await import("./dist-CTTTHG6U.js");
|
|
11171
11171
|
const cred = mod.readVercelCredStatus();
|
|
11172
11172
|
const credRes = cred.auth === "none" ? {
|
|
11173
11173
|
label: "credentials",
|
|
@@ -11203,7 +11203,7 @@ async function vercelChecks() {
|
|
|
11203
11203
|
}
|
|
11204
11204
|
async function e2bChecks() {
|
|
11205
11205
|
try {
|
|
11206
|
-
const mod = await import("./dist-
|
|
11206
|
+
const mod = await import("./dist-G5PDFWKH.js");
|
|
11207
11207
|
const cred = mod.readE2bCredStatus();
|
|
11208
11208
|
const credRes = cred.auth === "none" ? {
|
|
11209
11209
|
label: "credentials",
|
|
@@ -12083,7 +12083,7 @@ function ensureTty() {
|
|
|
12083
12083
|
async function runProviderLogin(name) {
|
|
12084
12084
|
if (name === "docker") return true;
|
|
12085
12085
|
if (name === "daytona") {
|
|
12086
|
-
const mod2 = await import("./dist-
|
|
12086
|
+
const mod2 = await import("./dist-LUEH7MER.js");
|
|
12087
12087
|
const status2 = await mod2.getDaytonaStatus();
|
|
12088
12088
|
if (status2.configured) {
|
|
12089
12089
|
prompt_exports.log.info("daytona: already configured");
|
|
@@ -12095,7 +12095,7 @@ async function runProviderLogin(name) {
|
|
|
12095
12095
|
return true;
|
|
12096
12096
|
}
|
|
12097
12097
|
if (name === "hetzner") {
|
|
12098
|
-
const mod2 = await import("./dist-
|
|
12098
|
+
const mod2 = await import("./dist-T3JIYHCA.js");
|
|
12099
12099
|
const status2 = mod2.readHetznerCredStatus();
|
|
12100
12100
|
if (status2.source !== "none") {
|
|
12101
12101
|
prompt_exports.log.info("hetzner: already configured");
|
|
@@ -12107,7 +12107,7 @@ async function runProviderLogin(name) {
|
|
|
12107
12107
|
return true;
|
|
12108
12108
|
}
|
|
12109
12109
|
if (name === "vercel") {
|
|
12110
|
-
const mod2 = await import("./dist-
|
|
12110
|
+
const mod2 = await import("./dist-CTTTHG6U.js");
|
|
12111
12111
|
const status2 = mod2.readVercelCredStatus();
|
|
12112
12112
|
if (status2.auth !== "none") {
|
|
12113
12113
|
prompt_exports.log.info(`vercel: already configured (${status2.auth})`);
|
|
@@ -12118,7 +12118,7 @@ async function runProviderLogin(name) {
|
|
|
12118
12118
|
await mod2.ensureVercelCredentials();
|
|
12119
12119
|
return true;
|
|
12120
12120
|
}
|
|
12121
|
-
const mod = await import("./dist-
|
|
12121
|
+
const mod = await import("./dist-G5PDFWKH.js");
|
|
12122
12122
|
const status = mod.readE2bCredStatus();
|
|
12123
12123
|
if (status.auth !== "none") {
|
|
12124
12124
|
prompt_exports.log.info(`e2b: already configured (${status.auth})`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@madarco/agentbox",
|
|
3
|
-
"version": "0.20.
|
|
3
|
+
"version": "0.20.1",
|
|
4
4
|
"description": "Launch Claude Code, Codex, and other coding agents in isolated sandboxes",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Marco D'Alia",
|
|
@@ -59,18 +59,18 @@
|
|
|
59
59
|
"tsup": "^8.3.5",
|
|
60
60
|
"typescript": "^5.7.2",
|
|
61
61
|
"vitest": "^2.1.8",
|
|
62
|
-
"@agentbox/config": "0.0.0",
|
|
63
62
|
"@agentbox/core": "0.0.0",
|
|
63
|
+
"@agentbox/config": "0.0.0",
|
|
64
64
|
"@agentbox/ctl": "0.0.0",
|
|
65
|
-
"@agentbox/integrations": "0.0.0",
|
|
66
65
|
"@agentbox/relay": "0.0.0",
|
|
67
66
|
"@agentbox/sandbox-cloud": "0.0.0",
|
|
67
|
+
"@agentbox/integrations": "0.0.0",
|
|
68
68
|
"@agentbox/sandbox-core": "0.0.0",
|
|
69
69
|
"@agentbox/sandbox-daytona": "0.0.0",
|
|
70
70
|
"@agentbox/sandbox-docker": "0.0.0",
|
|
71
71
|
"@agentbox/sandbox-e2b": "0.0.0",
|
|
72
|
-
"@agentbox/sandbox-
|
|
73
|
-
"@agentbox/sandbox-
|
|
72
|
+
"@agentbox/sandbox-vercel": "0.0.0",
|
|
73
|
+
"@agentbox/sandbox-hetzner": "0.0.0"
|
|
74
74
|
},
|
|
75
75
|
"scripts": {
|
|
76
76
|
"build": "tsup",
|