diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c3ffab..81baa08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,31 @@ This file records user-visible changes to the BoxCompute CLI. GitHub Releases use the same notes and bind them to the exact source commit. +## [0.11.0] - 2026-10-18 + +Stop a running VM with `bxc sandbox stop SANDBOX_ID`. + +### CLI users + +- `bxc sandbox stop SANDBOX_ID` stops a running VM's compute billing now and + keeps its disk and files; `bxc sandbox resume` starts it again. It reports + whether the VM was running (`stopped` in `--json`), never wakes a stopped VM + and is safe to repeat. HTTP 409 means it is still starting, stopping or in + use: run it again in a moment. +- Help, the README, the VM guide and the bundled skill now say that a VM also + stops by itself 30 minutes after its last resume, exec, file transfer or + preview, and that status, logs, analytics, costs and work inside the VM do + not count. They previously said an idle VM billed until deleted. +- Requires BoxCompute server 0.62.0 (`POST /api/v2/sandboxes/{id}/stop`). An + older server reports that stopping is not supported. Update with + `bxc update` or `npm install --global @boxcompute/cli@latest` after rollout. + +### Security + +- Uses the saved credential with the same HTTPS/loopback origin check, refused + redirects and bounded response reading as `sandbox resume`. The endpoint + needs the API key's `sandbox:create` scope, like resume. + ## [0.10.0] - 2026-10-10 Read remaining credits and wallet history without opening the web app. diff --git a/README.md b/README.md index 14afb83..1220c98 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,8 @@ bxc --json sandbox start WORKSPACE_ID --vm --idempotency-key SAVED_UNIQUE_KEY -- bxc --json sandbox status SANDBOX_ID # Resume the same stopped sandbox, retaining its disk and files. bxc --json sandbox resume SANDBOX_ID +# Stop a running VM now; its disk and files stay for the next resume. +bxc --json sandbox stop SANDBOX_ID # Container sandbox instead (supports --cpu); explicit gVisor opt-out. bxc sandbox start WORKSPACE_ID --gvisor --cpu 2 bxc sandbox upload SANDBOX_ID fixture.txt /workspace/fixture.txt @@ -88,15 +90,23 @@ walkthroughs, retry recovery, and Hermes limitations. VMs default to the profile (1.5 CPU, 3072 MiB memory). Both use a 30 GiB thin-provisioned workspace. Sizing is VM only: the gVisor runtime ignores `small` and rejects `large`. VMs have outbound Internet -access by default, no automatic lifetime expiry, and no SSH access; delete them -when done because active VMs keep billing. Uploads are limited to 8 MiB; -downloads read to EOF and refuse to overwrite local files. +access by default, no automatic lifetime expiry, and no SSH access. A running +VM bills until it stops: stop it when done if you will reuse it, or delete it +when its files are no longer needed. Uploads are limited to 8 MiB; downloads +read to EOF and refuse to overwrite local files. `sandbox resume` starts an existing sandbox and resumes compute billing. It keeps its ID, disk and files. Add `--no-wait` to return the start receipt, or `--idempotency-key KEY` to retain a retry key. Inspect status after an uncertain response; the CLI never automatically retries or creates a replacement VM. +`sandbox stop` (server 0.62.0+) stops a running VM now and keeps its disk and +files; `stopped: false` means it was not running. It never wakes a stopped VM +and is safe to repeat; on HTTP 409 the VM is still starting, stopping or in +use, so try again in a moment. Without it, a VM stops by itself 30 minutes +after its last resume, exec, upload, download or preview. Status, logs, +analytics, costs and processes running inside the VM do not count as activity. + ### Expose VM services To reach a TCP service running inside a network-enabled VM, keep a foreground diff --git a/docs/vm-sandbox-beta.md b/docs/vm-sandbox-beta.md index a212dfa..7dfa4f2 100644 --- a/docs/vm-sandbox-beta.md +++ b/docs/vm-sandbox-beta.md @@ -6,7 +6,7 @@ bounded integration tests for command-line tools and agent tool execution. **Access:** any authenticated BoxCompute account can create VM sandboxes; no separate approval is required. This profile is not intended for production -workloads or always-on services, and active VMs bill until you delete them. +workloads or always-on services, and running VMs bill until they stop. **CLI support:** CLI 0.4.0 or newer creates VMs by default — `bxc sandbox start` omits the runtime selector and waits up to 180 seconds for `running` — plus @@ -32,13 +32,13 @@ sizing (`size`) added September 17, 2026. | Availability | Any authenticated account. No separate VM approval. | | Selection | Omitted `vmSandbox` selects the VM runtime (the default); `vmSandbox: false` explicitly selects a gVisor container sandbox. Rejected VM requests do not fall back to that path. | | Resources | Sizing is chosen at create with `size`. `small` (default) is 500m CPU (0.5 CPU), 1,024 MiB RAM; `large` is 1,536m CPU (1.5 CPU), 3,072 MiB RAM. Both get a 30 GiB thin-provisioned workspace. | -| Lifetime | No automatic expiry. The VM exists, and bills for active use, until you delete it. | +| Lifetime | No automatic expiry. The VM exists until you delete it and bills while it runs. A running VM stops, keeping its files, when you call stop or 30 minutes after its last start, execute, file call or preview request; reads, logs, operation polling and work inside the VM do not count. | | Image | Immutable, server-selected approved minimal Ubuntu image. No arbitrary image override, library profile, or attached volumes. | | User/runtime | Unprivileged user; `HOME=/workspace`. No sudo/root installation or SSH login. Check that your required executables are available; Node.js, uv and your tool's dependencies are not guaranteed. | | Networking | Outbound Internet access by default; request `blockNetwork: true` at create for a VM with no NIC. No inbound exposure either way. | | Serving | No supported public inbound port, SSH endpoint, application tunnel, or webhook URL. Binding a guest port does not publish it. | | Storage | `/workspace` is storage for this VM. Download needed data before deleting it. An account workspace groups sandboxes; it does not preserve their files. | -| Lifecycle | Create, status, execute, files, delete. Do not depend on sleep/resume, snapshots, checkpoints, forks, or restore for this VM profile. | +| Lifecycle | Create, status, execute, files, stop, resume, delete. Do not depend on snapshots, checkpoints, forks, or restore for this VM profile. | Start with a small payload and one command at a time. A full toolchain, browser, model or concurrent agent workload may exceed the available resources. @@ -358,8 +358,11 @@ not make a live database backup consistent. ### 5. Export early; delete explicitly -Download your results before deleting the VM. VMs have no automatic expiry, -so an idle VM keeps billing until you delete it. When an +Download your results before deleting the VM. VMs have no automatic expiry. +A running VM bills until it stops: `bxc sandbox stop SANDBOX_ID` (or +`POST /api/v2/sandboxes/{id}/stop` with `{}`) stops it now and keeps its files, +and otherwise it stops 30 idle minutes after its last start, execute, file call +or preview request. When an execute or file request detects that the VM has expired, it returns `503 SANDBOX_UNAVAILABLE` and the sandbox is marked `expired`. Using that sandbox ID again does not automatically create a replacement VM. diff --git a/package.json b/package.json index cd9413f..cb38370 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@boxcompute/cli", - "version": "0.10.0", + "version": "0.11.0", "description": "Connect local AI agents to BoxCompute sandboxes", "keywords": [ "boxcompute", diff --git a/skills/boxcompute-sandbox/SKILL.md b/skills/boxcompute-sandbox/SKILL.md index 3530507..f97ccd0 100644 --- a/skills/boxcompute-sandbox/SKILL.md +++ b/skills/boxcompute-sandbox/SKILL.md @@ -39,14 +39,23 @@ returns the receipt. An optional `--idempotency-key KEY` is reusable for the same resume request. Inspect status after an uncertain response; never create a replacement as a resume fallback. Do not wake compute for read-only status. +With CLI 0.11.0+, run `bxc --json sandbox stop SANDBOX_ID` when you are done +with a VM you will use again: it stops compute billing now and keeps the disk +and files, and `stopped: false` means it was not running. It never wakes a +stopped VM and is safe to repeat; on HTTP 409 (still starting, stopping or in +use) wait a moment and run it again. Without it, a VM stops by itself 30 +minutes after its last resume, exec, upload, download or preview; status, +logs, analytics, costs and processes running inside the VM do not count. + VMs are sized at create with `--size small|large` (default `small`): small is 0.5 CPU / 1024 MiB RAM and large is 1.5 CPU / 3072 MiB RAM, both with a 30 GiB workspace. Sizing is VM only: gVisor ignores `small` and rejects `large`, and VM sizing is mutually exclusive with `--cpu`. Use `--size large` only when the task needs more than the default profile; it bills more. VMs have outbound -Internet access by default, no SSH, and no automatic lifetime expiry — delete -the VM when finished because active VMs keep billing. Execution does not -replace an expired VM. Probe executables; dependencies are not guaranteed. +Internet access by default, no SSH, and no automatic lifetime expiry. A running +VM bills until it is stopped: stop it when finished if you will reuse it, or +delete it when its files are no longer needed. Execution does not replace an +expired VM. Probe executables; dependencies are not guaranteed. ```sh bxc sandbox upload SANDBOX_ID fixture.txt /workspace/fixture.txt diff --git a/src/cli.ts b/src/cli.ts index 169c1ad..72e02fc 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -48,6 +48,7 @@ import { runProxy } from "./proxy.js"; import { runSsh } from "./ssh.js"; import { cooperativeConnectionApi } from "./cooperative-connection.js"; import { resumeSandbox } from "./resume.js"; +import { stopSandbox } from "./stop.js"; const DEFAULT_URL = "https://app.boxcompute.ai"; const CLI_VERSION = (JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version; @@ -73,6 +74,7 @@ Commands: sandbox Manage isolated BoxCompute sandboxes start Create and start a workspace sandbox resume Start an existing sandbox with its retained files + stop Stop a running VM now; keep its files status Inspect one sandbox logs Read current or retained sandbox logs exec Execute a program inside a sandbox @@ -117,6 +119,7 @@ Examples: $ bxc sandbox start WORKSPACE_ID --size large --idempotency-key SAVED_UNIQUE_KEY $ bxc sandbox logs SANDBOX_ID --source execute $ bxc sandbox exec SANDBOX_ID -- python -m pytest + $ bxc sandbox stop SANDBOX_ID $ bxc sandbox expose SANDBOX_ID --port 3000 $ bxc sandbox preview SANDBOX_ID --port 3000 $ bxc costs --from 2026-10-01T00:00:00Z @@ -136,6 +139,7 @@ Commands: start WORKSPACE_ID Create and start a new sandbox instance resume SANDBOX_ID Start an existing sandbox; retain its disk and files + stop SANDBOX_ID Stop a running VM now; retain its disk and files status SANDBOX_ID Inspect one sandbox logs SANDBOX_ID [options] Read logs without starting the runtime exec SANDBOX_ID [options] -- PROGRAM [ARG...] @@ -182,6 +186,14 @@ Resume options: Resume keeps the existing sandbox ID, disk and files. Running compute resumes billing. It waits up to 180 seconds; inspect status after an uncertain response. +Stop: + + Stop ends a running VM's compute billing now and keeps its disk and files; + resume, exec or a file transfer starts it again. It never wakes a stopped VM + and is safe to repeat. Without it, a VM stops 30 minutes after its last + resume, exec, file transfer or preview; status, logs, analytics, costs and + work running inside the VM do not count as activity. + Expose options: --port [LOCAL:]REMOTE Repeat for up to 8 unique ports. The local @@ -1189,6 +1201,14 @@ export async function runCli(argv: string[], supplied: CliDependencies = {}): Pr if (action === "rm") action = "delete"; const id = args.shift(); if (!action || !id) throw new UsageError("sandbox requires an action and sandbox ID"); + if (action === "stop") { + if (args.length) throw new UsageError(`Unknown sandbox stop option: ${args[0]}`); + const { sandbox, stopped } = await stopSandbox(connection, fetchImpl, id); + emit(io, json, { sandbox, stopped }, stopped + ? `Stopped sandbox ${id}; its files are kept. Start it again with 'bxc sandbox resume ${id}'.\n` + : `Sandbox ${id} was not running (${sandbox.state}); nothing to stop.\n`); + return 0; + } if (action === "resume") { const key = option(args, "idempotency-key"); const noWait = flag(args, "no-wait"); diff --git a/src/stop.ts b/src/stop.ts new file mode 100644 index 0000000..4d330cb --- /dev/null +++ b/src/stop.ts @@ -0,0 +1,71 @@ +import { BoxComputeError, type Sandbox } from "@boxcompute/sdk"; +import type { Connection } from "./config.js"; + +export type StopResult = { sandbox: Sandbox; stopped: boolean }; + +/** + * `POST /api/v2/sandboxes/{id}/stop` (server 0.62.0+). The SDK does not expose + * it yet, so this keeps resume's origin, ID, redirect and size checks. Stopping + * is idempotent and never wakes compute, so unlike resume, server errors are + * shown as they are: a retry cannot start or double-bill anything. + */ +export async function stopSandbox(connection: Connection, fetchImpl: typeof fetch, id: string): Promise { + if (!/^sbx_[a-zA-Z0-9_-]+$/.test(id)) throw new Error("A sandbox ID is required"); + const origin = new URL(connection.url); + if (origin.username || origin.password || origin.search || origin.hash || origin.pathname !== "/" + || (origin.protocol !== "https:" && !(origin.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname)))) { + throw new Error("Stop requires HTTPS or a loopback development server"); + } + let response: Response; + try { + response = await fetchImpl(new URL(`/api/v2/sandboxes/${encodeURIComponent(id)}/stop`, origin), { + method: "POST", body: "{}", redirect: "error", signal: AbortSignal.timeout(60_000), + headers: { authorization: `Bearer ${connection.token}`, "content-type": "application/json", accept: "application/json" }, + }); + } catch { + throw new Error(`Stop request did not reach BoxCompute. Check 'bxc sandbox status ${id}', then retry.`); + } + const value = await boundedJson(response); + if (!response.ok) { + const body = value as { code?: unknown; error?: unknown } | undefined; + const code = typeof body?.code === "string" ? body.code : undefined; + const message = typeof body?.error === "string" ? body.error : undefined; + // A server older than 0.62.0 has no such route and answers without the API's error body. + if ((response.status === 404 || response.status === 405) && !code) { + throw new Error(`This BoxCompute server does not support stopping a sandbox yet (HTTP ${response.status}).`); + } + if (response.status === 409) { + throw new BoxComputeError({ status: 409, code: code ?? "SANDBOX_UNAVAILABLE", + message: `Sandbox ${id} is still starting, stopping or in use; run 'bxc sandbox stop ${id}' again in a moment` }); + } + throw new BoxComputeError({ status: response.status, code: code ?? "HTTP_ERROR", + message: message ?? `BoxCompute returned HTTP ${response.status}` }); + } + const result = value as Partial | undefined; + if (result?.sandbox?.id !== id || typeof result.stopped !== "boolean" + || !["running", "pending", "cold", "expired"].includes(result.sandbox.state)) { + throw new Error(`Stop was not confirmed. Check 'bxc sandbox status ${id}' before retrying.`); + } + return { sandbox: result.sandbox, stopped: result.stopped }; +} + +async function boundedJson(response: Response): Promise { + if (!response.body) return undefined; + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + length += value.byteLength; + if (length > 65_536) return undefined; + chunks.push(value); + } + } finally { await reader.cancel().catch(() => undefined); reader.releaseLock(); } + try { + return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))); + } catch { + return undefined; + } +} diff --git a/test/cli.test.ts b/test/cli.test.ts index 1ab1a1d..d837642 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -481,6 +481,7 @@ describe("bxc CLI", () => { const sandboxHelp = output(sandboxIo.stdout); expect(sandboxHelp).toContain("--cpu CPU"); expect(sandboxHelp).toContain("--size small|large"); + expect(sandboxHelp).toContain("stop SANDBOX_ID"); const versionIo = streams(); expect(await runCli(["--version"], { io: versionIo, env: {} })).toBe(0); diff --git a/test/stop.test.ts b/test/stop.test.ts new file mode 100644 index 0000000..2942225 --- /dev/null +++ b/test/stop.test.ts @@ -0,0 +1,75 @@ +import { expect, test } from "bun:test"; +import { PassThrough } from "node:stream"; +import { BoxComputeError } from "@boxcompute/sdk"; +import { formatCliError, runCli } from "../src/cli.js"; +import { stopSandbox } from "../src/stop.js"; + +const connection = { url: "https://app.boxcompute.ai", token: "test-credential", tokenFile: "/unused" }; +const sandbox = { id: "sbx_running", state: "cold", name: "retained", workspaceId: "ws_one", vmSandbox: true, createdAt: 1, lastUsedAt: 2 } as const; +const response = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status }); + +test("stop calls only the stop endpoint with an empty JSON body", async () => { + let calls = 0; + const fetcher = (async (url: unknown, init?: RequestInit) => { + calls++; + expect(String(url)).toBe("https://app.boxcompute.ai/api/v2/sandboxes/sbx_running/stop"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe("{}"); + expect(init?.redirect).toBe("error"); + expect(init?.signal).toBeInstanceOf(AbortSignal); + expect(new Headers(init?.headers).get("content-type")).toBe("application/json"); + expect(new Headers(init?.headers).get("authorization")).toBe("Bearer test-credential"); + return response({ sandbox, stopped: true }); + }) as typeof fetch; + expect(await stopSandbox(connection, fetcher, sandbox.id)).toEqual({ sandbox, stopped: true }); + expect(calls).toBe(1); +}); + +test("stop rejects unsafe origins and IDs before sending credentials", async () => { + const fetcher = (async () => { throw new Error("must not send"); }) as unknown as typeof fetch; + for (const url of ["http://public.example", "https://user:pass@app.boxcompute.ai", "https://app.boxcompute.ai/other", "https://app.boxcompute.ai/?query=yes"]) { + await expect(stopSandbox({ ...connection, url }, fetcher, sandbox.id)).rejects.toThrow("Stop requires"); + } + await expect(stopSandbox(connection, fetcher, "../sbx_other")).rejects.toThrow("sandbox ID"); +}); + +test("busy, rejected, unsupported and unreachable stops say what to do", async () => { + const run = (handler: () => Response) => stopSandbox(connection, (async () => handler()) as unknown as typeof fetch, sandbox.id); + + const busy = await run(() => response({ code: "SANDBOX_UNAVAILABLE", error: "This VM is pending, so it cannot be stopped now." }, 409)).catch((error) => error); + expect(busy).toBeInstanceOf(BoxComputeError); + expect(formatCliError(busy)).toBe("Sandbox sbx_running is still starting, stopping or in use; run 'bxc sandbox stop sbx_running' again in a moment (HTTP 409 SANDBOX_UNAVAILABLE)"); + + const container = await run(() => response({ code: "INVALID_REQUEST", error: "Only VMs can be stopped. Legacy containers stop when idle." }, 400)).catch((error) => error); + expect(formatCliError(container)).toBe("Only VMs can be stopped. Legacy containers stop when idle. (HTTP 400 INVALID_REQUEST)"); + + await expect(run(() => new Response("404 Not Found", { status: 404 }))).rejects.toThrow("does not support stopping"); + await expect(stopSandbox(connection, (async () => { throw new Error("private transport content"); }) as unknown as typeof fetch, sandbox.id)) + .rejects.toThrow("Stop request did not reach BoxCompute"); + for (const body of [{ sandbox: { ...sandbox, id: "sbx_other" }, stopped: true }, { sandbox }, { sandbox: { ...sandbox, state: "unknown" }, stopped: true }]) { + await expect(run(() => response(body))).rejects.toThrow("Stop was not confirmed"); + } + await expect(run(() => new Response("x".repeat(65_537)))).rejects.toThrow("Stop was not confirmed"); +}); + +test("CLI reports a stop, a VM that was not running, and refuses options", async () => { + for (const stopped of [true, false]) { + for (const json of [true, false]) { + const io = { stdout: new PassThrough(), stderr: new PassThrough() }; + const calls: string[] = []; + const deps = { io, env: {}, loadConnection: async () => connection, syncManagedSkills: async () => [], + fetch: (async (url: unknown) => { calls.push(String(url)); return response({ sandbox, stopped }); }) as unknown as typeof fetch }; + expect(await runCli([...(json ? ["--json"] : []), "sandbox", "stop", sandbox.id], deps)).toBe(0); + expect(calls).toEqual([`https://app.boxcompute.ai/api/v2/sandboxes/${sandbox.id}/stop`]); + const out = io.stdout.read().toString(); + if (json) expect(JSON.parse(out)).toEqual({ sandbox, stopped }); + else expect(out).toBe(stopped + ? "Stopped sandbox sbx_running; its files are kept. Start it again with 'bxc sandbox resume sbx_running'.\n" + : "Sandbox sbx_running was not running (cold); nothing to stop.\n"); + } + } + const io = { stdout: new PassThrough(), stderr: new PassThrough() }; + await expect(runCli(["sandbox", "stop", sandbox.id, "--force"], { io, env: {}, loadConnection: async () => connection, + syncManagedSkills: async () => [], fetch: (async () => { throw new Error("must not send"); }) as unknown as typeof fetch })) + .rejects.toThrow("Unknown sandbox stop option: --force"); +});