Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,22 @@
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.16.0] - 2026-11-30

Reconnect to sandbox commands after the CLI exits.

### CLI users

- Use `bxc sandbox operation start` with a saved idempotency key. Keep the
returned operation ID to inspect or wait for the command, page through its
stdout and stderr, or request cancellation.
- Update with `bxc update` or `npm install --global @boxcompute/cli@latest`.

### Security

- Operation commands use the saved BoxCompute connection and the API's
existing sandbox execution scope.

## [0.15.0] - 2026-11-30

Create XL and XXL VM sandboxes from the CLI.
Expand Down
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,53 @@ 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.

### Reconnect to a sandbox command

Use `bxc sandbox operation start` when you need to check a command after the
CLI exits or the connection drops. It accepts the same execution options as
`bxc sandbox exec`, including `--cwd`, repeatable `--env`, `--timeout`, and
`--max-output-bytes`. Everything after `--` goes to the program.

```sh
bxc --json sandbox operation start SANDBOX_ID --idempotency-key SAVED_UNIQUE_KEY --timeout 600 -- python -m pytest
bxc sandbox operation inspect SANDBOX_ID -- OPERATION_ID
bxc sandbox operation wait SANDBOX_ID --timeout 30 -- OPERATION_ID
bxc sandbox operation output SANDBOX_ID --stream stdout --offset 0 --limit 65536 -- OPERATION_ID
bxc sandbox operation output SANDBOX_ID --stream stderr --offset 0 -- OPERATION_ID
bxc sandbox operation cancel SANDBOX_ID -- OPERATION_ID
```

Save the sandbox ID, the returned `operationId`, and the idempotency key. If
the start response is lost, repeat the same start request with the saved key
within 24 hours to recover the original receipt. The execution timeout
defaults to 120 seconds and can be up to 900 seconds.

The `--` before `OPERATION_ID` keeps IDs that start with a dash intact. Put CLI
options before `--`.

- `wait` makes one request, with a timeout of 0 to 30 seconds (default 30).
It returns the command's exit code for a completed operation, 75 if the
operation is still accepted or running, 124 for an execution timeout, and 1
for failed or cancelled operations or a completed operation without an exit
code. Use the returned state to distinguish these outcomes when an exit code
overlaps. Call `wait` again with the same ID if the command is still running.
If `wait` exits 1 with no output on stdout, check stderr for the request
error. If the connection dropped, run `inspect` or `wait` again with that ID.
- `output` reads one page of one stream. The defaults are stdout, offset 0,
and 65,536 bytes per page. The maximum page size is 262,144 bytes. Use
`nextOffset` as the next `--offset` for the same stream. If `truncated` is
true, bytes before `earliestOffset` are gone. Without `--json`, the CLI
writes the selected stream's raw bytes to stdout and the page metadata to
stderr. With `--json`, stdout contains `stream`, `dataBase64`, `offset`,
`nextOffset`, `earliestOffset`, and `truncated` in one JSON object.
- `cancel` requests remote cancellation. It exits 0 when the returned state
is `cancelled` and 1 if another terminal state wins. Closing the CLI leaves
the operation running. With `--json`, start, inspect, wait, and cancel each
return an `{ "operation": ... }` object on stdout.

