From fb1748d6b9f941264efa281059d0f4755f842607 Mon Sep 17 00:00:00 2001 From: Farhan Helmy <59960562+farhan-helmy@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:07:49 +0800 Subject: [PATCH] feat(cli): run Orca workspaces on BoxCompute VMs (0.14.0) bxc orca create|suspend|resume|destroy|keep-open are the lifecycle steps of the BoxCompute plugin's Orca VM recipe: a VM per workspace running orca-ide serve on loopback, reached through a preview that keep-open renews while Orca runs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 31 +++ README.md | 22 ++ package.json | 2 +- src/cli.ts | 75 ++++++ src/orca.ts | 594 ++++++++++++++++++++++++++++++++++++++++++++++ test/orca.test.ts | 294 +++++++++++++++++++++++ 6 files changed, 1017 insertions(+), 1 deletion(-) create mode 100644 src/orca.ts create mode 100644 test/orca.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 869cd4e..cd148dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,37 @@ 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.14.0] - 2026-11-23 + +Orca (orca.dev) can run each workspace on its own BoxCompute VM. + +### CLI users + +- New `bxc orca create|suspend|resume|destroy|keep-open`: the lifecycle steps + of the BoxCompute plugin's Orca VM recipe. Orca runs them in your + repository. `create` starts a Large VM (`--size` or `BOXCOMPUTE_ORCA_SIZE` + picks another), installs Orca's server build after checking it against its + release checksums, clones the repository's remote and starts + `orca-ide serve` on the VM's loopback, reached through a BoxCompute preview. + Claude Code and Codex install in the background from their vendors' + installers. `keep-open`, which the plugin runs every 20 minutes while Orca + is open, keeps each awake workspace's link and VM up; it needs BoxCompute + 0.272.0. +- A running VM bills your credit by the minute. After Orca quits, its VMs + stop as idle within about half an hour and keep their files. +- Update with `bxc update` or `npm install --global @boxcompute/cli@latest`. + The Orca plugin pins this version through `npx`. + +### Security + +- A private GitHub repository is cloned with `GH_TOKEN`, `GITHUB_TOKEN` or + `gh auth token`. The token reaches the VM as a file, never in a command's + arguments or environment (which the VM's logs keep), and is deleted after + the clone or fetch. Orca's pairing code is read back as a file and deleted, + never printed by a command on the VM. +- Each workspace's VM and preview IDs are kept in `orca/` beside the CLI's + credential, mode 0600; no credential is stored there. + ## [0.13.0] - 2026-11-16 The retired gVisor options are gone, and the CLI's own guide says where it diff --git a/README.md b/README.md index 8bea3ba..a5ee039 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,28 @@ exact `--revoke` command; the server-side lease still expires naturally. Run `bxc` or `bxc --help` for the complete command reference. The previous `bcompute` executable remains available as a compatibility alias. +## Run Orca workspaces on BoxCompute VMs (`bxc orca`) + +The [BoxCompute plugin for Orca](https://github.com/boxcompute/orca-plugin) +adds **BoxCompute VM** under Orca's **Run on**: each workspace gets its own VM, +with Orca's server, a clone of the repository's remote, and Claude Code and +Codex. Sign in once with `bxc login` (or `npx @boxcompute/cli login`); Orca +then runs these steps itself: + +| Step | What it does | +| --- | --- | +| `bxc orca create [--size SIZE]` | Starts a VM (Large by default), installs Orca's server (checksum-checked), clones the remote, starts `orca-ide serve` on loopback and prints Orca's pairing through a preview link | +| `bxc orca suspend` | Stops the VM; its files stay | +| `bxc orca resume` | Starts it again and prints a fresh pairing | +| `bxc orca destroy` | Deletes the VM | +| `bxc orca keep-open` | Keeps each awake workspace's link open another hour; the plugin runs it every 20 minutes while Orca is open | + +A private GitHub repository is cloned with `GH_TOKEN`, `GITHUB_TOKEN` or +`gh auth token`; the token is copied to the VM as a file and deleted after the +clone or fetch. `BOXCOMPUTE_ORCA_SIZE` overrides the size and +`BOXCOMPUTE_ORCA_WORKSPACE` picks the BoxCompute workspace. A running VM bills +by the minute; after Orca quits, its VMs stop as idle and keep their files. + ## Run chats on your own machine (`bxc runner`) `bxc runner` lets the BoxCompute agent work on a computer you control. It diff --git a/package.json b/package.json index f82c1c3..edb4c61 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@boxcompute/cli", - "version": "0.13.0", + "version": "0.14.0", "description": "Connect local AI agents to BoxCompute sandboxes", "keywords": [ "boxcompute", diff --git a/src/cli.ts b/src/cli.ts index 3970b13..8e4f4c8 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -47,6 +47,7 @@ import { import { openServices, type ServiceMapping } from "./services.js"; import { runProxy } from "./proxy.js"; import { runSsh } from "./ssh.js"; +import { OrcaUsageError, runLocal, runOrca } from "./orca.js"; import { cooperativeConnectionApi } from "./cooperative-connection.js"; import { resumeSandbox } from "./resume.js"; import { stopSandbox } from "./stop.js"; @@ -100,6 +101,7 @@ Commands: costs Compute cost per API key and per sandbox audit Page the account's API audit log runner Run BoxCompute chats in Docker on this machine + orca Run Orca (orca.dev) workspaces on BoxCompute VMs skill [alias: skills] Manage coding-harness skills detect Detect compatible coding harnesses list [alias: ls] List detected or installed harnesses @@ -397,6 +399,51 @@ Supported harnesses: goose, pi, windsurf, and the shared agents directory `; +const orcaHelp = `Run Orca (orca.dev) workspaces on BoxCompute VMs + +Usage: bxc orca [--size SIZE] [--json] + + These are the lifecycle steps of the BoxCompute plugin's Orca VM recipe. + Orca runs them in your repository; you normally never run them by hand. + +Steps: + + create [--size SIZE] Create a VM (small, large, xl or xxl; default + large), clone this repository's remote, start + Orca's server and print Orca's pairing + suspend Stop the workspace's VM; its files are kept + resume Start it again and print a fresh pairing + destroy Delete the workspace's VM + keep-open Keep every awake Orca VM's link open another + hour (the plugin runs it every 20 minutes) + +Environment: + + BOXCOMPUTE_ORCA_SIZE Overrides --size: small, large, xl or xxl + (xl and xxl come with Starter) + BOXCOMPUTE_ORCA_WORKSPACE BoxCompute workspace ID (default: your first) + GH_TOKEN, GITHUB_TOKEN Clones a private GitHub repository; without + them, \`gh auth token\` is tried. Used for the + clone and fetch only, then removed from the VM + + A running VM bills your BoxCompute credit by the minute. While Orca is open, + its awake workspaces' VMs keep running; after Orca quits they stop as idle + within about half an hour, keeping their files. +`; + +async function readAll(stream: Readable): Promise { + if ((stream as { isTTY?: boolean }).isTTY) return ""; + const chunks: Buffer[] = []; + let length = 0; + for await (const chunk of stream) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)); + length += buffer.length; + if (length > 1_048_576) throw new Error("Orca's lifecycle payload is larger than 1 MiB"); + chunks.push(buffer); + } + return Buffer.concat(chunks).toString("utf8"); +} + type Io = { stdin?: Readable; stdout: Writable; stderr: Writable }; type DeviceAuthorization = { deviceCode: string; @@ -428,6 +475,7 @@ export type CliDependencies = { proxy?: typeof runProxy; ssh?: typeof runSsh; runner?: typeof runRunner; + runLocal?: typeof runLocal; /** null simulates a runtime without a global WebSocket (Node.js 20). */ webSocket?: typeof WebSocket | null; }; @@ -1192,6 +1240,32 @@ export async function runCli(argv: string[], supplied: CliDependencies = {}): Pr } } + if (command === "orca") { + const action = args.shift(); + if (!action) { + write(io.stdout, orcaHelp); + return 0; + } + const connection = await load(env); + try { + return await runOrca(action, args, { + client: createClient(connection, fetchImpl), + connection, + fetch: fetchImpl, + env, + stdout: io.stdout, + stderr: io.stderr, + readStdin: () => readAll(io.stdin ?? process.stdin), + sleep, + now, + run: supplied.runLocal ?? runLocal, + }, json); + } catch (error) { + if (error instanceof OrcaUsageError) throw new UsageError(error.message); + throw error; + } + } + if (command === "sandbox" && !args.length) { write(io.stdout, sandboxHelp); return 0; @@ -1493,6 +1567,7 @@ function helpFor(command?: string): string { if (command === "costs") return costsHelp; if (command === "audit") return auditHelp; if (command === "runner") return runnerHelp; + if (command === "orca") return orcaHelp; return rootHelp; } diff --git a/src/orca.ts b/src/orca.ts new file mode 100644 index 0000000..85e48ff --- /dev/null +++ b/src/orca.ts @@ -0,0 +1,594 @@ +import { BoxComputeError, type BoxCompute, type Sandbox } from "@boxcompute/sdk"; +import { execFile } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { connectionPaths, type Connection } from "./config.js"; +import { resumeSandbox } from "./resume.js"; +import { stopSandbox } from "./stop.js"; + +/** + * Orca (orca.dev) per-workspace "Cloud VM" recipe steps. Orca runs them in the + * user's repository with the ORCA_* variables set: `create` and `resume` print + * one recipe-result JSON object on stdout, the others read Orca's lifecycle + * payload on stdin. Everything else goes to stderr, because a stray line on + * stdout is a broken result. + * + * The VM runs `orca-ide serve`; Orca's desktop reaches it through a BoxCompute + * preview (wss://.bxcpreview.site), so nothing is published on the VM's + * own network. A preview lasts an hour unless kept open, and a WebSocket counts + * as VM use only when it opens: `keep-open`, which the Orca plugin's worker + * runs every 20 minutes while Orca is open, keeps both the link and the VM up. + */ + +export const ORCA_PORT = 6768; +const REMOTE_BASE = "/workspace/.boxcompute/orca"; +const PROJECTS = "/workspace/projects"; +/** Used only when Orca does not say which version it is (ORCA_VERSION). */ +const FALLBACK_ORCA_VERSION = "1.4.271"; +const SIZES = ["small", "large", "xl", "xxl"] as const; +type Size = typeof SIZES[number]; +const READY_TIMEOUT_MS = 180_000; + +export type OrcaState = { + instanceId: string; + sandboxId: string; + previewId?: string; + suspended?: boolean; + updatedAt: string; +}; + +export type OrcaDependencies = { + client: BoxCompute; + connection: Connection; + fetch: typeof fetch; + env: NodeJS.ProcessEnv; + stdout: NodeJS.WritableStream; + stderr: NodeJS.WritableStream; + readStdin: () => Promise; + sleep: (milliseconds: number) => Promise; + now: () => number; + /** Runs a local program (git, gh) and returns its trimmed stdout, or null when it fails. */ + run: (file: string, args: string[], cwd: string) => Promise; +}; + +export class OrcaUsageError extends Error {} + +export async function runOrca(action: string | undefined, args: string[], deps: OrcaDependencies, json = false): Promise { + const at = args.indexOf("--size"); + let size: string | undefined; + if (at >= 0) { + if (action !== "create") throw new OrcaUsageError("--size applies only to orca create"); + size = args[at + 1]; + if (!size || size.startsWith("--")) throw new OrcaUsageError("--size requires small, large, xl or xxl"); + args.splice(at, 2); + } + if (args.length) throw new OrcaUsageError(`Unknown orca option: ${args[0]}`); + if (action === "create") return create(deps, size); + if (action === "resume") return resume(deps, await payload(deps)); + if (action === "suspend") return suspend(deps, await payload(deps)); + if (action === "destroy") return destroy(deps, await payload(deps)); + if (action === "keep-open") return keepOpen(deps, json); + throw new OrcaUsageError("orca requires create, suspend, resume, destroy or keep-open"); +} + +// ─── Steps ────────────────────────────────────────────────────────────────── + +async function create(deps: OrcaDependencies, sizeOption?: string): Promise { + const instanceId = requireInstanceId(deps.env.ORCA_VM_INSTANCE_ID); + if ((deps.env.ORCA_RECIPE_RESULT_SCHEMA_VERSION ?? "1") !== "1") { + throw new Error("BoxCompute VMs use Orca's own worktree checkout; recipes with checkoutMode provisioned-root are not supported."); + } + const repo = await localRepository(deps); + // The environment wins, so a person can resize a recipe the plugin pins. + const size = chooseSize(deps.env.BOXCOMPUTE_ORCA_SIZE || sizeOption); + let state = await readState(deps.env, instanceId); + let sandbox: Sandbox; + if (state) { + // A create Orca timed out or retried: carry on with the VM it already has. + log(deps, `Reusing BoxCompute VM ${state.sandboxId} for this workspace…`); + sandbox = await ensureRunning(deps, state.sandboxId); + } else { + const workspaceId = await chooseWorkspace(deps); + log(deps, `Creating a ${size} BoxCompute VM…`); + sandbox = await deps.client.sandboxes.create({ + workspaceId, + vmSandbox: true, + // The SDK's type predates xl and xxl; the server checks the account may use them. + size: size as "small" | "large", + name: sandboxName(deps.env.ORCA_WORKSPACE_NAME, instanceId), + idempotencyKey: `orca-${instanceId}`, + } as Parameters[0]); + // Saved before the slow work, so destroy finds the VM even if Orca gives up on create. + state = { instanceId, sandboxId: sandbox.id, updatedAt: new Date(deps.now()).toISOString() }; + await writeState(deps.env, state); + sandbox = await waitRunning(deps, sandbox); + } + const result = await prepare(deps, state, repo); + deps.stdout.write(`${JSON.stringify(result)}\n`); + return 0; +} + +async function resume(deps: OrcaDependencies, lifecycle: Lifecycle): Promise { + const state = await stateFor(deps, lifecycle); + if (!state) throw new Error("No BoxCompute VM is recorded for this workspace; create a new workspace instead."); + log(deps, `Starting BoxCompute VM ${state.sandboxId}…`); + await ensureRunning(deps, state.sandboxId); + const repo = await localRepository(deps).catch(() => null); + const result = await prepare(deps, { ...state, suspended: false }, repo); + deps.stdout.write(`${JSON.stringify(result)}\n`); + return 0; +} + +async function suspend(deps: OrcaDependencies, lifecycle: Lifecycle): Promise { + const state = await stateFor(deps, lifecycle); + if (!state) throw new Error("No BoxCompute VM is recorded for this workspace."); + // Marked first: keep-open must not touch a VM Orca put to sleep. + await writeState(deps.env, { ...state, suspended: true, updatedAt: new Date(deps.now()).toISOString() }); + const { stopped } = await stopSandbox(deps.connection, deps.fetch, state.sandboxId); + log(deps, stopped + ? `Stopped BoxCompute VM ${state.sandboxId}; its files are kept.` + : `BoxCompute VM ${state.sandboxId} was not running.`); + return 0; +} + +async function destroy(deps: OrcaDependencies, lifecycle: Lifecycle): Promise { + const instanceId = lifecycle.instanceId ?? deps.env.ORCA_VM_INSTANCE_ID; + let sandboxId = (await stateFor(deps, lifecycle))?.sandboxId; + if (!sandboxId && instanceId) { + // Create never returned, and the state file is gone too: find the VM by the + // name create gave it, which ends in this instance's id. + const suffix = nameSuffix(requireInstanceId(instanceId)); + const matches = (await deps.client.sandboxes.list()).filter((item) => item.name.endsWith(suffix)); + if (matches.length > 1) throw new Error(`More than one BoxCompute VM is named for this workspace (${matches.map((item) => item.id).join(", ")}); delete the right one in BoxCompute.`); + sandboxId = matches[0]?.id; + } + if (!sandboxId) { + log(deps, "No BoxCompute VM was created for this workspace; nothing to delete."); + } else { + try { + await deps.client.sandboxes.delete(sandboxId); + log(deps, `Deleted BoxCompute VM ${sandboxId}.`); + } catch (error) { + if (!(error instanceof BoxComputeError && error.status === 404)) throw error; + log(deps, `BoxCompute VM ${sandboxId} was already deleted.`); + } + } + if (instanceId) await removeState(deps.env, requireInstanceId(instanceId)); + return 0; +} + +/** + * Keep each awake Orca VM's preview open another hour. Keeping it open counts + * as VM use, which is what keeps a long agent run from the 30-minute idle stop: + * Orca's single WebSocket is not counted after it opens. + */ +async function keepOpen(deps: OrcaDependencies, json: boolean): Promise { + const states = await listStates(deps.env); + const results: { instanceId: string; sandboxId: string; status: "kept" | "closed" | "asleep" | "failed" }[] = []; + for (const state of states) { + if (state.suspended || !state.previewId) { + results.push({ instanceId: state.instanceId, sandboxId: state.sandboxId, status: "asleep" }); + continue; + } + try { + const kept = await keepPreviewOpen(deps, state.sandboxId, state.previewId); + results.push({ instanceId: state.instanceId, sandboxId: state.sandboxId, status: kept ? "kept" : "closed" }); + } catch { + results.push({ instanceId: state.instanceId, sandboxId: state.sandboxId, status: "failed" }); + } + } + const running = results.filter((item) => item.status === "kept").length; + if (json) deps.stdout.write(`${JSON.stringify({ running, vms: results })}\n`); + else deps.stdout.write(`${running} of ${results.length} Orca VM${results.length === 1 ? "" : "s"} kept open\n`); + return results.some((item) => item.status === "failed") ? 1 : 0; +} + +// ─── Preparing the VM ─────────────────────────────────────────────────────── + +type Repository = { url: string; name: string; token: string | null }; + +type RecipeResult = { + schemaVersion: 1; + pairingCode: string; + projectRoot: string; + userData: { provider: "boxcompute"; sandboxId: string; previewId: string }; +}; + +async function prepare(deps: OrcaDependencies, state: OrcaState, repo: Repository | null): Promise { + const { sandboxId, instanceId } = state; + const version = orcaVersion(deps.env.ORCA_VERSION); + const projectRoot = repo ? `${PROJECTS}/${repo.name}` : await existingProjectRoot(deps, sandboxId); + await execute(deps, sandboxId, ["mkdir", "-p", REMOTE_BASE], 30); + if (repo?.token) { + // A file, not an argument or variable: execution arguments are kept in the VM's logs. + await deps.client.files.write(sandboxId, `${REMOTE_BASE}/git-token`, new TextEncoder().encode(repo.token)); + } + log(deps, "Installing Orca's server on the VM (first time only)…"); + // An operation, not one execute call: the first install takes minutes, and a + // request held past 100 seconds is cut by BoxCompute's edge (HTTP 524). + await operation(deps, sandboxId, ["bash", "-lc", SETUP_SCRIPT], 900, { + BXC_ORCA_VERSION: version, + BXC_ORCA_ROOT: projectRoot, + BXC_ORCA_REPO_URL: repo?.url ?? "", + }); + const preview = await deps.client.previews.create(sandboxId, { port: ORCA_PORT }); + const address = preview.url.replace(/^https:\/\//, "wss://"); + if (!address.startsWith("wss://")) throw new Error("BoxCompute returned a preview that is not HTTPS."); + await writeState(deps.env, { ...state, previewId: preview.previewId, updatedAt: new Date(deps.now()).toISOString() }); + log(deps, "Starting Orca's server…"); + await execute(deps, sandboxId, ["bash", "-lc", SERVE_SCRIPT], 120, { + BXC_ORCA_ROOT: projectRoot, + BXC_ORCA_ADDRESS: address, + BXC_ORCA_INSTANCE: instanceId, + }); + // Read as a file rather than from the command's output, which the VM's logs keep: + // the pairing code grants access to the server. + const recipePath = `${REMOTE_BASE}/recipe.json`; + const file = await deps.client.files.read(sandboxId, recipePath); + await deps.client.files.remove(sandboxId, recipePath).catch(() => undefined); + let served: { pairingCode?: unknown; projectRoot?: unknown }; + try { + served = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(file.data)) as typeof served; + } catch { + throw new Error("Orca's server on the VM did not report how to connect."); + } + if (typeof served.pairingCode !== "string" || !served.pairingCode.startsWith("orca://pair?")) { + throw new Error("Orca's server on the VM returned no pairing code."); + } + return { + schemaVersion: 1, + pairingCode: served.pairingCode, + projectRoot: typeof served.projectRoot === "string" ? served.projectRoot : projectRoot, + userData: { provider: "boxcompute", sandboxId, previewId: preview.previewId }, + }; +} + +/** The checkout a resumed VM already has, when this repository is not readable here. */ +async function existingProjectRoot(deps: OrcaDependencies, sandboxId: string): Promise { + const listed = await execute(deps, sandboxId, ["bash", "-lc", `ls -1d ${PROJECTS}/*/.git 2>/dev/null | head -n 2`], 30); + const roots = listed.stdout.split("\n").filter(Boolean).map((line) => line.replace(/\/\.git$/, "")); + if (roots.length !== 1) throw new Error("Run this step from the workspace's repository."); + return roots[0]!; +} + +async function execute( + deps: OrcaDependencies, + sandboxId: string, + argv: string[], + timeoutSeconds: number, + env?: Record, +) { + const result = await deps.client.sandboxes.execute(sandboxId, { + argv, cwd: "/workspace", timeoutSeconds, maxOutputBytes: 65_536, ...(env ? { env } : {}), + }); + if (result.exitCode !== 0 || result.timedOut) { + const detail = (result.stderr || result.stdout).trim().split("\n").slice(-12).join("\n"); + throw new Error(`${detail || "A command on the VM failed."}\n(BoxCompute VM ${sandboxId}, exit ${result.timedOut ? "timeout" : result.exitCode})`); + } + return result; +} + +/** A background command polled to its end, for work longer than one request may take. */ +async function operation( + deps: OrcaDependencies, + sandboxId: string, + argv: string[], + timeoutSeconds: number, + env: Record, +): Promise { + let current = await deps.client.operations.start(sandboxId, { + argv, cwd: "/workspace", env, timeoutSeconds, maxOutputBytes: 262_144, idempotencyKey: `orca-${randomUUID()}`, + }); + const deadline = deps.now() + (timeoutSeconds + 120) * 1000; + while (current.state === "accepted" || current.state === "running") { + if (deps.now() >= deadline) throw new Error(`A command on BoxCompute VM ${sandboxId} did not finish in ${timeoutSeconds} seconds.`); + current = await deps.client.operations.wait(sandboxId, current.operationId, { timeoutSeconds: 30 }); + } + if (current.state === "completed" && current.exitCode === 0) return; + let detail = ""; + try { + const offset = Math.max(0, current.stderrOffset - 4096); + const chunk = await deps.client.operations.output(sandboxId, current.operationId, { stream: "stderr", offset }); + detail = Buffer.from(chunk.dataBase64, "base64").toString("utf8").trim().split("\n").slice(-12).join("\n"); + } catch { + // The state below still says what happened. + } + throw new Error(`${detail || "A command on the VM failed."}\n(BoxCompute VM ${sandboxId}, ${current.state}${current.exitCode === null ? "" : `, exit ${current.exitCode}`})`); +} + +// The scripts take every value from the environment, never from their text, so +// nothing a repository or Orca names can change what they run. +export const SETUP_SCRIPT = String.raw`set -euo pipefail +B=/workspace/.boxcompute/orca +umask 077 +mkdir -p "$B" +# A create Orca retried waits for the one still running instead of racing it. +exec 8>"$B/setup.lock" +flock 8 +token="$B/git-token" +cleanup() { rm -f "$token" "$B/askpass"; } +trap cleanup EXIT +case "$(uname -m)" in x86_64) arch=x64 ;; aarch64) arch=arm64 ;; *) echo "Unsupported CPU $(uname -m)" >&2; exit 1 ;; esac +dir="$B/server/$BXC_ORCA_VERSION" +if [ ! -x "$dir/bin/orca-ide" ]; then + tmp="$(mktemp -d "$B/download.XXXXXX")" + base="https://github.com/stablyai/orca/releases/download/v$BXC_ORCA_VERSION" + archive="orca-server-linux-$arch.tar.gz" + curl -fsSL --proto '=https' --retry 3 -o "$tmp/$archive" "$base/$archive" + curl -fsSL --proto '=https' --retry 3 -o "$tmp/sums" "$base/orca-server-sha256sums.txt" + expected="$(awk -v f="$archive" '$2 == f || $2 == "*" f { print $1 }' "$tmp/sums")" + actual="$(sha256sum "$tmp/$archive" | awk '{ print $1 }')" + [ -n "$expected" ] && [ "$expected" = "$actual" ] || { echo "Orca server $BXC_ORCA_VERSION failed its checksum" >&2; rm -rf "$tmp"; exit 1; } + mkdir -p "$tmp/x" && tar -xzf "$tmp/$archive" -C "$tmp/x" --strip-components=1 + rm -rf "$dir" && mkdir -p "$B/server" && mv "$tmp/x" "$dir" && rm -rf "$tmp" +fi +ln -sfn "$dir" "$B/server/current" +ln -sfn "$dir/bin/orca-ide" /usr/local/bin/orca-ide +# Claude Code and Codex from their vendors' installers, which check what they +# download; the serve step runs this in the background so Orca opens first. +cat > "$B/install-agents.sh" <<'AGENTS' +set -uo pipefail +B=/workspace/.boxcompute/orca +export HOME=/workspace PATH="/workspace/.local/bin:$PATH" +exec 9>"$B/agents.lock" +flock -n 9 || exit 0 +claude() { + [ -x "$HOME/.local/bin/claude" ] || { curl -fsSL --proto '=https' --tlsv1.2 https://claude.ai/install.sh -o "$B/claude-install.sh" && bash "$B/claude-install.sh" latest; } + [ -x "$HOME/.local/bin/claude" ] && ln -sfn "$HOME/.local/bin/claude" /usr/local/bin/claude +} +codex() { + [ -x "$HOME/.local/bin/codex" ] || { curl -fsSL --proto '=https' --tlsv1.2 https://chatgpt.com/codex/install.sh -o "$B/codex-install.sh" && CODEX_NON_INTERACTIVE=1 sh "$B/codex-install.sh" --release latest; } + [ -x "$HOME/.local/bin/codex" ] && ln -sfn "$HOME/.local/bin/codex" /usr/local/bin/codex +} +claude > "$B/claude-install.log" 2>&1 & +codex > "$B/codex-install.log" 2>&1 & +wait +AGENTS +umask 022 +if [ -n "$BXC_ORCA_REPO_URL" ]; then + export GIT_TERMINAL_PROMPT=0 + if [ -s "$token" ]; then + printf '%s\n' '#!/bin/sh' 'case "$1" in *sername*) echo x-access-token ;; *) cat /workspace/.boxcompute/orca/git-token ;; esac' > "$B/askpass" + chmod 700 "$B/askpass" + export GIT_ASKPASS="$B/askpass" + fi + if [ -d "$BXC_ORCA_ROOT/.git" ]; then + git -C "$BXC_ORCA_ROOT" fetch --quiet --prune origin || echo "Could not fetch $BXC_ORCA_REPO_URL; using the VM's copy." >&2 + else + mkdir -p "$(dirname "$BXC_ORCA_ROOT")" + git clone --quiet -- "$BXC_ORCA_REPO_URL" "$BXC_ORCA_ROOT" || { echo "Could not clone $BXC_ORCA_REPO_URL. A private repository needs GH_TOKEN, GITHUB_TOKEN or 'gh auth login' on this computer." >&2; exit 1; } + fi +fi +[ -d "$BXC_ORCA_ROOT/.git" ] || { echo "The VM has no checkout at $BXC_ORCA_ROOT." >&2; exit 1; } +`; + +export const SERVE_SCRIPT = String.raw`set -euo pipefail +B=/workspace/.boxcompute/orca +O="$B/server/current/bin/orca-ide" +out="$B/recipe.json" +umask 077 +rm -f "$out" +export HOME=/workspace ORCA_INSTANCE_ID="$BXC_ORCA_INSTANCE" +setsid nohup bash "$B/install-agents.sh" > /dev/null 2>&1 < /dev/null & +node="$(ls -d "$B"/server/current/runtimes/node-*/bin/node 2>/dev/null | head -n 1)" +[ -x "$node" ] || node="$(command -v node)" +ready() { "$O" status --json 2>/dev/null | "$node" -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{process.exit(JSON.parse(s).result?.runtime?.state==="ready"?0:1)}catch{process.exit(1)}})'; } +if ready; then + # Still serving (the VM kept running while its link changed): pair with the new link. + "$O" pair --address "$BXC_ORCA_ADDRESS" --json | "$node" -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const r=JSON.parse(s).result;if(!r?.pairingUrl)process.exit(1);process.stdout.write(JSON.stringify({schemaVersion:1,pairingCode:r.pairingUrl,projectRoot:process.env.BXC_ORCA_ROOT}))})' > "$out" + exit 0 +fi +# The launcher prints the result and exits; the server it started keeps running. +setsid nohup "$O" serve --port 6768 --bind 127.0.0.1 --project-root "$BXC_ORCA_ROOT" --pairing-address "$BXC_ORCA_ADDRESS" --recipe-json > "$out" 2> "$B/serve.log" < /dev/null & +for _ in $(seq 1 120); do + if "$node" -e 'JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))' "$out" 2>/dev/null; then exit 0; fi + sleep 0.5 +done +tail -n 20 "$B/serve.log" >&2 +echo "Orca's server did not start within a minute." >&2 +exit 1 +`; + +// ─── Local repository ─────────────────────────────────────────────────────── + +async function localRepository(deps: OrcaDependencies): Promise { + const cwd = deps.env.ORCA_REPO_PATH || process.cwd(); + let raw = await deps.run("git", ["remote", "get-url", "origin"], cwd); + if (!raw) { + const first = (await deps.run("git", ["remote"], cwd))?.split("\n").map((name) => name.trim()).find(Boolean); + raw = first ? await deps.run("git", ["remote", "get-url", first], cwd) : null; + } + if (!raw) throw new Error("This repository has no Git remote. Push it to GitHub (or another Git host) so the BoxCompute VM can clone it."); + const url = httpsRemote(raw); + const host = new URL(url).hostname; + const token = host === "github.com" + ? deps.env.GH_TOKEN || deps.env.GITHUB_TOKEN || await deps.run("gh", ["auth", "token"], cwd) + : null; + return { url, name: repositoryName(url), token: token?.trim() || null }; +} + +/** The VM has no SSH key, so an SSH remote is cloned over HTTPS, without any credential in the URL. */ +export function httpsRemote(remote: string): string { + const value = remote.trim(); + const scp = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/.exec(value); + let url: URL; + try { + url = scp ? new URL(`https://${scp[1]}/${scp[2]}`) : new URL(value); + } catch { + throw new Error(`The VM cannot clone ${value}; use an HTTPS or SSH remote.`); + } + if (url.protocol === "ssh:" || url.protocol === "git:" || url.protocol === "http:") url = new URL(`https://${url.hostname}${url.pathname}`); + if (url.protocol !== "https:") throw new Error(`The VM cannot clone a ${url.protocol} remote; use HTTPS or SSH.`); + url.username = ""; + url.password = ""; + url.search = ""; + url.hash = ""; + return url.href; +} + +export function repositoryName(url: string): string { + const last = new URL(url).pathname.split("/").filter(Boolean).pop() ?? "repo"; + const name = last.replace(/\.git$/, "").replace(/[^A-Za-z0-9._-]/g, "-").replace(/^[.-]+/, "").slice(0, 64); + return name || "repo"; +} + +// ─── BoxCompute ───────────────────────────────────────────────────────────── + +function chooseSize(value: string | undefined): Size { + if (!value) return "large"; + if (!SIZES.includes(value as Size)) throw new OrcaUsageError(`The VM size (--size or BOXCOMPUTE_ORCA_SIZE) must be one of ${SIZES.join(", ")}`); + return value as Size; +} + +async function chooseWorkspace(deps: OrcaDependencies): Promise { + const chosen = deps.env.BOXCOMPUTE_ORCA_WORKSPACE?.trim(); + if (chosen) return chosen; + const workspaces = await deps.client.workspaces.list(); + if (!workspaces[0]) throw new Error("This BoxCompute account has no workspace yet; open app.boxcompute.ai once to create one."); + return workspaces[0].id; +} + +async function waitRunning(deps: OrcaDependencies, sandbox: Sandbox): Promise { + const deadline = deps.now() + READY_TIMEOUT_MS; + let current = sandbox; + while (current.state !== "running") { + if (current.state === "expired") throw new Error(`BoxCompute VM ${current.id} ended before it started.`); + if (deps.now() >= deadline) throw new Error(`BoxCompute VM ${current.id} is still ${current.state} after three minutes.`); + await deps.sleep(3_000); + current = await deps.client.sandboxes.inspect(current.id); + } + return current; +} + +async function ensureRunning(deps: OrcaDependencies, sandboxId: string): Promise { + const current = await deps.client.sandboxes.inspect(sandboxId); + if (current.state === "running") return current; + return waitRunning(deps, await resumeSandbox(deps.connection, deps.fetch, sandboxId)); +} + +/** `POST /api/v2/sandboxes/{id}/previews/{previewId}/keep-open` (server 0.272.0+). False once the link has closed. */ +async function keepPreviewOpen(deps: OrcaDependencies, sandboxId: string, previewId: string): Promise { + if (!/^sbx_[A-Za-z0-9_-]+$/.test(sandboxId) || !/^[a-f0-9]{32}$/.test(previewId)) return false; + const response = await deps.fetch( + new URL(`/api/v2/sandboxes/${sandboxId}/previews/${previewId}/keep-open`, deps.connection.url), + { + method: "POST", redirect: "error", signal: AbortSignal.timeout(30_000), + headers: { authorization: `Bearer ${deps.connection.token}`, accept: "application/json" }, + }, + ); + await response.body?.cancel().catch(() => undefined); + if (response.status === 404) return false; + if (!response.ok) throw new Error(`HTTP ${response.status}`); + return true; +} + +// ─── Names and versions ───────────────────────────────────────────────────── + +export function requireInstanceId(value: string | undefined): string { + const id = value?.trim() ?? ""; + if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(id)) { + throw new OrcaUsageError("ORCA_VM_INSTANCE_ID is missing; run this from an Orca VM recipe."); + } + return id; +} + +/** Ends with the instance id so destroy can find the VM without its state file. */ +function nameSuffix(instanceId: string): string { + return instanceId.startsWith("orca-") ? instanceId : `orca-${instanceId}`.slice(0, 48); +} + +export function sandboxName(workspaceName: string | undefined, instanceId: string): string { + const suffix = nameSuffix(instanceId); + const label = (workspaceName ?? "").replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") + .slice(0, Math.max(0, 79 - suffix.length)); + return label ? `${label}-${suffix}` : suffix; +} + +export function orcaVersion(value: string | undefined): string { + const version = value?.trim().replace(/^v/, "") ?? ""; + // Match the desktop: Orca's client and server speak one protocol version. + return /^\d+\.\d+\.\d+$/.test(version) ? version : FALLBACK_ORCA_VERSION; +} + +// ─── Lifecycle payload and local state ────────────────────────────────────── + +type Lifecycle = { instanceId?: string; sandboxId?: string }; + +async function payload(deps: OrcaDependencies): Promise { + const text = (await deps.readStdin()).trim(); + let parsed: { instanceId?: unknown; recipeResult?: { userData?: { sandboxId?: unknown } } } = {}; + if (text) { + try { + parsed = JSON.parse(text) as typeof parsed; + } catch { + throw new Error("Orca's lifecycle payload on stdin is not JSON."); + } + } + const instanceId = typeof parsed.instanceId === "string" ? parsed.instanceId : deps.env.ORCA_VM_INSTANCE_ID; + const sandboxId = parsed.recipeResult?.userData?.sandboxId; + return { + ...(instanceId ? { instanceId: requireInstanceId(instanceId) } : {}), + ...(typeof sandboxId === "string" && /^sbx_[A-Za-z0-9_-]+$/.test(sandboxId) ? { sandboxId } : {}), + }; +} + +async function stateFor(deps: OrcaDependencies, lifecycle: Lifecycle): Promise { + const saved = lifecycle.instanceId ? await readState(deps.env, lifecycle.instanceId) : null; + if (saved) return saved; + if (lifecycle.sandboxId && lifecycle.instanceId) { + return { instanceId: lifecycle.instanceId, sandboxId: lifecycle.sandboxId, updatedAt: new Date(deps.now()).toISOString() }; + } + return null; +} + +function stateDirectory(env: NodeJS.ProcessEnv): string { + return path.join(connectionPaths(env).directory, "orca"); +} + +async function readState(env: NodeJS.ProcessEnv, instanceId: string): Promise { + try { + const value = JSON.parse(await readFile(path.join(stateDirectory(env), `${instanceId}.json`), "utf8")) as Partial; + return typeof value.sandboxId === "string" && value.instanceId === instanceId ? value as OrcaState : null; + } catch { + return null; + } +} + +async function writeState(env: NodeJS.ProcessEnv, state: OrcaState): Promise { + const directory = stateDirectory(env); + await mkdir(directory, { recursive: true, mode: 0o700 }); + await chmod(directory, 0o700); + const file = path.join(directory, `${state.instanceId}.json`); + const temp = `${file}.${process.pid}.tmp`; + await writeFile(temp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 }); + await rename(temp, file); +} + +async function removeState(env: NodeJS.ProcessEnv, instanceId: string): Promise { + await rm(path.join(stateDirectory(env), `${instanceId}.json`), { force: true }); +} + +async function listStates(env: NodeJS.ProcessEnv): Promise { + let names: string[]; + try { + names = await readdir(stateDirectory(env)); + } catch { + return []; + } + const states = await Promise.all(names.filter((name) => name.endsWith(".json")) + .map((name) => readState(env, name.slice(0, -5)))); + return states.filter((state): state is OrcaState => state !== null); +} + +function log(deps: OrcaDependencies, message: string): void { + deps.stderr.write(`${message}\n`); +} + +/** Local git and gh, with no shell and a short deadline; failures are answers, not errors. */ +export function runLocal(file: string, args: string[], cwd: string): Promise { + return new Promise((resolve) => { + execFile(file, args, { cwd, timeout: 10_000, maxBuffer: 65_536, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }, + (error, stdout) => resolve(error ? null : stdout.trim() || null)); + }); +} diff --git a/test/orca.test.ts b/test/orca.test.ts new file mode 100644 index 0000000..772baae --- /dev/null +++ b/test/orca.test.ts @@ -0,0 +1,294 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdtemp, readFile, readdir, rm, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { PassThrough } from "node:stream"; +import { BoxComputeError, type BoxCompute } from "@boxcompute/sdk"; +import { runCli } from "../src/cli.js"; +import { + httpsRemote, orcaVersion, repositoryName, runOrca, sandboxName, SERVE_SCRIPT, SETUP_SCRIPT, + type OrcaDependencies, +} from "../src/orca.js"; + +const connection = { url: "https://app.boxcompute.ai", token: "bc_live_test", tokenFile: "/unused" }; +const instanceId = "orca-6f1c2d4e-0a1b-4c3d-9e8f-123456789abc"; +const pairingCode = "orca://pair?code=secret-pairing"; +const previewId = "c".repeat(32); +let configDir = ""; + +beforeEach(async () => { configDir = await mkdtemp(path.join(tmpdir(), "bxc-orca-")); }); +afterEach(async () => { await rm(configDir, { recursive: true, force: true }); }); + +type Call = { method: string; args: unknown[] }; + +function fakeClient(overrides: { states?: string[]; list?: { id: string; name: string }[]; deleteStatus?: number; setupFails?: boolean } = {}) { + const calls: Call[] = []; + const states = [...(overrides.states ?? ["pending", "running"])]; + const files = new Map(); + const record = (method: string, ...args: unknown[]) => { calls.push({ method, args }); }; + const sandbox = (state: string) => ({ id: "sbx_orca", name: "n", state, workspaceId: "ws_one", vmSandbox: true, createdAt: 1, lastUsedAt: 1 }); + const client = { + workspaces: { list: async () => { record("workspaces.list"); return [{ id: "ws_one", name: "Personal", createdAt: 1 }]; } }, + sandboxes: { + create: async (input: unknown) => { record("sandboxes.create", input); return sandbox(states.shift() ?? "running"); }, + inspect: async (id: string) => { record("sandboxes.inspect", id); return sandbox(states.shift() ?? "running"); }, + list: async () => { record("sandboxes.list"); return overrides.list ?? []; }, + delete: async (id: string) => { + record("sandboxes.delete", id); + if (overrides.deleteStatus) throw new BoxComputeError({ status: overrides.deleteStatus, code: "NOT_FOUND", message: "gone" }); + }, + execute: async (id: string, input: { argv: string[]; env?: Record }) => { + record("sandboxes.execute", id, input); + if (input.argv[2] === SERVE_SCRIPT) { + files.set("/workspace/.boxcompute/orca/recipe.json", new TextEncoder().encode(JSON.stringify({ + schemaVersion: 1, pairingCode, projectRoot: input.env?.BXC_ORCA_ROOT, + }))); + } + return { stdout: "", stderr: "", exitCode: 0, timedOut: false, stdoutTruncated: false, stderrTruncated: false }; + }, + }, + operations: { + start: async (id: string, input: { argv: string[]; env?: Record }) => { + record("operations.start", id, input); + return { operationId: `op_${"a".repeat(32)}`, state: "running", exitCode: null, stderrOffset: 0 }; + }, + wait: async (id: string, operationId: string) => { + record("operations.wait", id, operationId); + return { operationId, state: overrides.setupFails ? "completed" : "completed", exitCode: overrides.setupFails ? 1 : 0, stderrOffset: 12 }; + }, + output: async (id: string, operationId: string, options: unknown) => { + record("operations.output", id, operationId, options); + return { stream: "stderr", dataBase64: Buffer.from("clone failed").toString("base64"), offset: 0, nextOffset: 12, earliestOffset: 0, truncated: false }; + }, + }, + previews: { + create: async (id: string, input: unknown) => { + record("previews.create", id, input); + return { previewId, sandboxId: id, port: 6768, url: `https://${previewId}.bxcpreview.site`, expiresAt: "2026-11-23T04:00:00.000Z" }; + }, + }, + files: { + write: async (id: string, file: string, data: Uint8Array) => { record("files.write", id, file); files.set(file, data); }, + read: async (id: string, file: string) => { + record("files.read", id, file); + const data = files.get(file); + if (!data) throw new Error(`missing ${file}`); + return { data, offset: 0, nextOffset: data.length, fileSize: data.length, eof: true }; + }, + remove: async (id: string, file: string) => { record("files.remove", id, file); files.delete(file); }, + }, + }; + return { client: client as unknown as BoxCompute, calls, files }; +} + +function deps(client: BoxCompute, options: { + env?: NodeJS.ProcessEnv; stdin?: string; fetch?: typeof fetch; + run?: OrcaDependencies["run"]; +} = {}) { + const stdout = new PassThrough(); + const stderr = new PassThrough(); + let out = ""; + let err = ""; + stdout.on("data", (chunk) => { out += chunk; }); + stderr.on("data", (chunk) => { err += chunk; }); + const value: OrcaDependencies = { + client, connection, + fetch: options.fetch ?? ((async () => { throw new Error("no fetch expected"); }) as unknown as typeof fetch), + env: { BOXCOMPUTE_CONFIG_DIR: configDir, ORCA_VM_INSTANCE_ID: instanceId, ORCA_WORKSPACE_NAME: "fix login bug", ORCA_VERSION: "1.4.280", ...options.env }, + stdout, stderr, + readStdin: async () => options.stdin ?? "", + sleep: async () => undefined, + now: () => Date.parse("2026-11-23T03:00:00Z"), + run: options.run ?? (async (file, args) => { + if (file === "git" && args.join(" ") === "remote get-url origin") return "git@github.com:acme/widget.git"; + if (file === "gh") return "gho_from_gh"; + return null; + }), + }; + return { value, out: () => out, err: () => err }; +} + +const state = async () => JSON.parse(await readFile(path.join(configDir, "orca", `${instanceId}.json`), "utf8")); + +test("create makes one VM, keeps the token out of commands and prints only Orca's result", async () => { + const { client, calls } = fakeClient(); + const d = deps(client); + expect(await runOrca("create", [], d.value)).toBe(0); + + const created = calls.find((call) => call.method === "sandboxes.create")!.args[0] as Record; + expect(created).toEqual({ + workspaceId: "ws_one", vmSandbox: true, size: "large", + name: `fix-login-bug-${instanceId}`, idempotencyKey: `orca-${instanceId}`, + }); + // The token is written as a file, never into a command's arguments or environment. + expect(calls.find((call) => call.method === "files.write")?.args[1]).toBe("/workspace/.boxcompute/orca/git-token"); + const executions = calls.filter((call) => call.method === "sandboxes.execute" || call.method === "operations.start") + .map((call) => call.args[1] as { argv: string[]; env?: Record }); + expect(JSON.stringify(executions)).not.toContain("gho_from_gh"); + // The long install runs as a polled operation, never one execute call. + const setup = calls.find((call) => call.method === "operations.start")!.args[1] as { argv: string[]; env?: Record }; + expect(setup.argv[2]).toBe(SETUP_SCRIPT); + expect(setup.env).toEqual({ BXC_ORCA_VERSION: "1.4.280", BXC_ORCA_ROOT: "/workspace/projects/widget", BXC_ORCA_REPO_URL: "https://github.com/acme/widget.git" }); + const serve = executions.find((input) => input.argv[2] === SERVE_SCRIPT)!; + expect(serve.env).toEqual({ BXC_ORCA_ROOT: "/workspace/projects/widget", BXC_ORCA_ADDRESS: `wss://${previewId}.bxcpreview.site`, BXC_ORCA_INSTANCE: instanceId }); + // The pairing code is read from a file and removed, not taken from command output. + expect(calls.some((call) => call.method === "files.remove")).toBe(true); + + const lines = d.out().trim().split("\n"); + expect(lines).toHaveLength(1); + expect(JSON.parse(lines[0]!)).toEqual({ + schemaVersion: 1, pairingCode, projectRoot: "/workspace/projects/widget", + userData: { provider: "boxcompute", sandboxId: "sbx_orca", previewId }, + }); + expect(d.err()).not.toContain("secret-pairing"); + expect(await state()).toMatchObject({ instanceId, sandboxId: "sbx_orca", previewId }); + expect((await stat(path.join(configDir, "orca", `${instanceId}.json`))).mode & 0o077).toBe(0); +}); + +test("--size picks the VM size, and the environment overrides it", async () => { + const xl = fakeClient(); + await runOrca("create", ["--size", "xl"], deps(xl.client).value); + expect((xl.calls.find((call) => call.method === "sandboxes.create")!.args[0] as { size: string }).size).toBe("xl"); + await rm(path.join(configDir, "orca"), { recursive: true, force: true }); + const small = fakeClient(); + await runOrca("create", ["--size", "xl"], deps(small.client, { env: { BOXCOMPUTE_ORCA_SIZE: "small" } }).value); + expect((small.calls.find((call) => call.method === "sandboxes.create")!.args[0] as { size: string }).size).toBe("small"); +}); + +test("a retried create reuses the VM it already made", async () => { + const first = fakeClient(); + await runOrca("create", [], deps(first.client).value); + const again = fakeClient({ states: ["running"] }); + expect(await runOrca("create", [], deps(again.client).value)).toBe(0); + expect(again.calls.some((call) => call.method === "sandboxes.create")).toBe(false); +}); + +test("create refuses what it cannot run before creating anything", async () => { + const { client, calls } = fakeClient(); + await expect(runOrca("create", [], deps(client, { env: { ORCA_RECIPE_RESULT_SCHEMA_VERSION: "2" } }).value)).rejects.toThrow("provisioned-root"); + await expect(runOrca("create", [], deps(client, { run: async () => null }).value)).rejects.toThrow("no Git remote"); + await expect(runOrca("create", [], deps(client, { env: { BOXCOMPUTE_ORCA_SIZE: "huge" } }).value)).rejects.toThrow("BOXCOMPUTE_ORCA_SIZE"); + await expect(runOrca("create", ["--size", "huge"], deps(client).value)).rejects.toThrow("must be one of"); + await expect(runOrca("resume", ["--size", "xl"], deps(client).value)).rejects.toThrow("only to orca create"); + await expect(runOrca("create", [], deps(client, { env: { ORCA_VM_INSTANCE_ID: "" } }).value)).rejects.toThrow("ORCA_VM_INSTANCE_ID"); + expect(calls.some((call) => call.method === "sandboxes.create")).toBe(false); +}); + +test("a failed install names the VM and the last lines it printed", async () => { + const { client } = fakeClient({ setupFails: true }); + await expect(runOrca("create", [], deps(client).value)).rejects.toThrow(/clone failed\n\(BoxCompute VM sbx_orca, completed, exit 1\)/); +}); + +test("a public repository on another host clones without any token", async () => { + const { client, calls } = fakeClient(); + const d = deps(client, { run: async (file, args) => file === "git" && args[0] === "remote" && args[1] === "get-url" ? "https://gitlab.com/acme/tool.git" : file === "gh" ? "gho_never" : null }); + await runOrca("create", [], d.value); + expect(calls.some((call) => call.method === "files.write")).toBe(false); +}); + +test("suspend stops the VM and keep-open then leaves it alone", async () => { + const { client } = fakeClient(); + await runOrca("create", [], deps(client).value); + const stops: string[] = []; + const fetcher = (async (url: unknown) => { + stops.push(String(url)); + return new Response(JSON.stringify({ sandbox: { id: "sbx_orca", state: "cold", name: "n" }, stopped: true })); + }) as typeof fetch; + const lifecycle = JSON.stringify({ schemaVersion: 1, mode: "suspend", instanceId, recipeResult: { userData: { sandboxId: "sbx_orca" } } }); + expect(await runOrca("suspend", [], deps(client, { stdin: lifecycle, fetch: fetcher }).value)).toBe(0); + expect(stops).toEqual(["https://app.boxcompute.ai/api/v2/sandboxes/sbx_orca/stop"]); + expect(await state()).toMatchObject({ suspended: true }); + + const keep = deps(client, { fetch: (async () => { throw new Error("must not touch a sleeping VM"); }) as unknown as typeof fetch }); + expect(await runOrca("keep-open", [], keep.value, true)).toBe(0); + expect(JSON.parse(keep.out())).toEqual({ running: 0, vms: [{ instanceId, sandboxId: "sbx_orca", status: "asleep" }] }); +}); + +test("resume starts the VM and prints a fresh result", async () => { + const { client } = fakeClient(); + await runOrca("create", [], deps(client).value); + const resumed = fakeClient({ states: ["cold", "running"] }); + const starts: string[] = []; + const fetcher = (async (url: unknown) => { + starts.push(String(url)); + return new Response(JSON.stringify({ sandbox: { id: "sbx_orca", state: "pending", name: "n" } }), { status: 201 }); + }) as typeof fetch; + const d = deps(resumed.client, { stdin: JSON.stringify({ mode: "resume", instanceId }), fetch: fetcher }); + expect(await runOrca("resume", [], d.value)).toBe(0); + expect(starts).toEqual(["https://app.boxcompute.ai/api/v2/sandboxes/sbx_orca/start"]); + expect(JSON.parse(d.out()).pairingCode).toBe(pairingCode); + expect(await state()).toMatchObject({ suspended: false, previewId }); +}); + +test("keep-open keeps each awake VM's link and reports one that closed", async () => { + const { client } = fakeClient(); + await runOrca("create", [], deps(client).value); + const requests: { url: string; init?: RequestInit }[] = []; + let status = 200; + const fetcher = (async (url: unknown, init?: RequestInit) => { + requests.push({ url: String(url), init }); + return new Response("{}", { status }); + }) as typeof fetch; + const kept = deps(client, { fetch: fetcher }); + expect(await runOrca("keep-open", [], kept.value, true)).toBe(0); + expect(JSON.parse(kept.out())).toEqual({ running: 1, vms: [{ instanceId, sandboxId: "sbx_orca", status: "kept" }] }); + expect(requests[0]!.url).toBe(`https://app.boxcompute.ai/api/v2/sandboxes/sbx_orca/previews/${previewId}/keep-open`); + expect(requests[0]!.init?.method).toBe("POST"); + expect(requests[0]!.init?.redirect).toBe("error"); + expect(new Headers(requests[0]!.init?.headers).get("authorization")).toBe("Bearer bc_live_test"); + + status = 404; + const closed = deps(client, { fetch: fetcher }); + expect(await runOrca("keep-open", [], closed.value, true)).toBe(0); + expect(JSON.parse(closed.out()).vms[0].status).toBe("closed"); + + status = 500; + expect(await runOrca("keep-open", [], deps(client, { fetch: fetcher }).value, true)).toBe(1); +}); + +test("destroy deletes the recorded VM, finds one by name, and is fine with none", async () => { + const { client, calls } = fakeClient(); + await runOrca("create", [], deps(client).value); + const destroy = (stdin: string, c = client) => runOrca("destroy", [], deps(c, { stdin }).value); + expect(await destroy(JSON.stringify({ mode: "destroy", instanceId }))).toBe(0); + expect(calls.filter((call) => call.method === "sandboxes.delete").map((call) => call.args[0])).toEqual(["sbx_orca"]); + expect(await readdir(path.join(configDir, "orca"))).toEqual([]); + + // No state and no result: the VM named for this instance is the one deleted, and only it. + const named = fakeClient({ list: [{ id: "sbx_other", name: "unrelated" }, { id: "sbx_named", name: `ws-${instanceId}` }] }); + expect(await destroy(JSON.stringify({ mode: "destroy", instanceId }), named.client)).toBe(0); + expect(named.calls.filter((call) => call.method === "sandboxes.delete").map((call) => call.args[0])).toEqual(["sbx_named"]); + + const none = fakeClient({ list: [{ id: "sbx_other", name: "unrelated" }] }); + expect(await destroy(JSON.stringify({ mode: "destroy", instanceId }), none.client)).toBe(0); + expect(none.calls.some((call) => call.method === "sandboxes.delete")).toBe(false); + + const gone = fakeClient({ deleteStatus: 404 }); + expect(await destroy(JSON.stringify({ mode: "destroy", instanceId, recipeResult: { userData: { sandboxId: "sbx_gone" } } }), gone.client)).toBe(0); +}); + +test("remotes, names and versions", () => { + expect(httpsRemote("git@github.com:acme/widget.git")).toBe("https://github.com/acme/widget.git"); + expect(httpsRemote("ssh://git@github.com/acme/widget.git")).toBe("https://github.com/acme/widget.git"); + expect(httpsRemote("https://user:token@github.com/acme/widget.git")).toBe("https://github.com/acme/widget.git"); + expect(() => httpsRemote("/srv/git/widget")).toThrow(); + expect(repositoryName("https://github.com/acme/my%20repo.git")).toBe("my-20repo"); + expect(repositoryName("https://github.com/acme/.hidden.git")).toBe("hidden"); + const long = sandboxName("x".repeat(200), instanceId); + expect(long.length).toBeLessThanOrEqual(80); + expect(long.endsWith(instanceId)).toBe(true); + expect(sandboxName(undefined, instanceId)).toBe(instanceId); + expect(orcaVersion("1.4.300")).toBe("1.4.300"); + expect(orcaVersion("v1.4.300")).toBe("1.4.300"); + expect(orcaVersion("1.4.300; rm -rf /")).toBe("1.4.271"); +}); + +test("bxc orca prints its help and refuses unknown steps", async () => { + const io = { stdout: new PassThrough(), stderr: new PassThrough() }; + let out = ""; + io.stdout.on("data", (chunk) => { out += chunk; }); + expect(await runCli(["orca"], { io, env: {}, syncManagedSkills: async () => [] })).toBe(0); + expect(out).toContain("BOXCOMPUTE_ORCA_SIZE"); + await expect(runCli(["orca", "explode"], { io, env: {}, syncManagedSkills: async () => [], loadConnection: async () => connection })) + .rejects.toThrow("orca requires"); +});