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.17.0] - 2026-11-30

Run committed local code in an existing sandbox, including commits you have
never pushed.

### CLI users

- Run `bxc sandbox import-git SANDBOX_ID . HEAD /workspace/project` from a
local checkout. The command verifies the commit and creates a detached
checkout at a new path. Large Git packs transfer in 8 MiB chunks.

### Security

- The import sends Git objects reachable from the selected commit. Working-tree
changes, Git configuration, credential helpers, and remotes stay local.

## [0.16.0] - 2026-11-30

Reconnect to sandbox commands after the CLI exits.
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,27 @@ options before `--`.
Terminal state and output are retained until `expiresAt`, 24 hours after the
operation ends. See [Execute commands](https://boxcompute.ai/docs/execute/).

### Import a local Git revision

```sh
bxc sandbox import-git SANDBOX_ID . HEAD /workspace/project
```

Pass a local checkout directory and a Git revision such as `HEAD`, a tag, or
a commit ID. The commit and its history must be available locally. The command
works with unpublished commits and repositories without a remote. It prints
the full commit ID and creates a detached checkout in the sandbox. Use a new
destination below `/workspace` whose parent directory already exists.

Git is required on both machines. The import transfers the selected commit and
its reachable history. Working-tree changes, Git configuration, credential
helpers, and remotes stay local. Submodules stay uninitialized, and Git LFS
files stay as pointers.

The command uploads the Git pack in chunks and verifies it before moving the
checkout into place. If publication returns an uncertain result, inspect the
destination and the staging path printed by the command before retrying.

### 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.16.0",
"version": "0.17.0",
"description": "Connect local AI agents to BoxCompute sandboxes",
"keywords": [
"boxcompute",
Expand Down
6 changes: 6 additions & 0 deletions skills/boxcompute-sandbox/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ bxc sandbox download SANDBOX_ID /workspace/result.txt result.txt
Uploads send raw bytes and are limited to 8 MiB. Downloads follow cursors to
EOF, discard partial output on errors, and require a new local destination.
Remote paths stay under `/workspace`; create parent directories with exec.

To import a committed local revision, use
`bxc sandbox import-git SANDBOX_ID . HEAD /workspace/project`.
The destination must be new and its parent must exist. The command verifies
the exact commit, including an unpublished commit, and returns its full ID.

Stop writers before downloading state. For disposable VM tests, export early
and delete with `bxc sandbox delete SANDBOX_ID --yes`, including on test failure
or expiry. Ordinary Sandbox persistence guidance below does not apply to VMs.
Expand Down
16 changes: 16 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { hostname, platform, release } from "node:os";
import type { Readable, Writable } from "node:stream";
import { fileURLToPath } from "node:url";
import { downloadFile, uploadFile } from "./files.js";
import { importGit } from "./git-import.js";
import {
BoxCompute,
BoxComputeError,
Expand Down Expand Up @@ -98,6 +99,7 @@ Commands:
ssh Open experimental lease-limited SSH
upload Upload a local file (up to 8 MiB)
download Download a complete file to a new local path
import-git Import a pinned local Git commit into a new directory
analytics Read lifecycle, operation, and resource analytics
costs List every charged run of one sandbox
delete [alias: rm] Destroy the runtime; the workspace remains
Expand Down Expand Up @@ -184,6 +186,8 @@ Commands:
upload SANDBOX_ID LOCAL REMOTE Upload raw bytes under /workspace (up to 8 MiB)
download SANDBOX_ID REMOTE LOCAL
Download all chunks; refuse an existing local file
import-git SANDBOX_ID LOCAL REVISION REMOTE
Check out a local Git commit at a new path under /workspace

Start options:

Expand Down Expand Up @@ -1574,6 +1578,18 @@ export async function runCli(argv: string[], supplied: CliDependencies = {}): Pr
emit(io, json, { sandboxId: id, source, destination, bytes }, `${action === "upload" ? "Uploaded" : "Downloaded"} ${bytes} bytes: ${source} -> ${destination}\n`);
return 0;
}
if (action === "import-git") {
if (args.length !== 3 || args.some((arg) => !arg)) {
throw new UsageError("sandbox import-git requires SANDBOX_ID LOCAL REVISION REMOTE");
}
const [source, revision, destination] = args;
const imported = await importGit(client, {
sandboxId: id, source, revision, destination,
warn: (message) => write(io.stderr, `Warning: ${message}\n`),
});
emit(io, json, imported, `Imported commit ${imported.commit} to ${destination} in sandbox ${id}.\n`);
return 0;
}
if (action === "status") {
if (args.length) throw new UsageError("sandbox status takes one sandbox ID");
const sandbox = await client.sandboxes.inspect(id);
Expand Down
191 changes: 191 additions & 0 deletions src/git-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import { execFile, spawn } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { constants } from "node:fs";
import { access, mkdtemp, open, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { delimiter, dirname, isAbsolute, join, posix, resolve } from "node:path";
import { promisify } from "node:util";
import { BoxComputeError, type BoxCompute } from "@boxcompute/sdk";
import { FILE_CHUNK_BYTES, validateFilePath } from "./sdk.js";

const execGit = promisify(execFile);
const request = { timeoutMs: 30_000 };
const gitOptions = ["--no-replace-objects", "-c", "advice.graftFileDeprecated=false"];

const restoreCheckout = `
set -eu
cd -- "$1"
cat -- part-* > export.pack
actual=$(sha256sum < export.pack)
if [ "\${actual%% *}" != "$2" ]; then
echo 'Git pack failed its SHA-256 check' >&2
exit 1
fi
rm -- part-*

git_clean() {
env -i PATH="$PATH" GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_ATTR_NOSYSTEM=1 git "$@"
}
git_clean init -q --template= --object-format="$4" checkout
git_clean -C checkout index-pack --stdin < export.pack > /dev/null
rm -- export.pack
git_clean -C checkout rev-list --objects --missing=error "$3" > /dev/null
git_clean -C checkout checkout --quiet --detach --no-recurse-submodules "$3"
test "$(git_clean -C checkout rev-parse --verify HEAD)" = "$3"
`;

function sourceGitEnvironment(): NodeJS.ProcessEnv {
// Keep protected settings such as safe.directory and discover metadata in the selected checkout.
const config = /^GIT_CONFIG_(GLOBAL|SYSTEM|NOSYSTEM|COUNT|PARAMETERS|(?:KEY|VALUE)_\d+)$/i;
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^GIT_/i.test(key) || config.test(key)));
return {
...env,
GIT_GRAFT_FILE: "/dev/null",
GIT_ALLOW_PROTOCOL: "",
GIT_NO_LAZY_FETCH: "1",
};
}

async function findGit(): Promise<string> {
const windows = process.platform === "win32";
for (const entry of (process.env.PATH ?? "").split(delimiter)) {
const directory = windows && entry.startsWith('"') && entry.endsWith('"') ? entry.slice(1, -1) : entry;
if (!isAbsolute(directory)) continue;
const candidate = resolve(directory, windows ? "git.exe" : "git");
try {
if (!(await stat(candidate)).isFile()) continue;
await access(candidate, constants.X_OK);
return candidate;
} catch {
// Look in the next PATH directory.
}
}
throw new Error("Git was not found in an absolute PATH directory");
}

async function writePack(input: { git: string; source: string; commit: string; pack: string; env: NodeJS.ProcessEnv }): Promise<void> {
const { git, source, commit, pack, env } = input;
const file = await open(pack, "wx", 0o600);
try {
// Walk actual parents even when the source has a shallow boundary.
const args = ["-C", source, ...gitOptions, "--shallow-file", "", "pack-objects", "--stdout", "--revs"];
const child = spawn(git, args, {
cwd: dirname(git), env, stdio: ["pipe", file.fd, "ignore"],
});
await new Promise<void>((resolve, reject) => {
child.once("error", reject);
child.once("close", (code) => {
if (code === 0) resolve();
else reject(new Error("Could not export the pinned Git commit. The commit and its full history must be available locally."));
});
// Git may exit before consuming stdin. Its exit status reports that failure.
child.stdin?.on("error", () => {});
child.stdin?.end(`${commit}\n`);
});
} finally {
await file.close();
}
}

async function uploadPack(client: BoxCompute, id: string, stage: string, pack: string) {
const buffer = Buffer.alloc(FILE_CHUNK_BYTES);
const hash = createHash("sha256");
let bytes = 0;
let part = 0;
const file = await open(pack, "r");
try {
for (;;) {
const { bytesRead } = await file.read(buffer, 0, buffer.length, null);
if (bytesRead === 0) break;
const chunk = buffer.subarray(0, bytesRead);
hash.update(chunk);
const name = `part-${String(part++).padStart(10, "0")}`;
await client.files.write(id, `${stage}/${name}`, chunk, request);
bytes += bytesRead;
}
} finally {
await file.close();
}
return { bytes, sha256: hash.digest("hex") };
}

function mutationUncertain(error: unknown): boolean {
return !(error instanceof BoxComputeError) || error.status >= 500;
}

export async function importGit(client: BoxCompute, input: {
sandboxId: string;
source: string;
revision: string;
destination: string;
warn: (message: string) => void;
}) {
const { sandboxId: id, revision, destination, warn } = input;
validateFilePath(destination);
if (destination === "/workspace" || destination.endsWith("/") || destination.includes("//")) {
throw new Error("Git import destination must name a new directory below /workspace with no empty path components");
}

const source = resolve(input.source);
const git = await findGit();
const env = sourceGitEnvironment();
const args = ["-C", source, ...gitOptions, "rev-parse", "--verify", "--end-of-options"];
const options = { cwd: dirname(git), env };
const object = await execGit(git, [...args, revision], options);
const { stdout } = await execGit(git, [...args, `${object.stdout.trim()}^{commit}`], options);
const commit = stdout.trim();
if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit)) throw new Error("Git did not return a full commit ID");
const objectFormat = commit.length === 40 ? "sha1" : "sha256";

const stage = `${posix.dirname(destination)}/.bxc-git-import-${randomUUID()}`;
validateFilePath(`${stage}/part-0000000000`);
const local = await mkdtemp(join(tmpdir(), "bxc-git-import-"));
try {
const pack = join(local, "export.pack");
await writePack({ git, source, commit, pack, env });
try {
await client.files.mkdir(id, stage, { recursive: false }, request);
} catch (error) {
if (!mutationUncertain(error)) throw error;
throw new Error(`Could not confirm creation of sandbox staging directory ${JSON.stringify(stage)}. Inspect it before retrying.`, { cause: error });
}

let publishing = false;
let bytes: number;
try {
const upload = await uploadPack(client, id, stage, pack);
bytes = upload.bytes;
const result = await client.sandboxes.execute(id, {
argv: ["sh", "-c", restoreCheckout, "bxc-import-git", stage, upload.sha256, commit, objectFormat],
cwd: "/workspace",
timeoutSeconds: 900,
maxOutputBytes: 4096,
}, { timeoutMs: 930_000 });
if (result.timedOut) throw new Error("Git checkout verification timed out in the sandbox");
if (result.exitCode !== 0) {
throw new Error(`Git checkout verification failed in the sandbox (exit ${result.exitCode})\n${result.stderr.trimEnd()}`);
}
publishing = true;
await client.files.rename(id, `${stage}/checkout`, { destination, overwrite: false }, request);
} catch (error) {
// Recursive removal could race an in-flight rename of the checkout.
if (publishing && mutationUncertain(error)) {
throw new Error(`Could not confirm publication of commit ${commit} at ${JSON.stringify(destination)}. Inspect the destination and staging directory ${JSON.stringify(stage)} before retrying.`, { cause: error });
}
try {
await client.files.remove(id, stage, { recursive: true, force: true, ...request });
} catch (cleanupError) {
throw new Error(`${String(error)}. Could not remove sandbox staging directory ${JSON.stringify(stage)}.`, { cause: cleanupError });
}
throw error;
}
await client.files.remove(id, stage, { force: true, ...request }).catch(() => {
warn(`Could not remove empty sandbox staging directory ${JSON.stringify(stage)}.`);
});
return { sandboxId: id, destination, commit, bytes };
} finally {
await rm(local, { recursive: true, force: true }).catch(() => {
warn(`Could not remove local Git staging directory ${JSON.stringify(local)}.`);
});
}
}
Loading