Terminal state and output are retained until `expiresAt`, 24 hours after the
operation ends. See [Execute commands](https://boxcompute.ai/docs/execute/).

### Expose VM services

To reach a TCP service running inside a network-enabled VM, keep a foreground
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@boxcompute/cli",
"version": "0.15.0",
"version": "0.16.0",
"description": "Connect local AI agents to BoxCompute sandboxes",
"keywords": [
"boxcompute",
Expand Down
13 changes: 13 additions & 0 deletions skills/boxcompute-sandbox/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,19 @@ is task evidence, not a reason to repeat blindly: read stdout/stderr, correct
the cause, and then run the revised command. Never send local secrets into the
sandbox unless the user explicitly places those secrets in scope.

For a command you need to check after disconnecting, start a durable operation:

```sh
bxc --json sandbox operation start SANDBOX_ID --idempotency-key SAVED_UNIQUE_KEY -- python -m pytest
```

Save the sandbox ID, `operationId`, and key. If the start response is lost,
retry the same request with that key. Use `sandbox operation inspect` or
`sandbox operation wait` with both IDs. Each wait lasts up to 30 seconds.
Read `operation.state` from the JSON before interpreting the wait exit status.
Use `sandbox operation output` to page stdout or stderr at `nextOffset`, and
`sandbox operation cancel` to request remote cancellation.

## Experimental SSH transport

Use `bxc sandbox exec` for normal agent work. Only use the experimental SSH
Expand Down
173 changes: 144 additions & 29 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ import {
type BillingTransactionPage,
type AuditEventPage,
type DeletedSandbox,
type ExecuteRequest,
type ExecutionResult,
type Me,
type Operation,
type Preview,
type Sandbox,
type SandboxAnalytics,
Expand Down Expand Up @@ -89,6 +91,7 @@ Commands:
status Inspect one sandbox
logs Read current or retained sandbox logs
exec Execute a program inside a sandbox
operation Start, inspect, wait for, read, or cancel a command
expose Forward selected TCP ports to local loopback
Requires ${SERVICE_PLATFORMS}
preview Open or close a one-hour browser preview URL
Expand Down Expand Up @@ -158,6 +161,16 @@ Commands:
logs SANDBOX_ID [options] Read logs without starting the runtime
exec SANDBOX_ID [options] -- PROGRAM [ARG...]
Execute a program inside a sandbox
operation start SANDBOX_ID --idempotency-key KEY [options] -- PROGRAM [ARG...]
Start a command and return an operation ID
operation inspect SANDBOX_ID OPERATION_ID
Read the current operation state
operation wait SANDBOX_ID OPERATION_ID [--timeout SECONDS]
Wait once for up to 30 seconds (0 checks immediately)
operation output SANDBOX_ID OPERATION_ID [--stream stdout|stderr] [--offset BYTES] [--limit BYTES]
Read one page of retained output (default: stdout)
operation cancel SANDBOX_ID OPERATION_ID
Request remote cancellation
expose SANDBOX_ID --port [LOCAL:]REMOTE
Forward up to 8 TCP ports to 127.0.0.1
Requires ${SERVICE_PLATFORMS}
Expand Down Expand Up @@ -205,6 +218,20 @@ Stop:
resume, exec, file transfer or preview; status, logs, analytics, costs and
work running inside the VM do not count as activity.

Exec and operation start options:

--cwd PATH Working directory under /workspace (default: /workspace)
--env KEY=VALUE Environment variable (repeatable)
--timeout SECONDS Execution timeout (default: 120, max: 900)
--max-output-bytes BYTES Retained bytes per stream (default: 262144, max: 1048576)

For operation start, save the idempotency key and reuse it with the same
options and arguments if you lose the response. Save the returned operation ID.
Use --idempotency-key=KEY for a key that starts with two dashes.
For operation output, offset defaults to zero and limit to 65536 bytes
(max: 262144). Continue at nextOffset. Use --json for base64 and cursor fields.
For an operation ID that starts with a dash, put options before -- OPERATION_ID.

Expose options:

--port [LOCAL:]REMOTE Repeat for up to 8 unique ports. The local
Expand Down Expand Up @@ -237,13 +264,6 @@ SSH options:
Requires BOXCOMPUTE_ENABLE_SSH=1. Available only for operator-enabled
sandboxes on Linux and macOS (x64 or arm64). Cleanup remains unconfirmed.

Exec options:

--cwd PATH Working directory under /workspace
--env KEY=VALUE Set an environment variable; repeatable
--timeout SECONDS Command timeout
--max-output-bytes BYTES Maximum captured output

Log options:

--since TIMESTAMP Include entries at or after an RFC 3339 time
Expand Down Expand Up @@ -634,10 +654,12 @@ function flag(tokens: string[], name: string): boolean {
return true;
}

function globalFlag(tokens: string[], ...names: string[]): boolean {
function globalFlag(tokens: string[], valueOption: string | undefined, ...names: string[]): boolean {
const separator = tokens.indexOf("--");
const boundary = separator < 0 ? tokens.length : separator;
const index = tokens.findIndex((token, position) => position < boundary && names.includes(token));
const index = tokens.findIndex((token, position) =>
position < boundary && names.includes(token) &&
(!valueOption || tokens[position - 1] !== valueOption));
if (index < 0) return false;
tokens.splice(index, 1);
return true;
Expand All @@ -650,6 +672,13 @@ function positive(value: string | undefined, name: string): number | undefined {
return parsed;
}

function nonnegative(value: string | undefined, name: string): number | undefined {
if (value === undefined) return undefined;
const parsed = Number(value);
if (!value || /\D/.test(value) || !Number.isSafeInteger(parsed)) throw new UsageError(`${name} must be a nonnegative integer`);
return parsed;
}

export function serviceMappings(tokens: string[]): ServiceMapping[] {
const mappings: ServiceMapping[] = [];
while (tokens.includes("--port")) {
Expand Down Expand Up @@ -706,6 +735,21 @@ function environment(tokens: string[]): Record<string, string> | undefined {
}));
}

function executionRequest(args: string[], command: string, options: string[]): ExecuteRequest {
const cwd = option(options, "cwd") ?? "/workspace";
const timeoutSeconds = positive(option(options, "timeout"), "--timeout") ?? 120;
const maxOutputBytes = positive(option(options, "max-output-bytes"), "--max-output-bytes") ?? 262_144;
const env = environment(options);
if (options.length) throw new UsageError(`Unknown ${command} option: ${options[0]}`);
return { argv: args, cwd, timeoutSeconds, maxOutputBytes, ...(env ? { env } : {}) };
}

function splitExecutionArgs(args: string[], command: string) {
const separator = args.indexOf("--");
if (separator < 0 || separator === args.length - 1) throw new UsageError(`${command} requires a program after --`);
return { options: args.slice(0, separator), argv: args.slice(separator + 1) };
}

async function deviceRequest<T>(
url: string,
pathname: string,
Expand Down Expand Up @@ -821,6 +865,88 @@ function executionOutput(io: Io, json: boolean, sandboxId: string, result: Execu
return result.exitCode;
}

function emitOperation(io: Io, json: boolean, operation: Operation): void {
const { operationId, state, exitCode, signal, stdoutOffset, stderrOffset, expiresAt } = operation;
emit(io, json, { operation }, `${operationId}\t${state}\texitCode=${exitCode ?? "-"} signal=${signal ?? "-"} ` +
`stdoutOffset=${stdoutOffset} stderrOffset=${stderrOffset} expiresAt=${expiresAt ?? "-"}\n`);
}

function waitExitCode(operation: Operation): number {
switch (operation.state) {
case "accepted":
case "running":
return 75;
case "completed":
return operation.exitCode ?? 1;
case "timedOut":
return 124;
case "failed":
case "cancelled":
return 1;
default: {
const state: never = operation.state;
throw new Error(`Unexpected operation state: ${state}`);
}
}
}

async function runSandboxOperation(operations: BoxCompute["operations"], args: string[], io: Io, json: boolean): Promise<number> {
const action = oneOf(args.shift(), "sandbox operation action", ["start", "inspect", "wait", "output", "cancel"]);
const sandboxId = args.shift();
if (!action || !sandboxId) throw new UsageError("sandbox operation requires an action and SANDBOX_ID");
const command = `sandbox operation ${action}`;
if (action === "start") {
const { options, argv } = splitExecutionArgs(args, command);
const inlineKey = "--idempotency-key=";
const keyIndex = options.findIndex((token) => token.startsWith(inlineKey));
const idempotencyKey = keyIndex < 0
? option(options, "idempotency-key")
: options.splice(keyIndex, 1)[0].slice(inlineKey.length);
if (!idempotencyKey) throw new UsageError(`${command} requires --idempotency-key; save and reuse it with the same request on retry`);
if (idempotencyKey.length > 255 || /[^\x21-\x7e]/.test(idempotencyKey)) {
throw new UsageError("--idempotency-key must contain 1 to 255 visible ASCII characters");
}
const request = executionRequest(argv, command, options);
emitOperation(io, json, await operations.start(sandboxId, { ...request, idempotencyKey }));
return 0;
}

const separator = args.indexOf("--");
if (separator >= 0 && separator !== args.length - 2) {
throw new UsageError(`${command} requires one OPERATION_ID after --`);
}
const operationId = separator < 0 ? args.shift() : args.splice(separator, 2)[1];
if (!operationId) throw new UsageError(`${command} requires OPERATION_ID after SANDBOX_ID`);
if (action === "output") {
const stream = oneOf(option(args, "stream"), "--stream", ["stdout", "stderr"]) ?? "stdout";
const offset = nonnegative(option(args, "offset"), "--offset") ?? 0;
const limit = nonnegative(option(args, "limit"), "--limit") ?? 65_536;
if (limit < 1 || limit > 262_144) throw new UsageError("--limit must be from 1 to 262144 bytes");
if (args.length) throw new UsageError(`Unknown ${command} option: ${args[0]}`);
const chunk = await operations.output(sandboxId, operationId, { stream, offset, limit });
if (json) emit(io, true, chunk, "");
else {
io.stdout.write(Buffer.from(chunk.dataBase64, "base64"));
write(io.stderr, `stream=${chunk.stream} offset=${chunk.offset} nextOffset=${chunk.nextOffset} ` +
`earliestOffset=${chunk.earliestOffset} truncated=${chunk.truncated}\n`);
}
return 0;
}
if (action === "wait") {
const timeoutSeconds = nonnegative(option(args, "timeout"), "--timeout") ?? 30;
if (timeoutSeconds > 30) throw new UsageError("--timeout must be 30 seconds or fewer");
if (args.length) throw new UsageError(`Unknown ${command} option: ${args[0]}`);
const operation = await operations.wait(sandboxId, operationId, { timeoutSeconds });
const code = waitExitCode(operation);
emitOperation(io, json, operation);
return code;
}
if (args.length) throw new UsageError(`Unknown ${command} option: ${args[0]}`);
const operation = await operations[action](sandboxId, operationId);
emitOperation(io, json, operation);
return action === "cancel" && operation.state !== "cancelled" ? 1 : 0;
}

function logsOutput(io: Io, json: boolean, logs: SandboxLogs): number {
if (json) {
emit(io, true, { logs }, "");
Expand Down Expand Up @@ -1044,13 +1170,15 @@ export async function runCli(argv: string[], supplied: CliDependencies = {}): Pr
const ssh = supplied.ssh ?? runSsh;
const streamIo = { stdin: io.stdin ?? process.stdin, stdout: io.stdout, stderr: io.stderr };
const args = [...argv];
const json = globalFlag(args, "--json");
const versionRequested = args[0] === "version" || globalFlag(args, "--version", "-V", "-v");
const [scope, group, verb] = args.filter((token) => !token.startsWith("-"));
const keyOption = scope === "sandbox" && group === "operation" && verb === "start" ? "--idempotency-key" : undefined;
const json = globalFlag(args, keyOption, "--json");
const versionRequested = args[0] === "version" || globalFlag(args, keyOption, "--version", "-V", "-v");
if (versionRequested) {
emit(io, json, { version: CLI_VERSION }, `${CLI_VERSION}\n`);
return 0;
}
const helpRequested = globalFlag(args, "--help", "-h");
const helpRequested = globalFlag(args, keyOption, "--help", "-h");
if (!args.length || args[0] === "help" || helpRequested) {
const helpTarget = args[0] === "help" ? args[1] : args[0];
write(io.stdout, helpFor(helpTarget));
Expand Down Expand Up @@ -1270,7 +1398,7 @@ export async function runCli(argv: string[], supplied: CliDependencies = {}): Pr
}
}

if (command === "sandbox" && !args.length) {
if (command === "sandbox" && (!args.length || (args.length === 1 && args[0] === "operation"))) {
write(io.stdout, sandboxHelp);
return 0;
}
Expand Down Expand Up @@ -1369,6 +1497,7 @@ export async function runCli(argv: string[], supplied: CliDependencies = {}): Pr
if (command !== "sandbox") throw new UsageError(`Unknown command: ${command}`);

let action = args.shift();
if (action === "operation") return runSandboxOperation(client.operations, args, io, json);
if (action === "rm") action = "delete";
const id = args.shift();
if (!action || !id) throw new UsageError("sandbox requires an action and sandbox ID");
Expand Down Expand Up @@ -1527,22 +1656,8 @@ export async function runCli(argv: string[], supplied: CliDependencies = {}): Pr
return 0;
}
if (action === "exec") {
const separator = args.indexOf("--");
if (separator < 0 || separator === args.length - 1) throw new UsageError("sandbox exec requires a program after --");
const options = args.splice(0, separator);
args.shift();
const cwd = option(options, "cwd");
const timeoutSeconds = positive(option(options, "timeout"), "--timeout");
const maxOutputBytes = positive(option(options, "max-output-bytes"), "--max-output-bytes");
const envInput = environment(options);
if (options.length) throw new UsageError(`Unknown sandbox exec option: ${options[0]}`);
const execution = await client.sandboxes.execute(id, {
argv: args,
cwd: cwd ?? "/workspace",
timeoutSeconds: timeoutSeconds ?? 120,
maxOutputBytes: maxOutputBytes ?? 262_144,
...(envInput ? { env: envInput } : {}),
});
const { argv, options } = splitExecutionArgs(args, "sandbox exec");
const execution = await client.sandboxes.execute(id, executionRequest(argv, "sandbox exec", options));
return executionOutput(io, json, id, execution);
}
throw new UsageError(`Unknown sandbox action: ${action}`);
Expand Down
Loading