From d765b0e2339084fc3a92d3b741b4780bc2332b5f Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Mon, 30 Nov 2026 04:05:34 +0530 Subject: [PATCH 01/10] fix: the live test script gets past the dashboard's same-origin check The dashboard API refuses POST requests without a matching Origin, so scripts/live.ts stopped at login. --- scripts/live.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/live.ts b/scripts/live.ts index e91322cb..5e4fc7d6 100644 --- a/scripts/live.ts +++ b/scripts/live.ts @@ -34,14 +34,14 @@ async function admin(method: string, path: string, body?: unknown): Pr if (!cookie) { const login = await fetch(`${base}/admin/api/login`, { method: "POST", - headers: { "content-type": "application/json" }, + headers: { origin: base, "content-type": "application/json" }, body: JSON.stringify({ key: (await Bun.file(keyFile!).text()).trim() }), }); cookie = login.headers.get("set-cookie")!.split(";")[0]!; } const response = await fetch(`${base}/admin/api${path}`, { method, - headers: { cookie, "content-type": "application/json" }, + headers: { cookie, origin: base, "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }); const value = (await response.json()) as T & { error?: string }; From 88b5a77abc51a2ccfa577d98a005c33f491dfcea Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Mon, 30 Nov 2026 04:05:35 +0530 Subject: [PATCH 02/10] feat: Vast.ai GPU VMs Each VM rents the cheapest verified on-demand Vast.ai machine with one GPU that fits the size, optionally a chosen GPU model. Commands, files and the T3 and OpenCode ports go over SSH with a key VM Bridge makes and adds to the account. Sleep stops the instance and wake starts it, keeping the disk. A script in each VM stops it after 60 minutes with no SSH connection, as a safety net when VM Bridge is down. --- apps/server/dev/workerd/checks.ts | 4 +- apps/server/src/pricing.ts | 22 +- apps/server/src/providers/index.ts | 2 + apps/server/src/providers/vast-ssh.ts | 248 +++++++++++ apps/server/src/providers/vast.ts | 579 +++++++++++++++++++++++++ apps/server/test/vast.test.ts | 241 ++++++++++ apps/web/src/Analytics.tsx | 1 + apps/web/src/assets/providers/vast.svg | 1 + apps/web/src/brand.tsx | 2 + packages/contracts/src/index.ts | 2 +- 10 files changed, 1098 insertions(+), 4 deletions(-) create mode 100644 apps/server/src/providers/vast-ssh.ts create mode 100644 apps/server/src/providers/vast.ts create mode 100644 apps/server/test/vast.test.ts create mode 100644 apps/web/src/assets/providers/vast.svg diff --git a/apps/server/dev/workerd/checks.ts b/apps/server/dev/workerd/checks.ts index a9527f7d..44652721 100644 --- a/apps/server/dev/workerd/checks.ts +++ b/apps/server/dev/workerd/checks.ts @@ -14,6 +14,7 @@ const fakeValues: Record> = { kubi: { apiKey: "kubi_fake" }, railway: { token: "00000000-0000-0000-0000-000000000000", environmentId: "00000000-0000-0000-0000-000000000000" }, superserve: { apiKey: "ss_live_fake" }, + vast: { apiKey: "vast_fake" }, }; export interface Result { @@ -25,7 +26,8 @@ export interface Result { function checks() { const open = (id: ProviderId) => providers[id].open({ values: fakeValues[id] }); - const verify = Object.keys(providers).map((id) => ({ name: id, call: () => open(id as ProviderId).verify() })); + // Vast.ai reaches VMs with the `ssh` command, which Workers do not have, so it is not checked here. + const verify = Object.keys(providers).filter((id) => id !== "vast").map((id) => ({ name: id, call: () => open(id as ProviderId).verify() })); return [ ...verify, // Railway's verify uses the SDK adapter's own fetch. These two go through the `railway` package. diff --git a/apps/server/src/pricing.ts b/apps/server/src/pricing.ts index d726b1f5..b051619c 100644 --- a/apps/server/src/pricing.ts +++ b/apps/server/src/pricing.ts @@ -33,6 +33,9 @@ const hoursPerMonth = 730; // Daytona's built-in snapshots VM Bridge creates from (see providers/daytona.ts) fix the reserved disk. const daytonaDisk = { small: 3, medium: 8, large: 10 }; +// Disk sizes of the Vast.ai sizes (see providers/vast.ts). +const vastDisk = { small: 40, medium: 60, large: 100 }; + const published: Record = { boat: { currency: "USD", @@ -140,11 +143,26 @@ const published: Record = { snapshots: "No separate price; saved changes bill as storage.", plans: "Developer: $20 a month, all of it usage. Pro: $250.", }, + vast: { + currency: "USD", + source: "https://vast.ai/pricing", + asOf: "2026-11-30", + running: { perSize: { small: 0.058, medium: 0.07, large: 0.109 } }, + asleep: { diskGibHour: 0.2 / hoursPerMonth, diskGib: vastDisk }, + storageGibMonth: 0.2, + sleeping: "A stopped VM pays only for its disk, about $0.20 per GB a month (some hosts charge $0.40).", + snapshots: "Not available.", + plans: "Prepaid credit, billed per second. At zero credit Vast.ai stops your VMs.", + caveat: "Prices are the cheapest offers for any GPU and change by host. Picking a GPU model costs more.", + }, }; -/** "2 vCPU, 4 GB" from a provider's size labels. Memory is taken as GiB, as the pricing pages bill it. */ +/** + * "2 vCPU, 4 GB" from a provider's size labels, or the least a size gets from labels such as Vast.ai's + * "1 GPU, 4+ vCPU, 8+ GB, 40 GB disk". Memory is taken as GiB, as the pricing pages bill it. + */ export function machine(provider: ProviderId, size: VmSize) { - const match = /^(\d+) vCPU, (\d+) GB$/.exec(providers[provider].sizes[size]); + const match = /(?:^|, )(\d+)\+? vCPU, (\d+)\+? GB(?:,|$)/.exec(providers[provider].sizes[size]); if (!match) throw new Error(`Unreadable size label for ${provider} ${size}.`); return { vcpu: Number(match[1]), gib: Number(match[2]) }; } diff --git a/apps/server/src/providers/index.ts b/apps/server/src/providers/index.ts index 5cd2e6e9..5ac30d31 100644 --- a/apps/server/src/providers/index.ts +++ b/apps/server/src/providers/index.ts @@ -13,6 +13,7 @@ import { boxdWeb, useBoxdWeb } from "./boxd-web.ts"; import { daytonaProvider } from "./daytona.ts"; import { e2bProvider } from "./e2b.ts"; import { kubiProvider } from "./kubi.ts"; +import { vastProvider } from "./vast.ts"; import { sleep } from "../runtime.ts"; import { notFound, retryNotFound, sdkDriver } from "./sdk.ts"; import { required, type Box, type ProviderDefinition } from "./types.ts"; @@ -313,6 +314,7 @@ export const providers: Record = { kubi: kubiProvider, railway: railwayProvider, superserve: superserveProvider, + vast: vastProvider, }; /** Whether VMs on this provider have a screen to watch (see watch/). */ diff --git a/apps/server/src/providers/vast-ssh.ts b/apps/server/src/providers/vast-ssh.ts new file mode 100644 index 00000000..06eb9f06 --- /dev/null +++ b/apps/server/src/providers/vast-ssh.ts @@ -0,0 +1,248 @@ +import { mkdirSync, rmSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { sleep } from "../runtime.ts"; + +/** + * SSH to Vast.ai instances through the `ssh` command on the computer VM Bridge runs on. Vast.ai has no API that runs + * commands (its own runs only `ls`, `rm` and `du`), and a container's ports are reachable only as plain HTTP on the + * host's public address, which would carry T3's and OpenCode's credentials in the clear. So commands and files go over + * SSH, and every port VM Bridge uses over an SSH tunnel to 127.0.0.1 here. Nothing on the instance is open but SSH. + */ + +export interface SshTarget { + host: string; + port: number; +} + +export interface RunOptions { + stdin?: Uint8Array; + signal?: AbortSignal; + /** Ends the local `ssh` after this long. The command itself is timed in the instance (see `vast.ts`). */ + timeoutMs?: number; + onStdout?(bytes: Uint8Array): void; + onStderr?(bytes: Uint8Array): void; +} + +export interface RunResult { + /** Null when the local `ssh` was ended: aborted or out of time. */ + exitCode: number | null; + stdout: Uint8Array; + stderr: string; +} + +/** How the provider reaches an instance. Tests use one that runs commands on this computer. */ +export interface Transport { + /** Runs `command` in the instance's login shell. Exit code 255 is SSH's own failure, such as an instance unreachable. */ + run(id: string, command: string, options?: RunOptions): Promise; + /** A port on 127.0.0.1 that reaches `port` in the instance. It stays the same, reconnecting as needed, until `close(id)`. */ + forward(id: string, port: number): Promise; + /** Ends the instance's tunnels, as when it sleeps or is deleted. */ + close(id: string): void; +} + +/** SSH's exit code for its own failures, as opposed to the command's. */ +export const sshFailed = 255; + +/** VM Bridge's folder, as `dataDir` in index.ts, which this module cannot import: Workers bundle the providers. */ +const vmbridgeHome = () => process.env.VMBRIDGE_HOME || join(homedir(), ".vmbridge"); + +/** Where VM Bridge keeps its Vast.ai SSH key, the instances' host keys and SSH's shared connections. */ +export const sshDir = () => join(vmbridgeHome(), "vast"); + +/** Why VM Bridge cannot use SSH here, or null when it can. */ +export function sshProblem() { + if (typeof Bun === "undefined") return "Vast.ai needs VM Bridge running on a computer, not on Cloudflare: it reaches VMs over SSH."; + if (!Bun.which("ssh") || !Bun.which("ssh-keygen")) return "Vast.ai needs the ssh command, which this computer does not have. Install OpenSSH."; + return null; +} + +/** VM Bridge's own key for Vast.ai instances, made on first use. Returns the public key. */ +export async function sshKey(dir = sshDir()) { + const path = join(dir, "id_ed25519"); + if (!(await Bun.file(`${path}.pub`).exists())) { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const made = Bun.spawn(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "vmbridge", "-f", path], { stdin: "ignore", stdout: "ignore", stderr: "pipe" }); + if ((await made.exited) !== 0) throw new Error(`Could not make an SSH key for Vast.ai: ${(await new Response(made.stderr).text()).trim()}`); + } + return { path, publicKey: (await Bun.file(`${path}.pub`).text()).trim() }; +} + +/** A free port on 127.0.0.1 for a tunnel, found by listening on port 0. */ +function freePort() { + const listener = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } }); + const { port } = listener; + listener.stop(true); + return port; +} + +/** Whether something listens on `port` here: the tunnel's `ssh` once it is connected. */ +const listening = (port: number) => + Bun.connect({ hostname: "127.0.0.1", port, socket: { data() {}, open: (socket) => void socket.end() } }).then( + () => true, + () => false, + ); + +async function drain(stream: ReadableStream, onChunk?: (bytes: Uint8Array) => void) { + const chunks: Uint8Array[] = []; + for await (const chunk of stream) { + chunks.push(chunk); + onChunk?.(chunk); + } + return Buffer.concat(chunks); +} + +/** Tunnel `ssh` processes, ended when VM Bridge exits so none hold a port after it. */ +const tunnels = new Set<{ kill(): void }>(); +let exitHook = false; + +/** + * Commands share one SSH connection per instance (OpenSSH's ControlMaster), so each one after the first starts in + * milliseconds rather than a handshake. Tunnels each keep their own connection and restart when it drops, on the same + * local port. Host keys are kept per instance: a host's public address and port can later belong to another instance. + */ +export function sshTransport(target: (id: string) => Promise, key: () => Promise<{ path: string }>, dir = sshDir()): Transport { + const open = new Map; stop(): void }>>(); + // A socket path can be at most 104 bytes on macOS (108 on Linux), and ssh makes the shared connection's socket at + // the path with %C as 40 characters, plus a 17 character suffix while it sets it up. A longer data folder would make + // every command fail, so there each command opens its own connection instead. + const control = join(dir, "c", "%C"); + const multiplex = + Buffer.byteLength(control) - "%C".length + 40 + 17 < 104 + ? ["-o", "ControlMaster=auto", "-o", `ControlPath=${control}`, "-o", "ControlPersist=120"] + : ["-o", "ControlMaster=no", "-o", "ControlPath=none"]; + + async function args(id: string, extra: string[]) { + const [{ host, port }, { path }] = await Promise.all([target(id), key()]); + mkdirSync(join(dir, "hosts"), { recursive: true, mode: 0o700 }); + mkdirSync(join(dir, "c"), { recursive: true, mode: 0o700 }); + return [ + "ssh", + "-i", + path, + "-p", + String(port), + "-o", + "IdentitiesOnly=yes", + "-o", + "BatchMode=yes", + "-o", + "StrictHostKeyChecking=accept-new", + "-o", + `UserKnownHostsFile=${join(dir, "hosts", id)}`, + "-o", + "ConnectTimeout=20", + "-o", + "ServerAliveInterval=15", + "-o", + "ServerAliveCountMax=4", + "-o", + "LogLevel=ERROR", + ...extra, + `root@${host}`, + ]; + } + + async function run(id: string, command: string, options: RunOptions = {}): Promise { + if (options.signal?.aborted) return { exitCode: null, stdout: new Uint8Array(), stderr: "" }; + const child = Bun.spawn([...(await args(id, multiplex)), command], { + stdin: options.stdin ? "pipe" : "ignore", + stdout: "pipe", + stderr: "pipe", + }); + let ended = false; + const end = () => { + ended = true; + child.kill(); + }; + options.signal?.addEventListener("abort", end, { once: true }); + const timer = options.timeoutMs === undefined ? undefined : setTimeout(end, options.timeoutMs); + try { + if (options.stdin && child.stdin) { + child.stdin.write(options.stdin); + await child.stdin.end(); + } + const [stdout, stderr, exitCode] = await Promise.all([drain(child.stdout, options.onStdout), drain(child.stderr, options.onStderr), child.exited]); + return { exitCode: ended ? null : exitCode, stdout, stderr: stderr.toString() }; + } finally { + clearTimeout(timer); + options.signal?.removeEventListener("abort", end); + } + } + + function tunnel(id: string, remote: number) { + const local = freePort(); + let stopped = false; + let child: ReturnType | undefined; + const handle = { kill: () => child?.kill() }; + tunnels.add(handle); + if (!exitHook) { + exitHook = true; + process.once("exit", () => { + for (const entry of tunnels) entry.kill(); + }); + } + let resolveReady = () => {}; + const ready = new Promise((resolve) => (resolveReady = resolve)); + void (async () => { + let wait = 1_000; + while (!stopped) { + const started = Date.now(); + try { + const command = await args(id, ["-N", "-o", "ExitOnForwardFailure=yes", "-o", "ControlMaster=no", "-o", "ControlPath=none", "-L", `127.0.0.1:${local}:127.0.0.1:${remote}`]); + if (stopped) break; + child = Bun.spawn(command, { stdin: "ignore", stdout: "ignore", stderr: "ignore" }); + // Ready once `ssh` listens, which it does only after it has connected and signed in. + void (async () => { + const until = Date.now() + 60_000; + while (!stopped && Date.now() < until && child?.exitCode === null) { + if (await listening(local)) return resolveReady(); + await sleep(200); + } + })(); + await child.exited; + } catch { + // The instance's address could not be read. Try again below. + } + if (stopped) break; + // A tunnel that held for a while starts over quickly. One that keeps failing waits longer, up to 15 s. + wait = Date.now() - started > 30_000 ? 1_000 : Math.min(wait * 2, 15_000); + await sleep(wait); + } + })(); + return { + local, + ready, + stop() { + stopped = true; + child?.kill(); + tunnels.delete(handle); + resolveReady(); + }, + }; + } + + return { + run, + + async forward(id, port) { + let forId = open.get(id); + if (!forId) open.set(id, (forId = new Map())); + let entry = forId.get(port); + if (!entry) forId.set(port, (entry = tunnel(id, port))); + // A caller waits only for the first connection. Its URL keeps working across later reconnects. + await Promise.race([entry.ready, sleep(60_000)]); + return entry.local; + }, + + close(id) { + for (const entry of open.get(id)?.values() ?? []) entry.stop(); + open.delete(id); + }, + }; +} + +/** Forgets an instance's host key once it is deleted. */ +export function forgetHost(id: string, dir = sshDir()) { + rmSync(join(dir, "hosts", id), { force: true }); +} diff --git a/apps/server/src/providers/vast.ts b/apps/server/src/providers/vast.ts new file mode 100644 index 00000000..837b4159 --- /dev/null +++ b/apps/server/src/providers/vast.ts @@ -0,0 +1,579 @@ +import { SandboxError, type ErrorCode } from "@opencoredev/sandbox-sdk"; +import { createHttpClient, type ExecInput, type ExecResult, type Fetch, type FileInfo, type Provider, type SandboxInfo } from "@opencoredev/sandbox-sdk/provider"; +import type { VmSize } from "@vmbridge/contracts"; +import { sleep } from "../runtime.ts"; +import { sdkDriver } from "./sdk.ts"; +import { forgetHost, sshFailed, sshKey, sshProblem, sshTransport, type SshTarget, type Transport } from "./vast-ssh.ts"; +import { required, type ProviderDefinition } from "./types.ts"; + +/** + * Vast.ai (vast.ai) over its REST API, as a sandbox-sdk provider. Vast.ai rents GPU machines from independent hosts, and + * each VM is a Docker container on one: VM Bridge rents the cheapest verified, on-demand offer that fits the size. + * + * Commands, files and ports go over SSH (see vast-ssh.ts). Sleep stops the container and wake starts it again on the + * same host, keeping the disk: memory and processes go, and T3 starts again on every wake. A host can rent the GPU to + * someone else meanwhile, and then the VM cannot wake until it is free again. + */ + +const apiUrl = "https://console.vast.ai/api"; +/** Ubuntu with CUDA matched to the host's driver, which Vast.ai's hosts usually have cached. */ +const image = "vastai/base-image:@vastai-automatic-tag"; +/** Marks the instances VM Bridge made: their label is this, then the SDK key and labels as JSON. */ +const labelPrefix = "vmbridge:"; +const keyLabel = "sandbox-sdk-key"; +const notFoundExit = 44; +/** How long an instance runs with no SSH connection from VM Bridge before it stops itself (see `onstart`). */ +const idleStopMinutes = 60; + +/** What each size rents: the least share of the host's CPU and memory with one GPU, and the disk VM Bridge asks for. */ +export const vastSizes: Record = { + small: { cores: 4, ramMb: 8_000, diskGb: 40 }, + medium: { cores: 8, ramMb: 16_000, diskGb: 60 }, + large: { cores: 16, ramMb: 32_000, diskGb: 100 }, +}; + +/** The GPU field's choices, as Vast.ai names the cards. The empty one, the default, is the cheapest that fits. */ +const gpuModels: Record = { + "": [], + "RTX 3060": ["RTX 3060"], + "RTX 3090": ["RTX 3090"], + "RTX 4090": ["RTX 4090"], + "RTX 5090": ["RTX 5090"], + A100: ["A100 PCIE", "A100 SXM4", "A100X"], + H100: ["H100 PCIE", "H100 SXM", "H100 NVL"], +}; + +/** + * Runs as the container starts, on every wake too. Vast.ai's image starts tmux on SSH logins, which this turns off. + * It also stops the instance if VM Bridge goes away, as other providers' idle timers do: VM Bridge keeps an SSH + * connection open to every VM it has awake, so an hour with none means it is down. The instance stops itself with + * the key Vast.ai gives every container, which can only start, stop or delete that one instance. + */ +export const onstart = `touch /root/.no_auto_tmux +cat > /root/vmbridge-idle.sh <<'EOF' +#!/bin/bash +[ -n "$CONTAINER_API_KEY" ] && [ -n "$CONTAINER_ID" ] || exit 0 +idle=0 +while sleep 60; do + if awk '$4 == "01" && $2 ~ /:0016$/ { found = 1 } END { exit !found }' /proc/net/tcp /proc/net/tcp6 2>/dev/null; then idle=0; else idle=$((idle + 1)); fi + if [ "$idle" -ge ${idleStopMinutes} ]; then + curl -fsS -X PUT -H "Authorization: Bearer $CONTAINER_API_KEY" -H "Content-Type: application/json" -d '{"state":"stopped"}' "https://console.vast.ai/api/v0/instances/$CONTAINER_ID/" && exit 0 + fi +done +EOF +setsid nohup bash /root/vmbridge-idle.sh >/dev/null 2>&1 < /dev/null &`; + +/** Hosts set an end date on each offer, when they may take the machine back. VM Bridge skips offers ending sooner. */ +const leastDurationS = 14 * 86_400; + +interface Instance { + id: number; + label: string | null; + actual_status: string | null; + intended_status?: string | null; + cur_state?: string | null; + status_msg?: string | null; + public_ipaddr?: string | null; + ssh_host?: string | null; + ssh_port?: number | null; + ports?: Record | null; + start_date?: number | null; +} + +interface Offer { + id: number; + gpu_name: string; + dph_total: number; +} + +export interface VastOptions { + apiKey: string; + /** A choice from the GPU field, or empty for the cheapest. */ + gpu?: string; + /** For tests. Default: the global `fetch`. */ + fetch?: Fetch; + /** For tests. Default: SSH (vast-ssh.ts). */ + transport?: Transport; + /** For tests. Default: VM Bridge's own key. */ + publicKey?: () => Promise; + /** For tests: how often to read an instance's state while waiting, and how long to wait. */ + timing?: Partial; +} + +const defaultTiming = { + pollMs: 5_000, + /** A new instance pulls its image first. On a host without it cached, that takes minutes. */ + bootMs: 12 * 60_000, + /** A start waits in `scheduling` while the host's GPU is rented to someone else, possibly for good. */ + schedulingMs: 2 * 60_000, + /** SSH starts a little after the container. */ + sshMs: 3 * 60_000, + stopMs: 2 * 60_000, +}; + +export type VastProvider = Provider, "pause" | "size"> & { + /** Throws a readable error when the key is refused, or this computer cannot run SSH. */ + verify(): Promise; +}; + +const fail = (message: string, code: ErrorCode, sandboxId?: string) => new SandboxError(message, { code, provider: "vast", sandboxId }); + +/** ssh's own last line on a failed connection, as ": reason", with any IPv4 address left out. */ +function sshReason(stderr: string) { + const line = stderr.trim().split("\n").at(-1)?.trim().replace(/\b\d{1,3}(?:\.\d{1,3}){3}\b/g, "the host"); + return line ? `: ${line}` : ""; +} + +const unreachable = (id: string, stderr: string) => fail(`Could not reach the Vast.ai instance over SSH${sshReason(stderr)}`, "unavailable", id); +const quote = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`; + +/** Vast.ai's states as the SDK's. A container stopped, starting, or on a host that went offline cannot be used. */ +const stateOf = (instance: Instance): SandboxInfo["state"] => (instance.actual_status === "running" && instance.intended_status !== "stopped" ? "running" : "paused"); + +/** The SDK key and labels VM Bridge wrote into the instance's label, or null for an instance it did not make. */ +export function parseLabel(label: string | null) { + if (!label?.startsWith(labelPrefix)) return null; + try { + const parsed: unknown = JSON.parse(label.slice(labelPrefix.length)); + if (typeof parsed !== "object" || parsed === null) return null; + const entries = Object.entries(parsed).filter((entry): entry is [string, string] => typeof entry[1] === "string"); + return Object.fromEntries(entries); + } catch { + return null; + } +} + +function info(instance: Instance, labels: Record): SandboxInfo { + const { [keyLabel]: key, ...rest } = labels; + return { id: String(instance.id), key, labels: rest, state: stateOf(instance), createdAt: Math.round((instance.start_date ?? 0) * 1000) }; +} + +/** The instance's SSH address: direct to the host when it maps port 22, else through Vast.ai's SSH proxy. */ +export function sshTarget(instance: Instance): SshTarget | null { + const direct = instance.ports?.["22/tcp"]?.[0]?.HostPort; + if (instance.public_ipaddr && direct) return { host: instance.public_ipaddr.trim(), port: Number(direct) }; + if (instance.ssh_host && instance.ssh_port) return { host: instance.ssh_host, port: instance.ssh_port }; + return null; +} + +/** + * The command line for an SDK exec: in its folder, with its variables, ended by `timeout` in the instance when it runs + * too long. Its stdin is SSH's. The tag names it, so an abort can end it and its children. + */ +export function commandLine(input: Pick, tag: string) { + const exports = Object.entries(input.env).map(([name, value]) => { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw fail(`Invalid environment variable name: ${name}`, "invalid_argument"); + return `export ${name}=${quote(value)}\n`; + }); + // A missing cwd fails the command (exit 2), not the call. + const script = `# ${tag}\ncd -- ${quote(input.cwd)} || exit 2\n${exports.join("")}exec sh -c ${quote(input.command)}`; + const seconds = (input.timeoutMs / 1000).toFixed(3); + return `if command -v timeout >/dev/null 2>&1; then exec timeout -k 2 ${seconds}s sh -c ${quote(script)}; else exec sh -c ${quote(script)}; fi`; +} + +/** + * Run on every new instance before VM Bridge uses it: the folder the SDK runs commands in, no tmux on SSH logins + * (Vast.ai's image starts one), and the tools VM Bridge's setup needs if the image lacks any. + */ +const prepareScript = `set -e +mkdir -p /workspace /tmp/.sandbox-sdk +touch /root/.no_auto_tmux +missing="" +for tool in curl git pkill setsid timeout; do command -v "$tool" >/dev/null 2>&1 || missing=1; done +if [ -n "$missing" ]; then + export DEBIAN_FRONTEND=noninteractive + apt-get update -qq && apt-get install -y -qq curl git procps util-linux coreutils >/dev/null +fi`; + +export function vast(options: VastOptions): VastProvider { + const { apiKey } = options; + const timing = { ...defaultTiming, ...options.timing }; + const gpuNames = gpuModels[options.gpu ?? ""] ?? []; + const makeClient = (retries: number) => + createHttpClient({ + provider: "vast", + label: "Vast.ai", + planes: { api: { baseUrl: apiUrl, auth: () => ({ authorization: `Bearer ${apiKey}` }) } }, + defaultPlane: "api", + fetch: options.fetch, + timeoutMs: 30_000, + retries, + // Vast.ai allows about one call a second on each endpoint, and answers 429 past that. + backoffMs: 1_000, + secrets: () => [apiKey], + authHint: "Create a key at cloud.vast.ai/manage-keys.", + // Vast.ai answers a refused key with 404 and `{"error":"auth_error"}`. + mapError: (failure) => { + const body = failure.kind === "status" ? failure.body.json : undefined; + return typeof body === "object" && body !== null && !Array.isArray(body) && body.error === "auth_error" ? "auth" : undefined; + }, + }); + const client = makeClient(3); + // Renting is never sent twice: a retried PUT after a lost answer could rent a second machine. + const renting = makeClient(0); + + type Method = "GET" | "POST" | "PUT" | "DELETE"; + const json = async (method: Method, path: string, sandboxId?: string, body?: unknown, query?: Record) => + (await client.request({ method, path, sandboxId, body, query })).json() as T; + + async function instance(id: string) { + const { instances } = await json<{ instances: Instance | null }>("GET", `/v0/instances/${encodeURIComponent(id)}/`, id); + // Vast.ai answers an unknown or deleted instance with null. + if (!instances || instances.actual_status === "destroyed") throw fail("The Vast.ai instance was deleted", "not_found", id); + return instances; + } + + /** Every instance on the account VM Bridge made, with the labels it wrote. */ + async function mine() { + const found: { instance: Instance; labels: Record }[] = []; + let after: string | undefined; + do { + const page = await json<{ instances: Instance[]; next_token?: string | null }>("GET", "/v1/instances/", undefined, undefined, { limit: 25, after_token: after }); + for (const entry of page.instances) { + const labels = parseLabel(entry.label); + if (labels) found.push({ instance: entry, labels }); + } + after = page.next_token ?? undefined; + } while (after); + return found; + } + + const targets = new Map>(); + /** Read from the API once per wake: a start can move SSH to another port. */ + function target(id: string) { + let known = targets.get(id); + if (!known) { + known = instance(id).then((current) => { + const found = sshTarget(current); + if (!found) throw fail("The Vast.ai instance has no SSH address yet", "unavailable", id); + return found; + }); + targets.set(id, known); + known.catch(() => targets.delete(id)); + } + return known; + } + + const transport = + options.transport ?? + sshTransport( + (id) => target(id), + () => sshKey(), + ); + const publicKey = options.publicKey ?? (async () => (await sshKey()).publicKey); + + /** Runs a short command and returns its stdout. Any failure is the operation's failure. */ + async function raw(id: string, command: string, stdin?: Uint8Array) { + const result = await transport.run(id, command, { stdin, timeoutMs: 120_000 }); + if (result.exitCode === sshFailed) throw unreachable(id, result.stderr); + if (result.exitCode !== 0) throw fail("Guest operation failed", "provider", id); + return result.stdout; + } + + /** + * Waits until the instance runs and answers over SSH. Throws, with the reason, on a state it cannot leave. A stopped + * container reads `exited`, so a wake counts that as a failure only once the instance has left it. + */ + async function untilReady(id: string, deadlineMs: number, waking = false) { + const deadline = Date.now() + deadlineMs; + let scheduling: number | undefined; + let left = !waking; + for (;;) { + const current = await instance(id); + const status = current.actual_status ?? ""; + if (status !== "exited" && status !== "stopped") left = true; + if ((status === "exited" && left) || status === "offline") { + throw fail(`The Vast.ai machine ${status === "exited" ? "stopped its container" : "went offline"} while starting`, "unavailable", id); + } + if (current.cur_state === "scheduling" || status === "scheduling") scheduling ??= Date.now(); + if (scheduling !== undefined && Date.now() - scheduling > timing.schedulingMs) { + throw fail("The GPU on this Vast.ai machine is rented to someone else. The VM can wake once it is free again.", "quota", id); + } + let sshError: string | undefined; + if (status === "running" && sshTarget(current)) { + targets.delete(id); + const ssh = await transport.run(id, "true", { timeoutMs: 30_000 }).catch(() => null); + if (ssh?.exitCode === 0) return current; + sshError = sshReason(ssh?.stderr ?? ""); + } + if (Date.now() > deadline) { + if (sshError !== undefined) throw fail(`The Vast.ai machine runs but did not answer over SSH${sshError}`, "timeout", id); + throw fail("The Vast.ai machine did not start in time", "timeout", id); + } + await sleep(timing.pollMs); + } + } + + /** Adds VM Bridge's SSH key to the account, which gives it to every instance made after. */ + async function registerKey(key: string) { + const listed = await json("GET", "/v0/ssh/"); + const keys = Array.isArray(listed) ? listed : typeof listed === "object" && listed && "keys" in listed && Array.isArray(listed.keys) ? listed.keys : []; + const body = key.split(" ").slice(0, 2).join(" "); + const known = keys.some((entry: unknown) => typeof entry === "object" && entry && "public_key" in entry && String(entry.public_key).includes(body)); + const knownAs = keys.some((entry: unknown) => typeof entry === "object" && entry && "ssh_key" in entry && String(entry.ssh_key).includes(body)); + if (!known && !knownAs) await json("POST", "/v0/ssh/", undefined, { ssh_key: key }); + } + + async function offers(size: VmSize) { + const { cores, ramMb, diskGb } = vastSizes[size]; + const { offers: found } = await json<{ offers: Offer[] }>("POST", "/v0/bundles/", undefined, { + verified: { eq: true }, + external: { eq: false }, + rentable: { eq: true }, + rented: { eq: false }, + num_gpus: { eq: 1 }, + // SSH straight to the host, which Vast.ai calls faster and more reliable than its proxy. + direct_port_count: { gte: 1 }, + disk_space: { gte: diskGb }, + inet_down: { gte: 200 }, + reliability2: { gte: 0.97 }, + cpu_cores_effective: { gte: cores }, + cpu_ram: { gte: ramMb }, + duration: { gte: leastDurationS }, + ...(gpuNames.length ? { gpu_name: { in: gpuNames } } : {}), + order: [["dph_total", "asc"]], + type: "on-demand", + allocated_storage: diskGb, + limit: 5, + }); + if (!found.length) throw fail("Vast.ai has no machine for this size right now. Try another size or GPU, or try again later.", "quota"); + return found; + } + + async function destroy(id: string) { + transport.close(id); + targets.delete(id); + try { + await json("DELETE", `/v0/instances/${encodeURIComponent(id)}/`, id); + } catch (error) { + if (!(error instanceof SandboxError && error.code === "not_found")) throw error; + } + forgetHost(id); + } + + async function create(input: Parameters[0]): Promise { + if (input.from !== undefined) throw fail("Vast.ai snapshots are not supported here", "unsupported"); + if (Object.keys(input.env ?? {}).length > 0) throw fail("Vast.ai sets no environment at create here", "unsupported"); + const size = typeof input.size === "string" ? input.size : "small"; + const key = await publicKey(); + await registerKey(key); + const labels = { ...input.labels, ...(input.key ? { [keyLabel]: input.key } : {}) }; + const label = labelPrefix + JSON.stringify(labels); + let lastError: unknown; + // Another renter can take an offer first, and a host can fail to start the container. Each try rents the next offer. + for (const offer of (await offers(size)).slice(0, 3)) { + let id: string; + try { + const body = { + client_id: "me", + image, + disk: vastSizes[size].diskGb, + label, + runtype: "ssh_direct", + onstart, + // A taken offer fails here, rather than leaving a stopped instance waiting for the GPU. + cancel_unavail: true, + }; + const response = await renting.request({ method: "PUT", path: `/v0/asks/${offer.id}/`, body }); + const rented = response.json() as { new_contract?: number }; + if (!rented.new_contract) throw fail("Vast.ai did not rent the machine", "provider"); + id = String(rented.new_contract); + } catch (error) { + lastError = error; + // A lost answer may still have rented it. The label says. + const found = input.key ? (await mine().catch(() => [])).find((entry) => entry.labels[keyLabel] === input.key) : undefined; + if (!found) continue; + id = String(found.instance.id); + } + try { + await json("POST", `/v0/instances/${encodeURIComponent(id)}/ssh/`, id, { ssh_key: key }).catch(() => {}); + const ready = await untilReady(id, timing.bootMs); + await raw(id, prepareScript); + return info(ready, labels); + } catch (error) { + lastError = error; + await destroy(id).catch(() => {}); + } + } + throw lastError ?? fail("Vast.ai did not rent a machine", "provider"); + } + + async function exec(id: string, input: ExecInput): Promise { + if (input.signal?.aborted) return { exitCode: null, timedOut: true }; + const tag = `vmbridge-exec-${crypto.randomUUID()}`; + const stdout = new TextDecoder(); + const stderr = new TextDecoder(); + let aborted = false; + const onAbort = () => { + aborted = true; + // `[v]` keeps the pattern from matching the kill itself, and `timeout` leads the command's process group. + const pattern = quote(`[v]${tag.slice(1)}`); + void transport.run(id, `for p in $(pgrep -f ${pattern}); do kill -9 -"$p" 2>/dev/null; kill -9 "$p" 2>/dev/null; done; true`, { timeoutMs: 30_000 }).catch(() => {}); + }; + input.signal?.addEventListener("abort", onAbort, { once: true }); + const started = Date.now(); + try { + const result = await transport.run(id, commandLine(input, tag), { + stdin: input.stdin === undefined ? undefined : new TextEncoder().encode(input.stdin), + signal: input.signal, + // The instance's `timeout` ends it first. This only covers SSH hanging. + timeoutMs: input.timeoutMs + 30_000, + onStdout: (bytes) => input.onChunk({ stream: "stdout", text: stdout.decode(bytes, { stream: true }) }), + onStderr: (bytes) => input.onChunk({ stream: "stderr", text: stderr.decode(bytes, { stream: true }) }), + }); + if (aborted || result.exitCode === null) return { exitCode: null, timedOut: true }; + if (result.exitCode === sshFailed) throw unreachable(id, result.stderr); + // 124 is `timeout`'s own exit code, 137 its kill after the grace period. + const timedOut = (result.exitCode === 124 || result.exitCode === 137) && Date.now() - started >= input.timeoutMs; + return { exitCode: timedOut ? null : result.exitCode, timedOut }; + } finally { + input.signal?.removeEventListener("abort", onAbort); + } + } + + /** Runs a file command that exits `notFoundExit` when the path does not exist. */ + async function fileCommand(id: string, command: string, stdin?: Uint8Array) { + const result = await transport.run(id, command, { stdin, timeoutMs: 10 * 60_000 }); + if (result.exitCode === notFoundExit) throw fail("File does not exist", "file_not_found", id); + if (result.exitCode === sshFailed) throw unreachable(id, result.stderr); + if (result.exitCode !== 0) throw fail("Guest operation failed", "provider", id); + return result.stdout; + } + const exists = (path: string) => `[ -e ${quote(path)} ] || [ -L ${quote(path)} ] || exit ${notFoundExit}`; + + async function stop(id: string) { + transport.close(id); + targets.delete(id); + const current = await instance(id); + if (current.actual_status !== "running" && current.intended_status === "stopped") return; + await json("PUT", `/v0/instances/${encodeURIComponent(id)}/`, id, { state: "stopped" }); + const deadline = Date.now() + timing.stopMs; + while (Date.now() < deadline && (await instance(id)).actual_status === "running") await sleep(timing.pollMs); + } + + async function start(id: string) { + targets.delete(id); + await json("PUT", `/v0/instances/${encodeURIComponent(id)}/`, id, { state: "running" }); + try { + await untilReady(id, timing.sshMs + timing.schedulingMs, true); + } catch (error) { + // A start left waiting for the GPU would take it whenever it frees, billing from then with nobody using it. + if (error instanceof SandboxError && error.code === "quota") await json("PUT", `/v0/instances/${encodeURIComponent(id)}/`, id, { state: "stopped" }).catch(() => {}); + throw error; + } + } + + return { + name: "vast", + keyMode: "best-effort", + capabilities: new Set(["pause", "size"] as const), + + async verify() { + const problem = sshProblem(); + if (problem) throw fail(problem, "unsupported"); + await json("GET", "/v0/users/current/"); + }, + + create, + + find: async (key) => { + const found = (await mine()).find((entry) => entry.labels[keyLabel] === key); + return found && info(found.instance, found.labels); + }, + + connect: async (id) => { + const current = await instance(id); + return info(current, parseLabel(current.label) ?? {}); + }, + + list: async (labels) => + (await mine()) + .filter((entry) => keyLabel in entry.labels && Object.entries(labels).every(([name, value]) => entry.labels[name] === value)) + .map((entry) => info(entry.instance, entry.labels)), + + destroy, + exec, + + files: { + writeCreatesParents: true, + writeSupportsMode: true, + read: (id, path) => fileCommand(id, `${exists(path)}; exec cat -- ${quote(path)}`), + write: async (id, path, data, writeOptions) => { + const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) || "/" : "."; + const mode = writeOptions?.mode === undefined ? "" : ` && chmod ${writeOptions.mode.toString(8)} -- ${quote(path)}`; + await fileCommand(id, `mkdir -p -- ${quote(dir)} && cat > ${quote(path)}${mode}`, data); + }, + stat: async (id, path) => { + const out = new TextDecoder().decode(await fileCommand(id, `${exists(path)}; stat -c '%F|%s|%Y' -- ${quote(path)}`)).trim(); + const [type = "", size = "0", modified = "0"] = out.split("|"); + return { + path, + type: type === "directory" ? "directory" : type === "symbolic link" ? "symlink" : "file", + size: Number(size), + modifiedAt: Number(modified) * 1000, + }; + }, + list: async (id, path) => { + const out = new TextDecoder().decode( + await fileCommand(id, `${exists(path)}; find ${quote(path)} -mindepth 1 -maxdepth 1 -printf '%y\\t%s\\t%T@\\t%f\\0'`), + ); + const base = path.replace(/\/+$/, ""); + return out + .split("\0") + .filter(Boolean) + .map((line): FileInfo => { + const [type = "f", size = "0", modified = "0", ...name] = line.split("\t"); + return { + path: `${base}/${name.join("\t")}`, + type: type === "d" ? "directory" : type === "l" ? "symlink" : "file", + size: Number(size), + modifiedAt: Math.round(Number(modified) * 1000), + }; + }); + }, + mkdir: async (id, path) => void (await raw(id, `mkdir -p -- ${quote(path)}`)), + remove: async (id, path, { recursive }) => void (await fileCommand(id, `${exists(path)}; rm -f${recursive ? "r" : ""} -- ${quote(path)}`)), + }, + + // A tunnel from this computer: nothing in the instance is open to the internet, so the URL needs no credential. + previewUrl: async (id, port) => ({ url: `http://127.0.0.1:${await transport.forward(id, port)}` }), + + native: () => ({}), + + pause: stop, + resume: start, + }; +} + +export const vastProvider: ProviderDefinition = { + id: "vast", + label: "Vast.ai", + website: "https://vast.ai", + fields: [ + { key: "apiKey", label: "API key", kind: "secret", required: true, help: "Create a key at cloud.vast.ai/manage-keys." }, + { + key: "gpu", + label: "GPU", + kind: "select", + required: false, + options: Object.keys(gpuModels).map((value) => ({ value, label: value || "Cheapest available" })), + }, + ], + features: { + // A stopped container keeps its disk. Memory and processes go, and T3 starts again on wake. + sleep: "stop", + keepsDisk: true, + keepsMemory: false, + }, + sizes: { + small: "1 GPU, 4+ vCPU, 8+ GB, 40 GB disk", + medium: "1 GPU, 8+ vCPU, 16+ GB, 60 GB disk", + large: "1 GPU, 16+ vCPU, 32+ GB, 100 GB disk", + }, + defaultSize: "small", + + open(config) { + const provider = vast({ apiKey: required(config, "apiKey", "Vast.ai API key"), gpu: config.values.gpu }); + return { ...sdkDriver({ id: "vast", provider, sleep: "pause" }), verify: provider.verify }; + }, +}; diff --git a/apps/server/test/vast.test.ts b/apps/server/test/vast.test.ts new file mode 100644 index 00000000..3d47a61b --- /dev/null +++ b/apps/server/test/vast.test.ts @@ -0,0 +1,241 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { SandboxError } from "@opencoredev/sandbox-sdk"; +import { parseLabel, sshTarget, vast } from "../src/providers/vast.ts"; +import type { RunOptions, RunResult, Transport } from "../src/providers/vast-ssh.ts"; + +interface Call { + method: string; + path: string; + query: URLSearchParams; + body: unknown; +} + +type Answer = { status?: number; json?: unknown }; + +/** A fake Vast.ai API: `route` answers each call, and every call is recorded. */ +function fakeApi(route: (call: Call) => Answer | undefined) { + const calls: Call[] = []; + const fetch = async (input: string, init: RequestInit) => { + const url = new URL(input); + const body = init.body ? JSON.parse(String(init.body)) : undefined; + const call = { method: init.method ?? "GET", path: url.pathname.replace(/^\/api/, ""), query: url.searchParams, body }; + calls.push(call); + const answer = route(call) ?? { json: { success: true } }; + return new Response(JSON.stringify(answer.json ?? {}), { status: answer.status ?? 200, headers: { "content-type": "application/json" } }); + }; + return { calls, fetch }; +} + +/** A transport that answers every command with `exit`, recording them. */ +function recordingTransport(exit = 0) { + const commands: string[] = []; + const transport: Transport = { + run: async (_id, command) => { + commands.push(command); + return { exitCode: exit, stdout: new Uint8Array(), stderr: "" }; + }, + forward: async (_id, port) => port + 10_000, + close: () => {}, + }; + return { commands, transport }; +} + +/** A transport that runs commands in a shell on this computer, as SSH would in the instance. */ +const localTransport: Transport = { + async run(_id, command, options: RunOptions = {}): Promise { + const child = Bun.spawn(["bash", "-c", command], { stdin: options.stdin ? "pipe" : "ignore", stdout: "pipe", stderr: "pipe" }); + if (options.stdin && child.stdin) { + child.stdin.write(options.stdin); + await child.stdin.end(); + } + const read = async (stream: ReadableStream, on?: (bytes: Uint8Array) => void) => { + const chunks: Uint8Array[] = []; + for await (const chunk of stream) { + chunks.push(chunk); + on?.(chunk); + } + return Buffer.concat(chunks); + }; + const [stdout, stderr, exitCode] = await Promise.all([read(child.stdout, options.onStdout), read(child.stderr, options.onStderr), child.exited]); + return { exitCode, stdout, stderr: stderr.toString() }; + }, + forward: async (_id, port) => port, + close: () => {}, +}; + +const timing = { pollMs: 1, bootMs: 2_000, schedulingMs: 30, sshMs: 2_000, stopMs: 100 }; +const publicKey = async () => "ssh-ed25519 AAAAvmbridge vmbridge"; + +const instance = (status: string | null, extra: Record = {}) => ({ + id: 7, + label: 'vmbridge:{"vmbridge":"b1","sandbox-sdk-key":"vm-1"}', + actual_status: status, + intended_status: "running", + public_ipaddr: "203.0.113.5\n", + ssh_host: "ssh4.vast.ai", + ssh_port: 31000, + ports: { "22/tcp": [{ HostIp: "0.0.0.0", HostPort: "40022" }] }, + start_date: 1_700_000_000, + ...extra, +}); + +const offers = { offers: [{ id: 101, gpu_name: "GTX 1070", dph_total: 0.058 }, { id: 102, gpu_name: "GTX 1660 S", dph_total: 0.067 }] }; + +describe("Vast.ai instances", () => { + test("a new VM rents the cheapest offer that fits, moving on when one is taken, and is ready once SSH answers", async () => { + let polls = 0; + const { calls, fetch } = fakeApi((call) => { + if (call.path === "/v0/ssh/" && call.method === "GET") return { json: [] }; + if (call.path === "/v0/bundles/") return { json: offers }; + if (call.path === "/v0/asks/101/") return { status: 400, json: { success: false, error: "invalid_args", msg: "no_such_ask" } }; + if (call.path === "/v1/instances/") return { json: { instances: [], next_token: null } }; + if (call.path === "/v0/asks/102/") return { json: { success: true, new_contract: 7 } }; + if (call.path === "/v0/instances/7/" && call.method === "GET") return { json: { instances: instance(polls++ < 2 ? "loading" : "running") } }; + return undefined; + }); + const { commands, transport } = recordingTransport(); + const provider = vast({ apiKey: "vast_secret", gpu: "A100", fetch, transport, publicKey, timing }); + + const info = await provider.create({ key: "vm-1", size: "medium", labels: { vmbridge: "b1" } }); + + expect(info).toEqual({ id: "7", key: "vm-1", labels: { vmbridge: "b1" }, state: "running", createdAt: 1_700_000_000_000 }); + expect(calls.find((call) => call.method === "POST" && call.path === "/v0/ssh/")?.body).toEqual({ ssh_key: "ssh-ed25519 AAAAvmbridge vmbridge" }); + const search = calls.find((call) => call.path === "/v0/bundles/")!.body as Record; + expect(search).toMatchObject({ + cpu_cores_effective: { gte: 8 }, + cpu_ram: { gte: 16_000 }, + disk_space: { gte: 60 }, + gpu_name: { in: ["A100 PCIE", "A100 SXM4", "A100X"] }, + type: "on-demand", + order: [["dph_total", "asc"]], + }); + const rent = calls.find((call) => call.path === "/v0/asks/102/")!.body as Record; + expect(rent).toMatchObject({ disk: 60, runtype: "ssh_direct", cancel_unavail: true, label: 'vmbridge:{"vmbridge":"b1","sandbox-sdk-key":"vm-1"}' }); + // The taken offer was tried once, never sent again. + expect(calls.filter((call) => call.path === "/v0/asks/101/")).toHaveLength(1); + expect(calls.some((call) => call.method === "POST" && call.path === "/v0/instances/7/ssh/")).toBe(true); + expect(commands.at(-1)).toContain("mkdir -p /workspace"); + }); + + test("a machine whose container stops while starting is deleted, and the next offer is rented", async () => { + let rented = 0; + const { calls, fetch } = fakeApi((call) => { + if (call.path === "/v0/ssh/" && call.method === "GET") return { json: [{ id: 1, public_key: "ssh-ed25519 AAAAvmbridge vmbridge" }] }; + if (call.path === "/v0/bundles/") return { json: offers }; + if (call.path.startsWith("/v0/asks/")) return { json: { success: true, new_contract: 7 + rented++ } }; + if (call.path === "/v0/instances/7/" && call.method === "GET") return { json: { instances: instance("exited") } }; + if (call.path === "/v0/instances/8/" && call.method === "GET") return { json: { instances: { ...instance("running"), id: 8 } } }; + return undefined; + }); + const provider = vast({ apiKey: "vast_secret", fetch, transport: recordingTransport().transport, publicKey, timing }); + + const info = await provider.create({ key: "vm-1", size: "small", labels: { vmbridge: "b1" } }); + + expect(info.id).toBe("8"); + expect(calls.some((call) => call.method === "DELETE" && call.path === "/v0/instances/7/")).toBe(true); + // The key was on the account already. + expect(calls.some((call) => call.method === "POST" && call.path === "/v0/ssh/")).toBe(false); + }); + + test("lists only the instances VM Bridge made with these labels, and finds one by its key", async () => { + const { calls, fetch } = fakeApi((call) => { + if (call.path !== "/v1/instances/") return undefined; + if (!call.query.get("after_token")) return { json: { instances: [instance("running"), { ...instance("running"), id: 8, label: "someone's training run" }], next_token: "t2" } }; + return { json: { instances: [{ ...instance("exited"), id: 9, label: 'vmbridge:{"vmbridge":"other","sandbox-sdk-key":"vm-9"}' }], next_token: null } }; + }); + const provider = vast({ apiKey: "vast_secret", fetch, transport: recordingTransport().transport, publicKey, timing }); + + expect((await provider.list({ vmbridge: "b1" })).map((entry) => entry.id)).toEqual(["7"]); + expect((await provider.find("vm-9"))?.state).toBe("paused"); + expect(calls.filter((call) => call.query.get("after_token") === "t2").length).toBe(2); + }); + + test("a wake waits through the stopped container's own `exited` until the instance runs", async () => { + const states = ["exited", "exited", "loading", "running"]; + const { fetch } = fakeApi((call) => { + if (call.path === "/v0/instances/7/" && call.method === "GET") return { json: { instances: instance(states.shift() ?? "running") } }; + return undefined; + }); + const provider = vast({ apiKey: "vast_secret", fetch, transport: recordingTransport().transport, publicKey, timing }); + + await provider.resume!("7"); + + expect(states).toEqual([]); + }); + + test("a wake that waits for a GPU rented to someone else is stopped again, with a reason that says so", async () => { + const { calls, fetch } = fakeApi((call) => { + if (call.path === "/v0/instances/7/" && call.method === "GET") return { json: { instances: instance("stopped", { cur_state: "scheduling" }) } }; + return undefined; + }); + const provider = vast({ apiKey: "vast_secret", fetch, transport: recordingTransport().transport, publicKey, timing }); + + const error = await provider.resume!("7").catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(SandboxError); + expect((error as SandboxError).message).toContain("rented to someone else"); + const puts = calls.filter((call) => call.method === "PUT").map((call) => call.body); + expect(puts).toEqual([{ state: "running" }, { state: "stopped" }]); + }); + + test("a refused key is an auth error that never shows the key", async () => { + const { fetch } = fakeApi(() => ({ status: 404, json: { success: false, error: "auth_error", msg: "Invalid user key" } })); + const provider = vast({ apiKey: "vast_secret", fetch, transport: recordingTransport().transport, publicKey, timing }); + + const error = (await provider.connect("7").catch((caught: unknown) => caught)) as SandboxError; + + expect(error.code).toBe("auth"); + expect(String(error.message) + String(error.cause)).not.toContain("vast_secret"); + }); + + test("SSH goes straight to the host when it maps port 22, else through Vast.ai's proxy", () => { + expect(sshTarget(instance("running") as never)).toEqual({ host: "203.0.113.5", port: 40022 }); + expect(sshTarget(instance("running", { ports: null }) as never)).toEqual({ host: "ssh4.vast.ai", port: 31000 }); + expect(parseLabel("vmbridge:not json")).toBeNull(); + }); +}); + +describe("Vast.ai commands and files", () => { + const dir = mkdtempSync(join(tmpdir(), "vast-test-")); + afterAll(() => rmSync(dir, { recursive: true, force: true })); + const provider = vast({ apiKey: "vast_secret", fetch: fakeApi(() => undefined).fetch, transport: localTransport, publicKey, timing }); + + test("a command runs in its folder with its variables and stdin, and its output streams back", async () => { + let stdout = ""; + const result = await provider.exec("7", { + command: 'printf "%s %s " "$(pwd)" "$GREETING"; cat', + cwd: dir, + env: { GREETING: "it's hi" }, + stdin: "from stdin", + timeoutMs: 10_000, + onChunk: (chunk) => (stdout += chunk.stream === "stdout" ? chunk.text : ""), + }); + expect(result).toEqual({ exitCode: 0, timedOut: false }); + expect(stdout).toBe(`${dir} it's hi from stdin`); + }); + + test("a command that runs too long is ended and reported as timed out", async () => { + const result = await provider.exec("7", { command: "sleep 5", cwd: dir, env: {}, timeoutMs: 300, onChunk: () => {} }); + expect(result).toEqual({ exitCode: null, timedOut: true }); + }); + + // Instances run Linux, whose `stat` and `find` the file commands use. macOS has other ones. + const gnu = Bun.spawnSync(["stat", "-c", "%s", "/"]).exitCode === 0 && Bun.spawnSync(["find", "/", "-maxdepth", "0", "-printf", "x"]).exitCode === 0; + + test.skipIf(!gnu)("files are written with their folders and mode, read back, listed, and removed", async () => { + const path = `${dir}/deep/notes it's.txt`; + await provider.files.write("7", path, new TextEncoder().encode("hello"), { mode: 0o600 }); + + expect(new TextDecoder().decode(await provider.files.read("7", path))).toBe("hello"); + expect(await provider.files.stat("7", path)).toMatchObject({ type: "file", size: 5 }); + expect(statSync(path).mode & 0o777).toBe(0o600); + expect((await provider.files.list("7", `${dir}/deep`)).map((entry) => entry.path)).toEqual([path]); + + await provider.files.remove("7", `${dir}/deep`, { recursive: true }); + const missing = (await provider.files.read("7", path).catch((caught: unknown) => caught)) as SandboxError; + expect(missing.code).toBe("file_not_found"); + }); +}); diff --git a/apps/web/src/Analytics.tsx b/apps/web/src/Analytics.tsx index 9de9021f..99bb2ccb 100644 --- a/apps/web/src/Analytics.tsx +++ b/apps/web/src/Analytics.tsx @@ -21,6 +21,7 @@ const providerColors: Record = { kubi: "#4ca464", railway: "#9085e9", superserve: "#e66767", + vast: "#315fff", }; const otherColor = "#5c5c5c"; diff --git a/apps/web/src/assets/providers/vast.svg b/apps/web/src/assets/providers/vast.svg new file mode 100644 index 00000000..490d1d6e --- /dev/null +++ b/apps/web/src/assets/providers/vast.svg @@ -0,0 +1 @@ + diff --git a/apps/web/src/brand.tsx b/apps/web/src/brand.tsx index 0bd95146..24be3b6e 100644 --- a/apps/web/src/brand.tsx +++ b/apps/web/src/brand.tsx @@ -12,6 +12,7 @@ import instabox from "./assets/providers/instabox.svg"; import kubi from "./assets/providers/kubi.svg"; import railway from "./assets/providers/railway.svg"; import superserve from "./assets/providers/superserve.svg"; +import vast from "./assets/providers/vast.svg"; /** The VM Bridge mark: a bridge between your device and a VM. Same drawing as assets/logo.svg. */ export function Logo({ className }: { className?: string }) { @@ -39,6 +40,7 @@ const providerLogos: Record Date: Mon, 30 Nov 2026 04:05:35 +0530 Subject: [PATCH 03/10] docs: Vast.ai in the README, provider notes and landing page --- README.md | 21 +++++++++-- apps/landing/app/docs/page.tsx | 11 ++++-- apps/landing/components/Providers.tsx | 2 +- apps/landing/components/Stage.tsx | 2 +- apps/landing/lib/copy.ts | 4 +-- apps/landing/lib/data.ts | 18 ++++++++-- apps/landing/public/providers/vast.svg | 1 + docs/PROVIDERS.md | 48 +++++++++++++++++++------- docs/cloudflare.md | 2 ++ 9 files changed, 85 insertions(+), 24 deletions(-) create mode 100644 apps/landing/public/providers/vast.svg diff --git a/README.md b/README.md index fec6188e..de82bddb 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ you pay only your cloud provider for the VMs. Website and docs: [vmbridge.ordinity.com](https://vmbridge.ordinity.com) - Use several providers at once: boxd, Instabox, Daytona, Boat, Railway, E2B, Freestyle, - Superserve and Kubi. New VMs go to your default provider, or to the one you pick for a repository. + Superserve, Kubi and Vast.ai. New VMs go to your default provider, or to the one you pick for a repository. - `vb opencode` opens OpenCode in your terminal while the agent works in its own worktree on a VM, with the branch, its pull request and the VM in OpenCode's sidebar. See [OpenCode](#opencode). - A VM sleeps when it sits idle and wakes when you send a message or an OpenCode prompt. Opening a @@ -121,6 +121,23 @@ A Kubi VM is a whole desktop, and VM Bridge lets you and its agents use it: How it works: [docs/PROVIDERS.md](docs/PROVIDERS.md). +## Vast.ai VMs + +Vast.ai rents GPU machines from independent hosts. Every VM gets one NVIDIA GPU, on the cheapest +verified on-demand machine that fits the size. Add an API key from +[cloud.vast.ai/manage-keys](https://cloud.vast.ai/manage-keys/), and optionally pick a GPU model. + +- **Cost:** about $0.06 to $0.11 an hour awake, billed per second from prepaid credit. A sleeping VM + pays only for its disk, about $0.20 per GB a month. A GPU model you pick costs more. If VM Bridge is + down, a VM stops itself after an hour with no SSH connection. +- **Access:** VM Bridge reaches each VM over SSH, and T3 and OpenCode through SSH tunnels, so no ports + are open to the internet. It needs the `ssh` command, so Vast.ai does not work on Cloudflare Workers. +- **Limits:** a sleeping VM wakes only if its host's GPU is still free. Hosts can go offline, and each + sets an end date on its machines (VM Bridge picks ones with at least 14 days left). There are no + snapshots, systemd or Docker. + +How it works: [docs/PROVIDERS.md](docs/PROVIDERS.md). + ## Environment variables Under **Settings**, **Environment**, add variables such as `NPM_TOKEN` or `API_URL`. Every VM gets @@ -253,7 +270,7 @@ with other busy Durable Objects needs Workers Paid ($5 a month). It asks for two Then open the Worker's address and log in. Pair T3 Code with the same address. There is no setup link, local network, Tailscale or tunnel to set up: the Worker's `workers.dev` address (or a domain -you add to it) is the only one. To change the password, change the secret under the Worker's +you add to it) is the only one. Vast.ai does not work on Workers, because it needs the `ssh` command. To change the password, change the secret under the Worker's **Settings** in Cloudflare; that also logs everyone out. There is no machine to read skills or `AGENTS.md` from, so upload skills and paste instructions under diff --git a/apps/landing/app/docs/page.tsx b/apps/landing/app/docs/page.tsx index c7b46c9f..b75fd8f6 100644 --- a/apps/landing/app/docs/page.tsx +++ b/apps/landing/app/docs/page.tsx @@ -226,7 +226,7 @@ export default function Docs() { items={[ "Repositories share VMs. A repository goes on a VM that has room, and VM Bridge makes a new VM only when none does. A busy repository spreads over up to 4 VMs.", "A VM sleeps after it has been idle for a set time, and wakes when you send a message or an OpenCode prompt.", - "Several providers at once: boxd, Instabox, Daytona, Boat, Railway, E2B, Freestyle, Superserve and Kubi. Pick one per repository, or let new VMs use the default.", + "Several providers at once: boxd, Instabox, Daytona, Boat, Railway, E2B, Freestyle, Superserve, Kubi and Vast.ai. Pick one per repository, or let new VMs use the default.", "Everything is set up from a web dashboard behind one password: provider keys, GitHub, agent sign-ins and device pairing.", "T3 Code needs no changes. To the app, VM Bridge looks like a single T3 server.", "vb opencode opens OpenCode in your terminal while the agent works in its own worktree on a VM.", @@ -428,7 +428,7 @@ bun run compile # dist/vmbridge ])} />

- Each provider also has its own idle or time limit as a safety net in case VM Bridge is offline. Railway and Kubi have none, so VM + Each provider also has its own idle or time limit as a safety net in case VM Bridge is offline. Railway, Kubi and Vast.ai have none, so VM Bridge never sets one there.

@@ -474,6 +474,11 @@ bun run compile # dist/vmbridge by default. A disposable VM, picked in the Kubi settings, is deleted after 7 days asleep. The API key needs read, exec, power and network. , + <> + Vast.ai rents one NVIDIA GPU per VM from independent hosts, the cheapest verified on-demand machine that fits the size. + Sleep stops the VM and you pay only for its disk. A sleeping VM wakes only if its host's GPU is still free. VM Bridge reaches + it over SSH, so it needs the ssh command and does not run on Cloudflare Workers. + , <> Freestyle, Superserve and Kubi have one machine size, so small, medium and large are the same VM. , @@ -717,7 +722,7 @@ bun run compile # dist/vmbridge ["An agent shows as signed out on a VM", "Add its sign-in under Accounts, or in your provider's dashboard if it supplies them."], ["The pairing link does not work", "Links work once and expire after 15 minutes. Create a new one."], ["The T3 server on a VM did not answer", "The VM may be busy or the provider slow. Check the VM on the dashboard canvas, then retry."], - ["Waking takes longer than usual", "Stopped VMs (Daytona, Boat, Kubi) start T3 cold, which adds a few seconds over a paused VM."], + ["Waking takes longer than usual", "Stopped VMs (Daytona, Boat, Kubi, Vast.ai) start T3 cold, which adds a few seconds over a paused VM."], ["You forgot the dashboard password", <>Run vmbridge password on the machine to set a new one.], ]} /> diff --git a/apps/landing/components/Providers.tsx b/apps/landing/components/Providers.tsx index dabf519a..d9fbb10d 100644 --- a/apps/landing/components/Providers.tsx +++ b/apps/landing/components/Providers.tsx @@ -17,7 +17,7 @@ const spots = providers.map((provider, i) => { }); /** - * The nine providers on a ring around the bridge mark: the ring is the whole demo. + * The ten providers on a ring around the bridge mark: the ring is the whole demo. * Title and body sit in the left column at xl; the ring fills the right and stays * visible, centred, at every width. Nodes are sized so neighbours never overlap. */ diff --git a/apps/landing/components/Stage.tsx b/apps/landing/components/Stage.tsx index 776d026e..a13eb9a9 100644 --- a/apps/landing/components/Stage.tsx +++ b/apps/landing/components/Stage.tsx @@ -26,7 +26,7 @@ export const steps: Step[] = [ }, { title: "Choose a provider", - body: "Paste a key for boxd, Instabox, Daytona, Boat, Railway, E2B, Freestyle, Superserve or Kubi in the dashboard. Pick a VM size and how long a VM may sit idle.", + body: "Paste a key for boxd, Instabox, Daytona, Boat, Railway, E2B, Freestyle, Superserve, Kubi or Vast.ai in the dashboard. Pick a VM size and how long a VM may sit idle.", links: [false, false], paired: false, vm: "pick", diff --git a/apps/landing/lib/copy.ts b/apps/landing/lib/copy.ts index 990c1a50..293ce9e1 100644 --- a/apps/landing/lib/copy.ts +++ b/apps/landing/lib/copy.ts @@ -140,10 +140,10 @@ export const copy = { }, }, - /** The nine providers on a ring around the bridge mark. */ + /** The ten providers on a ring around the bridge mark. */ providers: { /** 40 */ - title: "Nine supported sandbox providers", + title: "Ten supported sandbox providers", /** 150 */ body: "Use your own accounts and API keys, and add several providers at once.", }, diff --git a/apps/landing/lib/data.ts b/apps/landing/lib/data.ts index d14f1260..c9baebe0 100644 --- a/apps/landing/lib/data.ts +++ b/apps/landing/lib/data.ts @@ -1,4 +1,4 @@ -export type ProviderId = "boxd" | "instabox" | "daytona" | "boat" | "railway" | "e2b" | "freestyle" | "superserve" | "kubi"; +export type ProviderId = "boxd" | "instabox" | "daytona" | "boat" | "railway" | "e2b" | "freestyle" | "superserve" | "kubi" | "vast"; export interface Provider { id: ProviderId; @@ -155,6 +155,20 @@ export const providers: Provider[] = [ reach: "Private port with a token header", safetyNet: "None", }, + { + id: "vast", + name: "Vast.ai", + logo: "/providers/vast.svg", + tile: "#000", + inset: "22%", + color: "#315fff", + sleep: "Stop, disk kept", + wake: "Start (a reboot)", + sizes: ["1 GPU, 4+ vCPU, 8+ GB", "1 GPU, 8+ vCPU, 16+ GB", "1 GPU, 16+ vCPU, 32+ GB"], + defaultSize: "small", + reach: "SSH tunnel", + safetyNet: "None", + }, ]; export const github = "https://github.com/vkpdeveloper/vmbridge"; @@ -291,7 +305,7 @@ export const faq = [ { question: "Which cloud providers does VM Bridge support?", answer: - "VM Bridge supports boxd, Instabox, Daytona, Boat, Railway, E2B, Freestyle, Superserve and Kubi. You can add several at once, pick a default for new VMs, and send a repository to a given provider.", + "VM Bridge supports boxd, Instabox, Daytona, Boat, Railway, E2B, Freestyle, Superserve, Kubi and Vast.ai. You can add several at once, pick a default for new VMs, and send a repository to a given provider.", }, { question: "Which coding agents can I use?", diff --git a/apps/landing/public/providers/vast.svg b/apps/landing/public/providers/vast.svg new file mode 100644 index 00000000..490d1d6e --- /dev/null +++ b/apps/landing/public/providers/vast.svg @@ -0,0 +1 @@ + diff --git a/docs/PROVIDERS.md b/docs/PROVIDERS.md index 147948ae..b6929284 100644 --- a/docs/PROVIDERS.md +++ b/docs/PROVIDERS.md @@ -2,18 +2,18 @@ VM Bridge runs every VM through `@opencoredev/sandbox-sdk` 1.2.0. You can add several providers and use them at once. -| | Boat | boxd | Daytona | E2B | Freestyle | Instabox | Railway | Superserve | Kubi | -|---|---|---|---|---|---|---|---|---|---| -| Sizes (small / medium / large) | 2/4 GB, 4/8 GB, 8/16 GB | 1/4 GB, 2/8 GB, 4/16 GB | 1/1 GB, 2/4 GB, 4/8 GB | 2/2 GB, 4/4 GB, 8/8 GB | 4/8 GB for all three | 2/4 GB, 4/8 GB, 8/16 GB | 1/2 GB, 2/4 GB, 4/8 GB | 2/4 GB for all three | 4/8 GB for all three | -| Idle sleep | stop (disk kept) | pause (memory kept) | stop (disk kept) | pause (memory kept) | pause (memory kept) | pause (memory kept) | checkpoint, then destroy | pause (memory kept) | stop (disk kept) | -| Wake | resume | resume | start | resume | resume | resume | new VM from checkpoint (new sandbox ID) | resume | start (a full reboot) | -| Default size | small | medium | medium | medium | medium | medium | medium | medium | medium | -| Snapshot | yes, and delete | yes | yes (files only) | yes, and delete | yes (memory and disk) | yes, and delete | checkpoint (files only) | yes | not used | -| T3 port reachable through | preview host, `_port_auth` cookie | public default proxy | private preview, `X-Daytona-Preview-Token` header | public URL | public `*.style.dev` domain | public published port | public domain declared at create | private preview, token header | private port, `Kubi-Port-Token` header | -| Agent sign-ins | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | -| GitHub | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | -| Provider safety net if VM Bridge is down | auto-stop 12 h after start, pushed back while agents work | auto-suspend after 60 min idle | auto-stop after 60 min without preview or toolbox traffic | auto-pause 60 min after start or wake, pushed back while agents work | auto-pause after 60 min without network traffic | auto-suspend after 30 min idle | none | auto-pause after 12 h awake | none | -| Extra package | none | `@boxd-sh/sdk` | none | none | none | none | `railway` | none | none | +| | Boat | boxd | Daytona | E2B | Freestyle | Instabox | Railway | Superserve | Kubi | Vast.ai | +|---|---|---|---|---|---|---|---|---|---|---| +| Sizes (small / medium / large) | 2/4 GB, 4/8 GB, 8/16 GB | 1/4 GB, 2/8 GB, 4/16 GB | 1/1 GB, 2/4 GB, 4/8 GB | 2/2 GB, 4/4 GB, 8/8 GB | 4/8 GB for all three | 2/4 GB, 4/8 GB, 8/16 GB | 1/2 GB, 2/4 GB, 4/8 GB | 2/4 GB for all three | 4/8 GB for all three | 1 GPU with 4+/8+ GB, 8+/16+ GB, 16+/32+ GB | +| Idle sleep | stop (disk kept) | pause (memory kept) | stop (disk kept) | pause (memory kept) | pause (memory kept) | pause (memory kept) | checkpoint, then destroy | pause (memory kept) | stop (disk kept) | stop (disk kept) | +| Wake | resume | resume | start | resume | resume | resume | new VM from checkpoint (new sandbox ID) | resume | start (a full reboot) | start (a reboot, and only if the host's GPU is free) | +| Default size | small | medium | medium | medium | medium | medium | medium | medium | medium | small | +| Snapshot | yes, and delete | yes | yes (files only) | yes, and delete | yes (memory and disk) | yes, and delete | checkpoint (files only) | yes | not used | not available | +| T3 port reachable through | preview host, `_port_auth` cookie | public default proxy | private preview, `X-Daytona-Preview-Token` header | public URL | public `*.style.dev` domain | public published port | public domain declared at create | private preview, token header | private port, `Kubi-Port-Token` header | SSH tunnel | +| Agent sign-ins | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | +| GitHub | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | VM Bridge | +| Provider safety net if VM Bridge is down | auto-stop 12 h after start, pushed back while agents work | auto-suspend after 60 min idle | auto-stop after 60 min without preview or toolbox traffic | auto-pause 60 min after start or wake, pushed back while agents work | auto-pause after 60 min without network traffic | auto-suspend after 30 min idle | none | auto-pause after 12 h awake | none | stops itself after 60 min with no SSH connection | +| Extra package | none | `@boxd-sh/sdk` | none | none | none | none | `railway` | none | none | none (needs the `ssh` command) | Public previews (boxd, E2B, Freestyle, Instabox, Railway) expose the T3 server port. The T3 server requires its own bearer session token on every route, and only VM Bridge holds it. Each VM also opens OpenCode's server on port 4096 and a relay to dev servers on port 4797, both through the same route as T3. OpenCode answers only with the VM's OpenCode password, and the relay only with a header carrying that password. @@ -29,12 +29,13 @@ The default size is what new VMs get unless **Settings**, **VMs** or a repositor - **Instabox**: the default template is `agent-browser`. Ports must be 1024 or higher (T3 uses 3773). The free plan allows one machine in any state (a paused one counts) and only 4 vCPU, 8 GB (`400 spec_not_allowed` for 2 vCPU, 4 GB, checked live), so medium is the default. With one machine there is no room to build a base snapshot, and those builds fail with `429 quota_exceeded`, which the SDK retries for up to a minute first. A snapshot fixes the size of VMs made from it to its source's (`sizeLocked`), so VM Bridge names no size there. A snapshot of a running machine is like a power cut, so the base setup runs `sync` first. Deleting a snapshot leaves the machines made from it working. - **Superserve**: every template has 2 vCPU, 4 GB and 8 GB of disk, so all three sizes are the same VM. The SDK needs Python in the VM and the default `superserve/node-22` template has none, so VM Bridge uses `superserve/python-3.11` and installs Node itself. Superserve has no idle timer, only a cap on time awake that resets on every resume, so the safety net is a pause after 12 hours awake. Superserve's docs only say pause keeps "VM state". A check confirmed it keeps memory: a process started before a pause was still running after resume, and uptime carried on instead of restarting. - **Kubi**: one machine for every size: 4 vCPU, 8 GB and 50 GB of disk, Debian 13 with Node 20.19, in `eu-1`. VM Bridge calls Kubi's API with `fetch` (the `@trykubi/sdk` package has no ports). A VM is a Kubi screen labelled with VM Bridge's labels and its key. Sleep is a stop (disk kept) and wake is a start, which reboots the VM, so T3 starts again on every wake like on Daytona. Processes do not survive a stop. T3 is reached through a token port (`PUT /screens/{id}/ports/3773`), whose token goes in a `Kubi-Port-Token` header; Kubi closes idle HTTP connections after 5 minutes and WebSockets after 1 hour, and VM Bridge's 5 s ping keeps the socket busy. Exec takes at most 10000 characters of command and 64 KiB of stdin, so longer commands and all stdin go up as files only the VM's user can read, removed as the command starts. A persistent screen ($20 a month, kept until deleted) is the default. Kubi settings can pick disposable instead ($0.035 an hour running, $0.003 an hour stopped), which Kubi deletes 7 days after it stops. The API key needs `read`, `exec`, `power` and `network`; adding the provider checks the key with `GET /me` and names any that are missing. A full account (`402 QUOTA_EXCEEDED`) names its screen limit. Kubi has no idle timer, so there is no safety net. +- **Vast.ai**: every VM gets one NVIDIA GPU. VM Bridge rents the cheapest verified, on-demand machine from Vast.ai's marketplace that fits the size (small: 4+ vCPU, 8+ GB, 40 GB disk; medium: 8+ vCPU, 16+ GB, 60 GB; large: 16+ vCPU, 32+ GB, 100 GB), and only machines its host offers for at least 14 days. The optional GPU model setting narrows the search and costs more than "Cheapest available". The API key comes from https://cloud.vast.ai/manage-keys/. VM Bridge reaches each VM with the `ssh` command from the computer it runs on, so Vast.ai cannot run on Cloudflare Workers. It makes its own SSH key and adds it to the Vast.ai account. T3 and OpenCode are reached through SSH tunnels, so no ports are open to the internet. Sleep is a stop (disk kept, memory gone) and wake is a start, which reboots the VM. Asleep it pays only for its disk. Vast.ai bills per second from prepaid credit and stops instances at zero credit. Limits: a sleeping VM wakes only if its host's GPU is still free, so if someone else rented it meanwhile the wake fails and the VM has to wait or be deleted. Each host sets an end date on its machines (usually weeks to months), and a VM can be lost when it passes. Hosts are independent and can go offline. There are no snapshots, so base snapshots are not available. Containers have no systemd or Docker. Safety net: a small script in each VM stops it after 60 minutes with no SSH connection, using the key Vast.ai gives each container for itself, so a VM left awake while VM Bridge is down stops paying for its GPU within the hour. - **Kubi watch links**: every Kubi VM gets a link, `/watch/` on VM Bridge's address, that shows its screen live and view-only in any browser, with no dashboard login. The VM's details in the dashboard copy it, make a new one (the old one stops working at once) or turn it off. The token is 32 random bytes, looked up by its SHA-256 hash and stored encrypted, and a wrong or old token gets the same 404 as any unknown path. The page's stream goes through VM Bridge, which asks Kubi for a fresh view-only ticket (`POST /screens/{id}/viewer`) on every connect, so the browser never sees the Kubi key, ticket or address. VM Bridge only passes on the bytes a viewer sends to ask for frames; anything else, such as keys or the mouse, ends the stream. Opening the link never wakes the VM: while it sleeps the page says so and connects when it wakes. VM Bridge also keeps the link in `/workspace/.vmbridge/watch-url` on the VM (readable only by its user), written on every wake and whenever the link or VM Bridge's address changes, and removed while the link is off. On Cloudflare Workers the link uses the Worker's address. - **Railway**: no pause, and Railway's own idle timeout destroys the VM, so VM Bridge sets none. CPU and memory are fixed per client, so VM Bridge opens one client per size. Railway keeps checkpoints until they are deleted and the SDK has no delete, so VM Bridge deletes them with Railway's own SDK (`Sandbox.checkpoints` to find one by key, then `Sandbox.deleteCheckpoint`): after a wake from the checkpoint, and when a VM asleep as a checkpoint is deleted. ## Status -All nine drivers are built. All but Kubi have passed a full `scripts/live.ts` run; Kubi's live check is below. E2B, Freestyle and Superserve ran `scripts/live.ts --agent` on 2026-11-21 with the same steps as below. On 2026-11-21, Boat, boxd, Instabox and Railway each ran `scripts/live.ts --agent` at medium size: create, clone, one short Codex turn, sleep, reads while asleep, a new message that wakes the VM, a second turn, the checkout still there, delete. Daytona was not set up for that round, so its results below are from its own earlier runs without an agent turn. +All ten drivers are built. All but Kubi have passed a full `scripts/live.ts` run; Kubi's live check is below. E2B, Freestyle and Superserve ran `scripts/live.ts --agent` on 2026-11-21 with the same steps as below. On 2026-11-21, Boat, boxd, Instabox and Railway each ran `scripts/live.ts --agent` at medium size: create, clone, one short Codex turn, sleep, reads while asleep, a new message that wakes the VM, a second turn, the checkout still there, delete. Daytona was not set up for that round, so its results below are from its own earlier runs without an agent turn. Verified live: @@ -240,6 +241,27 @@ Earlier runs measured a stop at about 3.6 s, a blank create to running at 13 s, An earlier Railway run (2026-11-21, small size, no agent turn) took 57.2 s to the first VM, 8.8 s to sleep and 45.1 s to wake. +### Vast.ai live results (2026-11-30, small size, GTX 1070 at $0.058 an hour) + +`scripts/live.ts vast` without `--agent` (the test VM Bridge had no agent sign-ins), one run: create, T3 installed and started, clone, sleep, reads while asleep, wake, the checkout still there, delete. A separate script drove the driver directly: commands with stdin, environment and a timeout, `nvidia-smi`, file write, read, stat, list and delete, a server inside the VM reached through the SSH tunnel before and after a sleep, files kept across the sleep, and the idle safety-net script running with the container's own key. A third run started OpenCode the way `vb opencode` does, in a new worktree, then created and listed a session through VM Bridge's OpenCode address with the project password (a wrong one got 401). That run used a placeholder OpenCode key, so no agent turn. All the runs together cost about $0.03 of credit. + +| Step | Time | +|---|---| +| Rent and boot (cheapest offer to SSH answering) | 35 to 50 s | +| First VM ready after boot (prepare, install, start T3) | 47.6 s | +| Clone and register project | 1.9 s | +| Sleep (stop, until Vast.ai reports it stopped) | 22 to 29 s | +| Wake (start, container boots, T3 answering) | 47 to 65 s | +| OpenCode in a new worktree, from asking to ready, on a new VM | 98 to 101 s | + +| Latency (ms) | p50 | p95 | +|---|---|---| +| VM `filesystem.browse` | 264 | 515 | +| VM `vcs.refreshStatus` | 561 | 1068 | +| Asleep: `vcs.refreshStatus` from VM Bridge's copy | 0.6 | 19.2 | + +Found live: right after a start, Vast.ai still reports the stopped container's `exited` for up to a minute, so a wake waits through it. A data folder with a long path, such as one under macOS's temporary folder, is too long for SSH's shared connection socket, so there each command opens its own connection. + ## Not supported Agent37 is a hosted agents API, not a VM, so it cannot run T3's server. VM Bridge does not support it. diff --git a/docs/cloudflare.md b/docs/cloudflare.md index 627fa848..01c55f3e 100644 --- a/docs/cloudflare.md +++ b/docs/cloudflare.md @@ -78,6 +78,8 @@ Object, so nothing has to be set up again. pairing link from **Devices**. - No machine to read skills or `AGENTS.md` from: upload skills and paste `AGENTS.md` and `CLAUDE.md` under **Skills**. +- Vast.ai does not work here. VM Bridge reaches its VMs with the `ssh` command, which Workers do not + have. Run VM Bridge on your own computer to use it. - Passwords are hashed with PBKDF2-SHA256 at 100,000 rounds, the most Workers allows, instead of argon2id. A login is limited to a few tries per visitor and per minute overall, as on Bun. - Branch lookups skip the check that keeps them off private addresses, because a Worker cannot reach From daa0b973282f1462a305a63acb4d51b888ef9ef6 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Mon, 30 Nov 2026 15:11:24 +0530 Subject: [PATCH 04/10] fix: Vast.ai VMs on hosts that break SSH key permissions start, or move on in 3 minutes On some hosts the authorized_keys file Vast.ai writes has an owner or mode sshd refuses, so no key works and the VM waited the full 12 minute boot limit. The start script now sets the owner and mode, and a VM that runs but still refuses SSH after 3 minutes is deleted and the next offer rented. --- apps/server/src/providers/vast.ts | 25 ++++++++++++++++++++----- apps/server/test/vast.test.ts | 24 ++++++++++++++++++++++++ docs/PROVIDERS.md | 2 +- 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/apps/server/src/providers/vast.ts b/apps/server/src/providers/vast.ts index 837b4159..b0763594 100644 --- a/apps/server/src/providers/vast.ts +++ b/apps/server/src/providers/vast.ts @@ -48,13 +48,25 @@ const gpuModels: Record = { * It also stops the instance if VM Bridge goes away, as other providers' idle timers do: VM Bridge keeps an SSH * connection open to every VM it has awake, so an hour with none means it is down. The instance stops itself with * the key Vast.ai gives every container, which can only start, stop or delete that one instance. + * + * On some hosts the files Vast.ai writes the SSH keys to have an owner or mode sshd refuses ("bad ownership or modes + * for file /root/.ssh/authorized_keys"), so no key works. Vast.ai writes them just after the container starts and + * again when a key is added, so the script sets them right every 2 seconds for the first 5 minutes, then every minute. */ export const onstart = `touch /root/.no_auto_tmux cat > /root/vmbridge-idle.sh <<'EOF' #!/bin/bash -[ -n "$CONTAINER_API_KEY" ] && [ -n "$CONTAINER_ID" ] || exit 0 +keys() { + chown root:root /root /root/.ssh /root/.ssh/authorized_keys 2>/dev/null + chmod go-w /root 2>/dev/null + chmod 700 /root/.ssh 2>/dev/null + chmod 600 /root/.ssh/authorized_keys 2>/dev/null +} +for _ in $(seq 150); do keys; sleep 2; done idle=0 while sleep 60; do + keys + [ -n "$CONTAINER_API_KEY" ] && [ -n "$CONTAINER_ID" ] || continue if awk '$4 == "01" && $2 ~ /:0016$/ { found = 1 } END { exit !found }' /proc/net/tcp /proc/net/tcp6 2>/dev/null; then idle=0; else idle=$((idle + 1)); fi if [ "$idle" -ge ${idleStopMinutes} ]; then curl -fsS -X PUT -H "Authorization: Bearer $CONTAINER_API_KEY" -H "Content-Type: application/json" -d '{"state":"stopped"}' "https://console.vast.ai/api/v0/instances/$CONTAINER_ID/" && exit 0 @@ -106,7 +118,7 @@ const defaultTiming = { bootMs: 12 * 60_000, /** A start waits in `scheduling` while the host's GPU is rented to someone else, possibly for good. */ schedulingMs: 2 * 60_000, - /** SSH starts a little after the container. */ + /** SSH starts a little after the container. A machine running this long that SSH still cannot open is given up. */ sshMs: 3 * 60_000, stopMs: 2 * 60_000, }; @@ -277,6 +289,7 @@ export function vast(options: VastOptions): VastProvider { async function untilReady(id: string, deadlineMs: number, waking = false) { const deadline = Date.now() + deadlineMs; let scheduling: number | undefined; + let running: number | undefined; let left = !waking; for (;;) { const current = await instance(id); @@ -291,15 +304,17 @@ export function vast(options: VastOptions): VastProvider { } let sshError: string | undefined; if (status === "running" && sshTarget(current)) { + running ??= Date.now(); targets.delete(id); const ssh = await transport.run(id, "true", { timeoutMs: 30_000 }).catch(() => null); if (ssh?.exitCode === 0) return current; sshError = sshReason(ssh?.stderr ?? ""); } - if (Date.now() > deadline) { - if (sshError !== undefined) throw fail(`The Vast.ai machine runs but did not answer over SSH${sshError}`, "timeout", id); - throw fail("The Vast.ai machine did not start in time", "timeout", id); + const sshGivenUp = running !== undefined && Date.now() - running > timing.sshMs; + if (sshError !== undefined && (sshGivenUp || Date.now() > deadline)) { + throw fail(`The Vast.ai machine runs but did not answer over SSH${sshError}`, "timeout", id); } + if (Date.now() > deadline) throw fail("The Vast.ai machine did not start in time", "timeout", id); await sleep(timing.pollMs); } } diff --git a/apps/server/test/vast.test.ts b/apps/server/test/vast.test.ts index 3d47a61b..005b0250 100644 --- a/apps/server/test/vast.test.ts +++ b/apps/server/test/vast.test.ts @@ -140,6 +140,30 @@ describe("Vast.ai instances", () => { expect(calls.some((call) => call.method === "POST" && call.path === "/v0/ssh/")).toBe(false); }); + test("a machine that runs but never takes the key is given up well before the boot deadline, and the next offer is rented", async () => { + let rented = 0; + const { calls, fetch } = fakeApi((call) => { + if (call.path === "/v0/bundles/") return { json: offers }; + if (call.path.startsWith("/v0/asks/")) return { json: { success: true, new_contract: 7 + rented++ } }; + if (call.path === "/v0/instances/7/" && call.method === "GET") return { json: { instances: instance("running") } }; + if (call.path === "/v0/instances/8/" && call.method === "GET") return { json: { instances: { ...instance("running"), id: 8 } } }; + return undefined; + }); + // Host 7 has sshd refusing every key, as on hosts where the key file's owner or mode is wrong. + const transport: Transport = { + ...recordingTransport().transport, + run: async (id) => (id === "7" ? { exitCode: 255, stdout: new Uint8Array(), stderr: "root@203.0.113.5: Permission denied (publickey).\n" } : { exitCode: 0, stdout: new Uint8Array(), stderr: "" }), + }; + const provider = vast({ apiKey: "vast_secret", fetch, transport, publicKey, timing: { ...timing, bootMs: 60_000, sshMs: 50 } }); + + const started = Date.now(); + const info = await provider.create({ key: "vm-1", size: "small", labels: { vmbridge: "b1" } }); + + expect(info.id).toBe("8"); + expect(Date.now() - started).toBeLessThan(5_000); + expect(calls.some((call) => call.method === "DELETE" && call.path === "/v0/instances/7/")).toBe(true); + }); + test("lists only the instances VM Bridge made with these labels, and finds one by its key", async () => { const { calls, fetch } = fakeApi((call) => { if (call.path !== "/v1/instances/") return undefined; diff --git a/docs/PROVIDERS.md b/docs/PROVIDERS.md index b6929284..373e8114 100644 --- a/docs/PROVIDERS.md +++ b/docs/PROVIDERS.md @@ -260,7 +260,7 @@ An earlier Railway run (2026-11-21, small size, no agent turn) took 57.2 s to th | VM `vcs.refreshStatus` | 561 | 1068 | | Asleep: `vcs.refreshStatus` from VM Bridge's copy | 0.6 | 19.2 | -Found live: right after a start, Vast.ai still reports the stopped container's `exited` for up to a minute, so a wake waits through it. A data folder with a long path, such as one under macOS's temporary folder, is too long for SSH's shared connection socket, so there each command opens its own connection. +Found live: right after a start, Vast.ai still reports the stopped container's `exited` for up to a minute, so a wake waits through it. A data folder with a long path, such as one under macOS's temporary folder, is too long for SSH's shared connection socket, so there each command opens its own connection. On one RTX 4090 host, sshd refused every key with "bad ownership or modes for file /root/.ssh/authorized_keys": the VM's start script now sets those files' owner and mode, and a VM whose SSH still refuses VM Bridge 3 minutes after it runs is deleted and the next offer rented. The script's fix has not been seen working on that host yet, as it was not for rent again. ## Not supported From 032057c0ac1476660a4bfad09cc5d55e92db43cb Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Mon, 30 Nov 2026 15:50:46 +0530 Subject: [PATCH 05/10] fix: Claude Code runs on VMs that only give root, such as Vast.ai Claude Code refuses --dangerously-skip-permissions as root unless IS_SANDBOX=1, so every Claude turn on a Vast.ai VM failed before it started. VM Bridge's env file now sets it on every VM. --- apps/server/src/vm/runtime.ts | 3 +++ apps/server/test/env.test.ts | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/apps/server/src/vm/runtime.ts b/apps/server/src/vm/runtime.ts index 1ef2342b..2b44dec7 100644 --- a/apps/server/src/vm/runtime.ts +++ b/apps/server/src/vm/runtime.ts @@ -135,6 +135,9 @@ function envFile(credentials: VmCredentials, fingerprint: string) { const lines = [ `unset ${providerVars.join(" ")}`, `export PATH="${root}/node/bin:${root}/npm/bin:${root}/gh/bin:$PATH"`, + // Every VM is a sandbox. Some providers (Vast.ai) only give root, and Claude Code refuses to skip its permission + // prompts as root unless this says it is in one. + "export IS_SANDBOX=1", // Not exported: only start-t3.sh reads it, to record what the server starts with. `VMBRIDGE_CREDENTIALS=${fingerprint}`, ]; diff --git a/apps/server/test/env.test.ts b/apps/server/test/env.test.ts index 69cdf74f..ee17cef3 100644 --- a/apps/server/test/env.test.ts +++ b/apps/server/test/env.test.ts @@ -38,6 +38,17 @@ describe("environment variables", () => { } }); + test("agents are told they run in a sandbox, so Claude Code can skip its prompts on providers that only give root", async () => { + const dir = mkdtempSync(join(tmpdir(), "vmbridge-env-")); + try { + const file = join(dir, "env"); + writeFileSync(file, await envFile({})); + expect(Bun.spawnSync(["bash", "-c", `. ${file} && bash -c 'printf %s "$IS_SANDBOX"'`]).stdout.toString()).toBe("1"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + test("names VM Bridge sets, or that would break shells and agents, are refused", () => { for (const name of ["PATH", "HOME", "SHELL", "IFS", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "GH_TOKEN", "GITHUB_TOKEN", "GIT_TERMINAL_PROMPT", "ANTHROPIC_API_KEY", "T3CODE_HOME", "T3CODE_ANYTHING", "VMBRIDGE_CREDENTIALS", "LD_PRELOAD"]) { expect(envNameProblem(name)).toContain("reserved"); From 01eadcaca4360c131ac72ad149ca8f3da8ba51df Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Mon, 30 Nov 2026 16:32:24 +0530 Subject: [PATCH 06/10] feat: GPU use, memory, temperature and power in a VM's resources --- apps/server/src/vm/stats.ts | 30 +++++++++++++++++++++++-- apps/server/test/stats.test.ts | 14 +++++++++++- apps/web/src/Canvas.tsx | 40 +++++++++++++++++++++++++++------ packages/contracts/src/index.ts | 14 ++++++++++++ 4 files changed, 88 insertions(+), 10 deletions(-) diff --git a/apps/server/src/vm/stats.ts b/apps/server/src/vm/stats.ts index d2be9054..edfc34f1 100644 --- a/apps/server/src/vm/stats.ts +++ b/apps/server/src/vm/stats.ts @@ -1,4 +1,4 @@ -import type { Usage, VmStats } from "@vmbridge/contracts"; +import type { GpuStats, Usage, VmStats } from "@vmbridge/contracts"; import type { Fleet } from "../fleet.ts"; import { checkoutRoot } from "./runtime.ts"; @@ -7,6 +7,8 @@ import { checkoutRoot } from "./runtime.ts"; * and a part the VM lacks (PSI, cgroup files) prints nothing. Containers see the host in /proc/meminfo, * so their cgroup v2 limits are read too. CPU is measured over one second from the cgroup's * `usage_usec` when there is one, else from /proc/stat: /proc/loadavg would show a container's host. + * GPUs come from nvidia-smi in the VM rather than a provider's API: Vast.ai's GPU figures come from the + * host and lag behind, and nvidia-smi works the same on every provider. */ export const statsCommand = `exec 2>/dev/null cg=/sys/fs/cgroup @@ -22,6 +24,7 @@ echo @nproc; nproc || getconf _NPROCESSORS_ONLN echo @df; df -Pk ${checkoutRoot} sleep 1 cpu 1 +echo @gpu; nvidia-smi --query-gpu=name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw,power.limit --format=csv,noheader,nounits `; /** @@ -109,11 +112,34 @@ function disk(parts: Map): Usage | null { return { used: (size - available) * 1024, total: size * 1024 }; } +/** One CSV line per GPU. nvidia-smi prints "[N/A]" or "[Not Supported]" for what a GPU lacks, which reads as null. */ +function gpus(parts: Map): GpuStats[] { + const mib = 2 ** 20; + return (parts.get("gpu") ?? "") + .trim() + .split("\n") + .map((line) => line.split(",").map((field) => field.trim())) + .filter(([name, ...values]) => name && values.length === 6) + .map(([name, usage, used, total, temperature, draw, limit]) => { + const percent = number(usage); + const memoryUsed = number(used); + const memoryTotal = number(total); + const watts = number(draw); + return { + name: name!, + usage: percent === null ? null : percent / 100, + memory: memoryUsed !== null && memoryTotal ? { used: memoryUsed * mib, total: memoryTotal * mib } : null, + temperature: number(temperature), + power: watts === null ? null : { draw: watts, limit: number(limit) }, + }; + }); +} + export function parseStats(output: string, at: number): VmStats { const parts = sections(output); const mem = memory(parts); const pressure = number(parts.get("psi")?.match(/^some avg10=([\d.]+)/m)?.[1]); - return { at, memory: mem, memoryPressure: pressure, cpu: cpu(parts), disk: disk(parts), highMemory: highMemory(mem, pressure) }; + return { at, memory: mem, memoryPressure: pressure, cpu: cpu(parts), disk: disk(parts), highMemory: highMemory(mem, pressure), gpus: gpus(parts) }; } /** diff --git a/apps/server/test/stats.test.ts b/apps/server/test/stats.test.ts index 1398df8c..86007b41 100644 --- a/apps/server/test/stats.test.ts +++ b/apps/server/test/stats.test.ts @@ -69,7 +69,19 @@ describe("parseStats", () => { test("reads df with a long device name and survives missing parts", () => { const df = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/disk/by-id/packstore-rootfs 29985524 3670060 26299080 13% /"; expect(parseStats(output({ df }), 1).disk?.total).toBe(29985524 * 1024); - expect(parseStats("", 1)).toEqual({ at: 1, memory: null, memoryPressure: null, cpu: null, disk: null, highMemory: false }); + expect(parseStats("", 1)).toEqual({ at: 1, memory: null, memoryPressure: null, cpu: null, disk: null, highMemory: false, gpus: [] }); + }); + + test("reads each GPU from nvidia-smi, with what a GPU does not report left null", () => { + // A Vast.ai RTX 4090 at idle, then a GPU whose driver reports no power or temperature. + const gpu = "NVIDIA GeForce RTX 4090, 0, 40, 24564, 39, 28.82, 450.00\nNVIDIA A100-SXM4-80GB, 87, 61000, 81920, [N/A], [Not Supported], [Not Supported]"; + expect(parseStats(output({ gpu }), 1).gpus).toEqual([ + { name: "NVIDIA GeForce RTX 4090", usage: 0, memory: { used: 40 * 2 ** 20, total: 24564 * 2 ** 20 }, temperature: 39, power: { draw: 28.82, limit: 450 } }, + { name: "NVIDIA A100-SXM4-80GB", usage: 0.87, memory: { used: 61000 * 2 ** 20, total: 81920 * 2 ** 20 }, temperature: null, power: null }, + ]); + // No nvidia-smi, or one that failed with a message. + expect(parseStats(output(), 1).gpus).toEqual([]); + expect(parseStats(output({ gpu: "NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver." }), 1).gpus).toEqual([]); }); }); diff --git a/apps/web/src/Canvas.tsx b/apps/web/src/Canvas.tsx index d0d6132e..2be33806 100644 --- a/apps/web/src/Canvas.tsx +++ b/apps/web/src/Canvas.tsx @@ -17,7 +17,7 @@ import { } from "@xyflow/react"; import { HugeiconsIcon } from "@hugeicons/react"; import { Add01Icon, Alert02Icon, Cancel01Icon, CenterFocusIcon, Delete02Icon, InformationCircleIcon, LaptopIcon, Message01Icon, Moon02Icon, PowerIcon, ZoomInIcon, ZoomOutIcon } from "@hugeicons/core-free-icons"; -import { vmSizes, type BridgeUpdate, type ClientInfo, type Overview, type ProjectInfo, type ProviderId, type SessionAgent, type TrafficEvent, type Usage, type VmInfo, type VmSize, type VmState, type VmStats } from "@vmbridge/contracts"; +import { vmSizes, type BridgeUpdate, type ClientInfo, type GpuStats, type Overview, type ProjectInfo, type ProviderId, type SessionAgent, type TrafficEvent, type Usage, type VmInfo, type VmSize, type VmState, type VmStats } from "@vmbridge/contracts"; import { AlertDialog, AlertDialogAction, @@ -724,6 +724,34 @@ function Meter({ label, value, share, high }: { label: string; value: string; sh ); } +function Reading({ label, value, high }: { label: string; value: string; high?: boolean }) { + return ( +
+ {label} + {value} +
+ ); +} + +function Gpu({ gpu, label }: { gpu: GpuStats; label: string }) { + // "NVIDIA GeForce RTX 4090" reads as "RTX 4090". + const name = gpu.name.replace(/^NVIDIA\s+(GeForce\s+)?/, ""); + return ( + <> + {gpu.usage === null ? ( + + ) : ( + + )} + {gpu.memory && } + {gpu.temperature !== null && = 85} />} + {gpu.power && ( + + )} + + ); +} + function Resources({ stats, now }: { stats: VmStats | null; now: number }) { return (
@@ -734,12 +762,7 @@ function Resources({ stats, now }: { stats: VmStats | null; now: number }) { {stats ? (
{stats.memory && } - {stats.memoryPressure !== null && ( -
- Memory pressure - = 10 && "text-destructive")}>{stats.memoryPressure.toFixed(1)}% -
- )} + {stats.memoryPressure !== null && = 10} />} {stats.cpu && ( )} {stats.disk && } + {stats.gpus.map((gpu, index) => ( + 1 ? `GPU ${index + 1}` : "GPU"} /> + ))}
) : (

Measuring.

diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 397e8baa..b65b0b83 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -262,6 +262,20 @@ export interface VmStats { disk: Usage | null; /** Memory is nearly full or tasks often wait on it. */ highMemory: boolean; + /** NVIDIA GPUs, read with nvidia-smi. Empty on a VM without one. */ + gpus: GpuStats[]; +} + +/** One GPU. A value the GPU does not report is null. */ +export interface GpuStats { + name: string; + /** Share of the last sample period a kernel ran on the GPU, 0 to 1. */ + usage: number | null; + memory: Usage | null; + /** Degrees Celsius. */ + temperature: number | null; + /** Watts. */ + power: { draw: number; limit: number | null } | null; } export interface VmInfo { From 6c3286385dbb337c12b786705c18dfd19fbe9cd5 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Mon, 30 Nov 2026 16:50:18 +0530 Subject: [PATCH 07/10] feat: new VMs get T3, Codex and Claude Code in one download, rebuilt every two days --- .github/workflows/release.yml | 5 ++- .github/workflows/vm-tools.yml | 68 ++++++++++++++++++++++++++++++++++ apps/server/src/vm/runtime.ts | 63 ++++++++++++++++++++++++++++--- apps/server/test/setup.test.ts | 54 +++++++++++++++++++++++++-- scripts/vm-tools.ts | 34 +++++++++++++++++ 5 files changed, 213 insertions(+), 11 deletions(-) create mode 100644 .github/workflows/vm-tools.yml create mode 100644 scripts/vm-tools.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e6ab53a9..f23f1344 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -132,7 +132,10 @@ jobs: - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 with: subject-path: dist/* - - run: gh release create "$TAG" dist/* --repo "$GITHUB_REPOSITORY" --title "$TAG" --generate-notes + # The notes start at the previous VM Bridge release, never at the "vm-tools" prerelease (see vm-tools.yml). + - run: | + previous=$(gh release view --repo "$GITHUB_REPOSITORY" --json tagName --jq .tagName) + gh release create "$TAG" dist/* --repo "$GITHUB_REPOSITORY" --title "$TAG" --generate-notes --notes-start-tag "$previous" env: TAG: ${{ needs.version.outputs.tag }} GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/vm-tools.yml b/.github/workflows/vm-tools.yml new file mode 100644 index 00000000..f5ce12b0 --- /dev/null +++ b/.github/workflows/vm-tools.yml @@ -0,0 +1,68 @@ +# Builds the bundle of T3's latest stable release, Codex and Claude Code that VM setup downloads instead of +# installing them from npm (vmTools in apps/server/src/vm/runtime.ts), and publishes it to the "vm-tools" +# prerelease. Every two days, so new VMs get T3 releases and agent updates; by hand from the Actions tab; and as a +# build-only check on pull requests that change it. +name: VM tools + +on: + schedule: + - cron: "23 4 */2 * *" + workflow_dispatch: + pull_request: + paths: + - .github/workflows/vm-tools.yml + - scripts/vm-tools.ts + - apps/server/src/vm/runtime.ts + +# The build installs npm packages, which run their own scripts, so it only gets a read token. +permissions: + contents: read + +concurrency: + group: vm-tools-${{ github.event_name == 'pull_request' && github.ref || 'publish' }} + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version-file: package.json + - run: bun install --frozen-lockfile + # The bundle installs at a VM's own paths. + - run: sudo mkdir /workspace && sudo chown "$USER" /workspace + - run: bun scripts/vm-tools.ts dist/vm-tools + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: vm-tools + path: dist/vm-tools/* + + # The only job with write access. It never checks out the repo or runs package code. + publish: + needs: build + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + permissions: + contents: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: vm-tools + path: dist + # A prerelease, so VM Bridge's update check and install.sh, which read the latest release, never see it. + - run: | + gh release view vm-tools > /dev/null 2>&1 || + gh release create vm-tools --prerelease --latest=false --target main --title "VM tools" \ + --notes "T3's latest stable release, Codex and Claude Code, which VM setup downloads instead of installing them from npm. Rebuilt every two days." + gh release upload vm-tools dist/* --clobber + # Keeps the newest three T3 versions' bundles (an archive and its checksum each), for VMs on an older version. + - run: | + gh release view vm-tools --json assets --jq '.assets | sort_by(.createdAt) | reverse | .[6:] | .[].name' | + while read -r name; do gh release delete-asset vm-tools "$name" --yes; done diff --git a/apps/server/src/vm/runtime.ts b/apps/server/src/vm/runtime.ts index 2b44dec7..9fbd0879 100644 --- a/apps/server/src/vm/runtime.ts +++ b/apps/server/src/vm/runtime.ts @@ -1,6 +1,7 @@ import { createHash } from "node:crypto"; import type { AgentSecrets } from "../agent-auth/profiles.ts"; import type { Encryption } from "../encryption.ts"; +import { releaseRepo } from "../release.ts"; import type { Box } from "../providers/index.ts"; import { opencodeConfigPath, screenToolsFiles, screenToolsSetup, type ScreenTools } from "./screen-tools.ts"; @@ -189,6 +190,22 @@ export const openCodeCli = `${openCodeDir}/cli/bin/opencode`; */ export const installOpenCodeCli = `(command -v flock >/dev/null && flock 9; ${openCodeCli} --version 2>/dev/null | grep -qxF "opencode v${openCodeCliVersion}" || npm install -g --prefix ${openCodeDir}/cli --cache ${openCodeDir}/npm-cache --no-audit --no-fund --loglevel=error @opencode/cli@${openCodeCliVersion} >&2) 9>${openCodeDir}/cli.lock`; +/** + * VM Bridge's bundle of one `t3` version, its runtime, and the newest Codex and Claude Code, installed under `root` on + * x64 glibc Linux. scripts/vm-tools.ts builds it, and .github/workflows/vm-tools.yml publishes it every two days with + * T3's latest stable release, so a VM without the agent CLIs gets them in one download instead of npm installs. + */ +export const vmTools = { + url: `https://github.com/${releaseRepo}/releases/download/vm-tools`, + asset: (t3Version: string) => `vm-tools-t3-${t3Version}-linux-x64.tar.gz`, + /** What setup takes from the bundle for each package it lacks, under `root`. `$version` is the `t3` version. */ + parts: { + "t3@*": ["npm/lib/node_modules/t3", "npm/bin/t3", "t3-home/runtime/versions/$version"], + "@openai/codex": ["npm/lib/node_modules/@openai/codex", "npm/bin/codex"], + "@anthropic-ai/claude-code": ["npm/lib/node_modules/@anthropic-ai/claude-code", "npm/bin/claude"], + }, +}; + /** * Idempotent: installs Node when missing, the exact `t3` version, the agent CLIs, gh, and Git access. Connecting skips * it while the VM's stamp matches, so changing this text makes every VM run it once more. @@ -246,12 +263,46 @@ mkdir -p "$root/gh-config" mkdir -p ${openCodeDir} setsid nohup bash -c ${quote(installOpenCodeCli)} > ${openCodeDir}/install.log 2>&1 < /dev/null & -# Images usually have Node and the agent CLIs already: install only what is missing, in one npm run. -missing=() -installed="$(node -p "require('$root/npm/lib/node_modules/t3/package.json').version" 2>/dev/null || true)" -[ "$installed" = "$version" ] || missing+=("t3@$version") -command -v codex >/dev/null || missing+=(@openai/codex) -command -v claude >/dev/null || missing+=(@anthropic-ai/claude-code) +# Images usually have Node and the agent CLIs already: install only what is missing. +find_missing() { + missing=() + local installed + installed="$(node -p "require('$root/npm/lib/node_modules/t3/package.json').version" 2>/dev/null || true)" + [ "$installed" = "$version" ] || missing+=("t3@$version") + command -v codex >/dev/null || missing+=(@openai/codex) + command -v claude >/dev/null || missing+=(@anthropic-ai/claude-code) +} +find_missing + +# Without an agent CLI, VM Bridge's bundle (vmTools) brings what is missing in one download from GitHub. Anything it +# cannot bring, such as a T3 release newer than the bundle, or a bundle that fails its checksum, comes from npm below. +# Every step is chained, as set -e does not apply inside a function called with ||. +take_from_bundle() { + local file + file=${vmTools.asset("$version")} + bundle="$(mktemp -d "$root/bundle.XXXXXX")" && + fetch "${vmTools.url}/$file" > "$bundle/$file" && + fetch "${vmTools.url}/$file.sha256" > "$bundle/$file.sha256" && + (cd "$bundle" && sha256sum --check --status "$file.sha256") && + tar -xzf "$bundle/$file" --no-same-owner -C "$bundle" || return 1 + local package part + for package in "\${missing[@]}"; do + case "$package" in + ${Object.entries(vmTools.parts) + .map(([pattern, parts]) => `${pattern}) set -- ${parts.map((part) => `"${part}"`).join(" ")} ;;`) + .join("\n ")} + esac + # Renames on the same disk: a part is never left half-copied. + for part; do + mkdir -p "$root/$(dirname "$part")" && rm -rf "\${root:?}/$part" && mv "$bundle/$part" "$root/$part" || return 1 + done + done +} +if { ! command -v codex >/dev/null || ! command -v claude >/dev/null; } && [ "$(uname -m)" = x86_64 ] && getconf GNU_LIBC_VERSION >/dev/null 2>&1; then + take_from_bundle || echo "Could not use VM Bridge's bundle for T3 $version. Installing from npm." >&2 + rm -rf "\${bundle:-}" + find_missing +fi [ \${#missing[@]} -eq 0 ] || npm install -g --prefix "$root/npm" --no-audit --no-fund --loglevel=error "\${missing[@]}" mkdir -p "$root/codex" "$root/claude" # The npm launcher downloads the T3 runtime on first use. Do it now rather than during a request. diff --git a/apps/server/test/setup.test.ts b/apps/server/test/setup.test.ts index dfe4e78e..df82741c 100644 --- a/apps/server/test/setup.test.ts +++ b/apps/server/test/setup.test.ts @@ -3,14 +3,17 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSyn import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Box } from "../src/providers/index.ts"; -import { prepareVm, setupStamp, t3Port, type VmCredentials } from "../src/vm/runtime.ts"; +import { prepareVm, setupStamp, t3Port, vmTools, type VmCredentials } from "../src/vm/runtime.ts"; // A curl that logs every URL and answers only GitHub CLI release downloads, with a fake gh of the asked version, -// and only when GH_DOWNLOADS is set. Everything else fails, as GitHub's API does for anonymous calls from boxd. +// and only when GH_DOWNLOADS is set, and VM Bridge's bundle, from the folder in BUNDLE. Everything else fails, as +// GitHub's API does for anonymous calls from boxd. const fakeCurl = `#!/bin/bash for url; do :; done echo "$url" >> "$CURL_LOG" case "$url" in + ${vmTools.url}/*) + [ -n "\${BUNDLE:-}" ] && cat "$BUNDLE/\${url##*/}" ;; https://github.com/cli/cli/releases/download/*) [ -n "\${GH_DOWNLOADS:-}" ] || exit 22 version="\${url##*/gh_}"; version="\${version%%_linux*}" @@ -57,8 +60,10 @@ beforeEach(() => { }); const bin = join(dir, "bin"); mkdirSync(bin); - // npm logs what it was asked to install. t3 and codex are on the image; claude is not. - for (const [name, text] of Object.entries({ curl: fakeCurl, npm: '#!/bin/sh\necho "$*" >> "$NPM_LOG"\n', t3: "#!/bin/sh\n", codex: "#!/bin/sh\n" })) { + // npm logs what it was asked to install. t3 and codex are on the image; claude is not. Not glibc, so setup leaves + // VM Bridge's bundle alone, as it would on macOS, wherever the tests run. + const fakes = { curl: fakeCurl, npm: '#!/bin/sh\necho "$*" >> "$NPM_LOG"\n', t3: "#!/bin/sh\n", codex: "#!/bin/sh\n", getconf: "#!/bin/sh\nexit 1\n" }; + for (const [name, text] of Object.entries(fakes)) { writeFileSync(join(bin, name), text); chmodSync(join(bin, name), 0o755); } @@ -166,6 +171,47 @@ describe("VM setup", () => { expect(readFileSync(vmFile("setup-stamp"), "utf8")).toBe(setupStamp("1.0.1")); }); + test("on x64 glibc Linux, takes what is missing from VM Bridge's bundle, and installs from npm when it fails its checksum", async () => { + for (const [name, text] of Object.entries({ uname: "#!/bin/sh\necho x86_64\n", getconf: "#!/bin/sh\necho glibc 2.39\n" })) { + writeFileSync(join(dir, "bin", name), text); + chmodSync(join(dir, "bin", name), 0o755); + } + symlinkSync(Bun.which("sha256sum")!, join(dir, "bin", "sha256sum")); + // A bundle laid out as scripts/vm-tools.ts builds it: each part's tool answers with where it came from. + const tree = join(dir, "tree"); + for (const part of Object.values(vmTools.parts).flat()) mkdirSync(join(tree, part.replace("$version", "1.0.0")), { recursive: true }); + for (const tool of ["t3", "codex", "claude"]) { + rmSync(join(tree, "npm/bin", tool), { recursive: true }); + writeFileSync(join(tree, "npm/bin", tool), `#!/bin/sh\necho bundle\n`); + chmodSync(join(tree, "npm/bin", tool), 0o755); + } + writeFileSync(join(tree, "npm/lib/node_modules/t3/package.json"), '{"version":"1.0.0"}'); + env.BUNDLE = join(dir, "bundle"); + mkdirSync(env.BUNDLE); + const file = vmTools.asset("1.0.0"); + Bun.spawnSync(["tar", "-czf", join(env.BUNDLE, file), "-C", tree, "npm", "t3-home"]); + writeFileSync(join(env.BUNDLE, `${file}.sha256`), Bun.spawnSync(["sha256sum", file], { cwd: env.BUNDLE }).stdout); + const installs = () => log("npm.log").filter((line) => !line.includes("@opencode/cli@")); + + await prepareVm(box, "1.0.0", {}, "fingerprint"); + expect(installs()).toEqual([]); + // t3 at another version and claude came from the bundle; the image's codex stays the one used. + expect(Bun.spawnSync([vmFile("npm/bin/claude")]).stdout.toString()).toBe("bundle\n"); + expect(existsSync(vmFile("npm/lib/node_modules/t3/package.json"))).toBe(true); + expect(existsSync(vmFile("t3-home/runtime/versions/1.0.0"))).toBe(true); + expect(existsSync(vmFile("npm/bin/codex"))).toBe(false); + expect(readdirSync(vmFile("")).filter((name) => name.startsWith("bundle."))).toEqual([]); + + // A newer T3 than the bundle has: its checksum file names another archive, so npm installs it. + writeFileSync(join(env.BUNDLE, `${vmTools.asset("1.0.1")}.sha256`), `${"0".repeat(64)} ${vmTools.asset("1.0.1")}\n`); + writeFileSync(join(env.BUNDLE, vmTools.asset("1.0.1")), "not this"); + rmSync(vmFile("npm/bin/claude")); + await prepareVm(box, "1.0.1", {}, "fingerprint"); + expect(runs.at(-1)!.stderr).toContain("Could not use VM Bridge's bundle for T3 1.0.1. Installing from npm."); + expect(installs()).toEqual([expect.stringMatching(/ t3@1\.0\.1 @anthropic-ai\/claude-code$/)]); + expect(readdirSync(vmFile("")).filter((name) => name.startsWith("bundle."))).toEqual([]); + }); + test("one exec writes the sign-ins from stdin and reports T3, its sign-ins and the skills manifest", async () => { const credentials: VmCredentials = { github: { token: "github_pat_secret", login: "octo", name: "Octo Cat", email: "octo@example.test" }, diff --git a/scripts/vm-tools.ts b/scripts/vm-tools.ts new file mode 100644 index 00000000..29665976 --- /dev/null +++ b/scripts/vm-tools.ts @@ -0,0 +1,34 @@ +// Builds the VM tools bundle (vmTools in apps/server/src/vm/runtime.ts) for T3's latest stable release, into the folder +// given (dist/vm-tools by default): the archive and its SHA-256 file. It installs at a VM's own paths, so it needs x64 +// Linux with /workspace writable and no /workspace/.vmbridge yet, as in .github/workflows/vm-tools.yml. +import { $ } from "bun"; +import { existsSync, mkdirSync } from "node:fs"; +import { resolve } from "node:path"; +import { resolveT3Version, root, vmTools } from "../apps/server/src/vm/runtime.ts"; + +if (process.platform !== "linux" || process.arch !== "x64") throw new Error("Build the bundle on x64 Linux, where the VMs that use it run."); +if (existsSync(root)) throw new Error(`${root} already exists. Build the bundle on a machine without one.`); +const out = resolve(process.argv[2] ?? "dist/vm-tools"); + +// npm's `latest` tag: T3's stable release, never a nightly or preview. +const version = await resolveT3Version(null); +await $`npm install -g --prefix ${root}/npm --no-audit --no-fund --loglevel=error t3@${version} @openai/codex @anthropic-ai/claude-code`; +// The launcher downloads T3's runtime on first use, into T3CODE_HOME, as setup has it do on a VM. +await $`${root}/npm/bin/t3 --version`.env({ ...process.env, T3CODE_HOME: `${root}/t3-home` }); + +const parts = Object.values(vmTools.parts).flatMap((paths) => paths.map((path) => path.replace("$version", version))); +const lacking = parts.filter((part) => !existsSync(`${root}/${part}`)); +if (lacking.length > 0) throw new Error(`The bundle lacks ${lacking.join(", ")}: npm's layout no longer matches vmTools.parts.`); + +mkdirSync(out, { recursive: true }); +const file = vmTools.asset(version); +await $`tar -czf ${out}/${file} -C ${root} ${parts}`; +await $`sha256sum ${file} > ${file}.sha256`.cwd(out); + +// What a VM gets is the archive alone: unpack it where npm installed, and run each tool from it. T3's runtime must be +// complete, or its launcher would download it again on the VM. +await $`rm -rf ${root} && mkdir -p ${root} && tar -xzf ${out}/${file} -C ${root}`; +if ((await Bun.file(`${root}/t3-home/runtime/versions/${version}/.install-complete`).text()).trim() !== version) throw new Error("T3's runtime is incomplete."); +const versions = await Promise.all(["t3", "codex", "claude"].map((tool) => $`${root}/npm/bin/${tool} --version`.env({ ...process.env, T3CODE_HOME: `${root}/t3-home` }).text())); +const { size } = Bun.file(`${out}/${file}`); +console.log(`Built ${file} (${(size / 2 ** 20).toFixed(0)} MB): t3, codex and claude answer ${versions.map((text) => text.trim()).join(", ")}.`); From af942df3e2b5d5ed2eec1f00d866a7061f433dc1 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Mon, 30 Nov 2026 17:10:42 +0530 Subject: [PATCH 08/10] revert: the VM tools bundle, slower than npm on Vast.ai hosts --- .github/workflows/release.yml | 5 +-- .github/workflows/vm-tools.yml | 68 ---------------------------------- apps/server/src/vm/runtime.ts | 63 +++---------------------------- apps/server/test/setup.test.ts | 54 ++------------------------- scripts/vm-tools.ts | 34 ----------------- 5 files changed, 11 insertions(+), 213 deletions(-) delete mode 100644 .github/workflows/vm-tools.yml delete mode 100644 scripts/vm-tools.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f23f1344..e6ab53a9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -132,10 +132,7 @@ jobs: - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 with: subject-path: dist/* - # The notes start at the previous VM Bridge release, never at the "vm-tools" prerelease (see vm-tools.yml). - - run: | - previous=$(gh release view --repo "$GITHUB_REPOSITORY" --json tagName --jq .tagName) - gh release create "$TAG" dist/* --repo "$GITHUB_REPOSITORY" --title "$TAG" --generate-notes --notes-start-tag "$previous" + - run: gh release create "$TAG" dist/* --repo "$GITHUB_REPOSITORY" --title "$TAG" --generate-notes env: TAG: ${{ needs.version.outputs.tag }} GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/vm-tools.yml b/.github/workflows/vm-tools.yml deleted file mode 100644 index f5ce12b0..00000000 --- a/.github/workflows/vm-tools.yml +++ /dev/null @@ -1,68 +0,0 @@ -# Builds the bundle of T3's latest stable release, Codex and Claude Code that VM setup downloads instead of -# installing them from npm (vmTools in apps/server/src/vm/runtime.ts), and publishes it to the "vm-tools" -# prerelease. Every two days, so new VMs get T3 releases and agent updates; by hand from the Actions tab; and as a -# build-only check on pull requests that change it. -name: VM tools - -on: - schedule: - - cron: "23 4 */2 * *" - workflow_dispatch: - pull_request: - paths: - - .github/workflows/vm-tools.yml - - scripts/vm-tools.ts - - apps/server/src/vm/runtime.ts - -# The build installs npm packages, which run their own scripts, so it only gets a read token. -permissions: - contents: read - -concurrency: - group: vm-tools-${{ github.event_name == 'pull_request' && github.ref || 'publish' }} - cancel-in-progress: false - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version-file: package.json - - run: bun install --frozen-lockfile - # The bundle installs at a VM's own paths. - - run: sudo mkdir /workspace && sudo chown "$USER" /workspace - - run: bun scripts/vm-tools.ts dist/vm-tools - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: vm-tools - path: dist/vm-tools/* - - # The only job with write access. It never checks out the repo or runs package code. - publish: - needs: build - if: github.event_name != 'pull_request' - runs-on: ubuntu-latest - permissions: - contents: write - env: - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - steps: - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - name: vm-tools - path: dist - # A prerelease, so VM Bridge's update check and install.sh, which read the latest release, never see it. - - run: | - gh release view vm-tools > /dev/null 2>&1 || - gh release create vm-tools --prerelease --latest=false --target main --title "VM tools" \ - --notes "T3's latest stable release, Codex and Claude Code, which VM setup downloads instead of installing them from npm. Rebuilt every two days." - gh release upload vm-tools dist/* --clobber - # Keeps the newest three T3 versions' bundles (an archive and its checksum each), for VMs on an older version. - - run: | - gh release view vm-tools --json assets --jq '.assets | sort_by(.createdAt) | reverse | .[6:] | .[].name' | - while read -r name; do gh release delete-asset vm-tools "$name" --yes; done diff --git a/apps/server/src/vm/runtime.ts b/apps/server/src/vm/runtime.ts index 9fbd0879..2b44dec7 100644 --- a/apps/server/src/vm/runtime.ts +++ b/apps/server/src/vm/runtime.ts @@ -1,7 +1,6 @@ import { createHash } from "node:crypto"; import type { AgentSecrets } from "../agent-auth/profiles.ts"; import type { Encryption } from "../encryption.ts"; -import { releaseRepo } from "../release.ts"; import type { Box } from "../providers/index.ts"; import { opencodeConfigPath, screenToolsFiles, screenToolsSetup, type ScreenTools } from "./screen-tools.ts"; @@ -190,22 +189,6 @@ export const openCodeCli = `${openCodeDir}/cli/bin/opencode`; */ export const installOpenCodeCli = `(command -v flock >/dev/null && flock 9; ${openCodeCli} --version 2>/dev/null | grep -qxF "opencode v${openCodeCliVersion}" || npm install -g --prefix ${openCodeDir}/cli --cache ${openCodeDir}/npm-cache --no-audit --no-fund --loglevel=error @opencode/cli@${openCodeCliVersion} >&2) 9>${openCodeDir}/cli.lock`; -/** - * VM Bridge's bundle of one `t3` version, its runtime, and the newest Codex and Claude Code, installed under `root` on - * x64 glibc Linux. scripts/vm-tools.ts builds it, and .github/workflows/vm-tools.yml publishes it every two days with - * T3's latest stable release, so a VM without the agent CLIs gets them in one download instead of npm installs. - */ -export const vmTools = { - url: `https://github.com/${releaseRepo}/releases/download/vm-tools`, - asset: (t3Version: string) => `vm-tools-t3-${t3Version}-linux-x64.tar.gz`, - /** What setup takes from the bundle for each package it lacks, under `root`. `$version` is the `t3` version. */ - parts: { - "t3@*": ["npm/lib/node_modules/t3", "npm/bin/t3", "t3-home/runtime/versions/$version"], - "@openai/codex": ["npm/lib/node_modules/@openai/codex", "npm/bin/codex"], - "@anthropic-ai/claude-code": ["npm/lib/node_modules/@anthropic-ai/claude-code", "npm/bin/claude"], - }, -}; - /** * Idempotent: installs Node when missing, the exact `t3` version, the agent CLIs, gh, and Git access. Connecting skips * it while the VM's stamp matches, so changing this text makes every VM run it once more. @@ -263,46 +246,12 @@ mkdir -p "$root/gh-config" mkdir -p ${openCodeDir} setsid nohup bash -c ${quote(installOpenCodeCli)} > ${openCodeDir}/install.log 2>&1 < /dev/null & -# Images usually have Node and the agent CLIs already: install only what is missing. -find_missing() { - missing=() - local installed - installed="$(node -p "require('$root/npm/lib/node_modules/t3/package.json').version" 2>/dev/null || true)" - [ "$installed" = "$version" ] || missing+=("t3@$version") - command -v codex >/dev/null || missing+=(@openai/codex) - command -v claude >/dev/null || missing+=(@anthropic-ai/claude-code) -} -find_missing - -# Without an agent CLI, VM Bridge's bundle (vmTools) brings what is missing in one download from GitHub. Anything it -# cannot bring, such as a T3 release newer than the bundle, or a bundle that fails its checksum, comes from npm below. -# Every step is chained, as set -e does not apply inside a function called with ||. -take_from_bundle() { - local file - file=${vmTools.asset("$version")} - bundle="$(mktemp -d "$root/bundle.XXXXXX")" && - fetch "${vmTools.url}/$file" > "$bundle/$file" && - fetch "${vmTools.url}/$file.sha256" > "$bundle/$file.sha256" && - (cd "$bundle" && sha256sum --check --status "$file.sha256") && - tar -xzf "$bundle/$file" --no-same-owner -C "$bundle" || return 1 - local package part - for package in "\${missing[@]}"; do - case "$package" in - ${Object.entries(vmTools.parts) - .map(([pattern, parts]) => `${pattern}) set -- ${parts.map((part) => `"${part}"`).join(" ")} ;;`) - .join("\n ")} - esac - # Renames on the same disk: a part is never left half-copied. - for part; do - mkdir -p "$root/$(dirname "$part")" && rm -rf "\${root:?}/$part" && mv "$bundle/$part" "$root/$part" || return 1 - done - done -} -if { ! command -v codex >/dev/null || ! command -v claude >/dev/null; } && [ "$(uname -m)" = x86_64 ] && getconf GNU_LIBC_VERSION >/dev/null 2>&1; then - take_from_bundle || echo "Could not use VM Bridge's bundle for T3 $version. Installing from npm." >&2 - rm -rf "\${bundle:-}" - find_missing -fi +# Images usually have Node and the agent CLIs already: install only what is missing, in one npm run. +missing=() +installed="$(node -p "require('$root/npm/lib/node_modules/t3/package.json').version" 2>/dev/null || true)" +[ "$installed" = "$version" ] || missing+=("t3@$version") +command -v codex >/dev/null || missing+=(@openai/codex) +command -v claude >/dev/null || missing+=(@anthropic-ai/claude-code) [ \${#missing[@]} -eq 0 ] || npm install -g --prefix "$root/npm" --no-audit --no-fund --loglevel=error "\${missing[@]}" mkdir -p "$root/codex" "$root/claude" # The npm launcher downloads the T3 runtime on first use. Do it now rather than during a request. diff --git a/apps/server/test/setup.test.ts b/apps/server/test/setup.test.ts index df82741c..dfe4e78e 100644 --- a/apps/server/test/setup.test.ts +++ b/apps/server/test/setup.test.ts @@ -3,17 +3,14 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSyn import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Box } from "../src/providers/index.ts"; -import { prepareVm, setupStamp, t3Port, vmTools, type VmCredentials } from "../src/vm/runtime.ts"; +import { prepareVm, setupStamp, t3Port, type VmCredentials } from "../src/vm/runtime.ts"; // A curl that logs every URL and answers only GitHub CLI release downloads, with a fake gh of the asked version, -// and only when GH_DOWNLOADS is set, and VM Bridge's bundle, from the folder in BUNDLE. Everything else fails, as -// GitHub's API does for anonymous calls from boxd. +// and only when GH_DOWNLOADS is set. Everything else fails, as GitHub's API does for anonymous calls from boxd. const fakeCurl = `#!/bin/bash for url; do :; done echo "$url" >> "$CURL_LOG" case "$url" in - ${vmTools.url}/*) - [ -n "\${BUNDLE:-}" ] && cat "$BUNDLE/\${url##*/}" ;; https://github.com/cli/cli/releases/download/*) [ -n "\${GH_DOWNLOADS:-}" ] || exit 22 version="\${url##*/gh_}"; version="\${version%%_linux*}" @@ -60,10 +57,8 @@ beforeEach(() => { }); const bin = join(dir, "bin"); mkdirSync(bin); - // npm logs what it was asked to install. t3 and codex are on the image; claude is not. Not glibc, so setup leaves - // VM Bridge's bundle alone, as it would on macOS, wherever the tests run. - const fakes = { curl: fakeCurl, npm: '#!/bin/sh\necho "$*" >> "$NPM_LOG"\n', t3: "#!/bin/sh\n", codex: "#!/bin/sh\n", getconf: "#!/bin/sh\nexit 1\n" }; - for (const [name, text] of Object.entries(fakes)) { + // npm logs what it was asked to install. t3 and codex are on the image; claude is not. + for (const [name, text] of Object.entries({ curl: fakeCurl, npm: '#!/bin/sh\necho "$*" >> "$NPM_LOG"\n', t3: "#!/bin/sh\n", codex: "#!/bin/sh\n" })) { writeFileSync(join(bin, name), text); chmodSync(join(bin, name), 0o755); } @@ -171,47 +166,6 @@ describe("VM setup", () => { expect(readFileSync(vmFile("setup-stamp"), "utf8")).toBe(setupStamp("1.0.1")); }); - test("on x64 glibc Linux, takes what is missing from VM Bridge's bundle, and installs from npm when it fails its checksum", async () => { - for (const [name, text] of Object.entries({ uname: "#!/bin/sh\necho x86_64\n", getconf: "#!/bin/sh\necho glibc 2.39\n" })) { - writeFileSync(join(dir, "bin", name), text); - chmodSync(join(dir, "bin", name), 0o755); - } - symlinkSync(Bun.which("sha256sum")!, join(dir, "bin", "sha256sum")); - // A bundle laid out as scripts/vm-tools.ts builds it: each part's tool answers with where it came from. - const tree = join(dir, "tree"); - for (const part of Object.values(vmTools.parts).flat()) mkdirSync(join(tree, part.replace("$version", "1.0.0")), { recursive: true }); - for (const tool of ["t3", "codex", "claude"]) { - rmSync(join(tree, "npm/bin", tool), { recursive: true }); - writeFileSync(join(tree, "npm/bin", tool), `#!/bin/sh\necho bundle\n`); - chmodSync(join(tree, "npm/bin", tool), 0o755); - } - writeFileSync(join(tree, "npm/lib/node_modules/t3/package.json"), '{"version":"1.0.0"}'); - env.BUNDLE = join(dir, "bundle"); - mkdirSync(env.BUNDLE); - const file = vmTools.asset("1.0.0"); - Bun.spawnSync(["tar", "-czf", join(env.BUNDLE, file), "-C", tree, "npm", "t3-home"]); - writeFileSync(join(env.BUNDLE, `${file}.sha256`), Bun.spawnSync(["sha256sum", file], { cwd: env.BUNDLE }).stdout); - const installs = () => log("npm.log").filter((line) => !line.includes("@opencode/cli@")); - - await prepareVm(box, "1.0.0", {}, "fingerprint"); - expect(installs()).toEqual([]); - // t3 at another version and claude came from the bundle; the image's codex stays the one used. - expect(Bun.spawnSync([vmFile("npm/bin/claude")]).stdout.toString()).toBe("bundle\n"); - expect(existsSync(vmFile("npm/lib/node_modules/t3/package.json"))).toBe(true); - expect(existsSync(vmFile("t3-home/runtime/versions/1.0.0"))).toBe(true); - expect(existsSync(vmFile("npm/bin/codex"))).toBe(false); - expect(readdirSync(vmFile("")).filter((name) => name.startsWith("bundle."))).toEqual([]); - - // A newer T3 than the bundle has: its checksum file names another archive, so npm installs it. - writeFileSync(join(env.BUNDLE, `${vmTools.asset("1.0.1")}.sha256`), `${"0".repeat(64)} ${vmTools.asset("1.0.1")}\n`); - writeFileSync(join(env.BUNDLE, vmTools.asset("1.0.1")), "not this"); - rmSync(vmFile("npm/bin/claude")); - await prepareVm(box, "1.0.1", {}, "fingerprint"); - expect(runs.at(-1)!.stderr).toContain("Could not use VM Bridge's bundle for T3 1.0.1. Installing from npm."); - expect(installs()).toEqual([expect.stringMatching(/ t3@1\.0\.1 @anthropic-ai\/claude-code$/)]); - expect(readdirSync(vmFile("")).filter((name) => name.startsWith("bundle."))).toEqual([]); - }); - test("one exec writes the sign-ins from stdin and reports T3, its sign-ins and the skills manifest", async () => { const credentials: VmCredentials = { github: { token: "github_pat_secret", login: "octo", name: "Octo Cat", email: "octo@example.test" }, diff --git a/scripts/vm-tools.ts b/scripts/vm-tools.ts deleted file mode 100644 index 29665976..00000000 --- a/scripts/vm-tools.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Builds the VM tools bundle (vmTools in apps/server/src/vm/runtime.ts) for T3's latest stable release, into the folder -// given (dist/vm-tools by default): the archive and its SHA-256 file. It installs at a VM's own paths, so it needs x64 -// Linux with /workspace writable and no /workspace/.vmbridge yet, as in .github/workflows/vm-tools.yml. -import { $ } from "bun"; -import { existsSync, mkdirSync } from "node:fs"; -import { resolve } from "node:path"; -import { resolveT3Version, root, vmTools } from "../apps/server/src/vm/runtime.ts"; - -if (process.platform !== "linux" || process.arch !== "x64") throw new Error("Build the bundle on x64 Linux, where the VMs that use it run."); -if (existsSync(root)) throw new Error(`${root} already exists. Build the bundle on a machine without one.`); -const out = resolve(process.argv[2] ?? "dist/vm-tools"); - -// npm's `latest` tag: T3's stable release, never a nightly or preview. -const version = await resolveT3Version(null); -await $`npm install -g --prefix ${root}/npm --no-audit --no-fund --loglevel=error t3@${version} @openai/codex @anthropic-ai/claude-code`; -// The launcher downloads T3's runtime on first use, into T3CODE_HOME, as setup has it do on a VM. -await $`${root}/npm/bin/t3 --version`.env({ ...process.env, T3CODE_HOME: `${root}/t3-home` }); - -const parts = Object.values(vmTools.parts).flatMap((paths) => paths.map((path) => path.replace("$version", version))); -const lacking = parts.filter((part) => !existsSync(`${root}/${part}`)); -if (lacking.length > 0) throw new Error(`The bundle lacks ${lacking.join(", ")}: npm's layout no longer matches vmTools.parts.`); - -mkdirSync(out, { recursive: true }); -const file = vmTools.asset(version); -await $`tar -czf ${out}/${file} -C ${root} ${parts}`; -await $`sha256sum ${file} > ${file}.sha256`.cwd(out); - -// What a VM gets is the archive alone: unpack it where npm installed, and run each tool from it. T3's runtime must be -// complete, or its launcher would download it again on the VM. -await $`rm -rf ${root} && mkdir -p ${root} && tar -xzf ${out}/${file} -C ${root}`; -if ((await Bun.file(`${root}/t3-home/runtime/versions/${version}/.install-complete`).text()).trim() !== version) throw new Error("T3's runtime is incomplete."); -const versions = await Promise.all(["t3", "codex", "claude"].map((tool) => $`${root}/npm/bin/${tool} --version`.env({ ...process.env, T3CODE_HOME: `${root}/t3-home` }).text())); -const { size } = Bun.file(`${out}/${file}`); -console.log(`Built ${file} (${(size / 2 ** 20).toFixed(0)} MB): t3, codex and claude answer ${versions.map((text) => text.trim()).join(", ")}.`); From e7ebff78c2edf0e4d486c27033fce03a7784fe4c Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Mon, 30 Nov 2026 17:51:10 +0530 Subject: [PATCH 09/10] perf: new VMs download T3's runtime while npm installs the agents --- apps/server/src/vm/runtime.ts | 59 ++++++++++++++++++---------------- apps/server/test/setup.test.ts | 29 ++++++++++++++--- 2 files changed, 56 insertions(+), 32 deletions(-) diff --git a/apps/server/src/vm/runtime.ts b/apps/server/src/vm/runtime.ts index 2b44dec7..683db4e2 100644 --- a/apps/server/src/vm/runtime.ts +++ b/apps/server/src/vm/runtime.ts @@ -204,24 +204,6 @@ stamp="$2" fetch() { if command -v curl >/dev/null; then curl -fsSL "$1"; else wget -qO- "$1"; fi; } -# t3 needs Node 20.11 or later (import.meta.dirname). E2B's base image has 20.9. -node_ok() { - command -v node >/dev/null || return 1 - node -e 'const [major, minor] = process.versions.node.split(".").map(Number); process.exit(major > 20 || (major === 20 && minor >= 11) ? 0 : 1)' -} -if ! node_ok; then - case "$(uname -m)" in x86_64) arch=x64 ;; aarch64|arm64) arch=arm64 ;; *) echo "unsupported CPU" >&2; exit 70 ;; esac - base=https://nodejs.org/dist/latest-v22.x - file="$(fetch "$base/SHASUMS256.txt" | awk -v a="linux-$arch.tar.gz" '$2 ~ a { print $2 }')" - rm -rf "$root/node" && mkdir -p "$root/node" - fetch "$base/$file" | tar -xz -C "$root/node" --strip-components=1 -fi - -if ! command -v git >/dev/null; then - if command -v sudo >/dev/null; then sudo -n apt-get update -qq && sudo -n apt-get install -y -qq git - else apt-get update -qq && apt-get install -y -qq git; fi -fi - # The GitHub CLI, for agents opening pull requests. It signs in with GH_TOKEN. A pinned release, as GitHub's API # refuses anonymous calls from IPs that many VMs share (boxd), while release downloads have no such limit. # Optional: setup goes on without it. Every step is chained, as set -e does not apply inside a function called with ||. @@ -234,28 +216,51 @@ install_gh() { fetch "https://github.com/cli/cli/releases/download/v$ghversion/gh_\${ghversion}_linux_$gharch.tar.gz" | tar -xz -C "$ghnew" --strip-components=1 && rm -rf "$root/gh" && mv "$ghnew" "$root/gh" } -# Beside the npm install below. +# In the background, from the start: it needs neither Node nor npm. if ! "$root/gh/bin/gh" --version 2>/dev/null | grep -Fq "version $ghversion "; then { install_gh || { rm -rf "\${ghnew:-}"; echo "Could not install the GitHub CLI $ghversion. Setup goes on without it." >&2; }; } & gh_pid=$! fi mkdir -p "$root/gh-config" +# t3 needs Node 20.11 or later (import.meta.dirname). E2B's base image has 20.9. +node_ok() { + command -v node >/dev/null || return 1 + node -e 'const [major, minor] = process.versions.node.split(".").map(Number); process.exit(major > 20 || (major === 20 && minor >= 11) ? 0 : 1)' +} +if ! node_ok; then + case "$(uname -m)" in x86_64) arch=x64 ;; aarch64|arm64) arch=arm64 ;; *) echo "unsupported CPU" >&2; exit 70 ;; esac + base=https://nodejs.org/dist/latest-v22.x + file="$(fetch "$base/SHASUMS256.txt" | awk -v a="linux-$arch.tar.gz" '$2 ~ a { print $2 }')" + rm -rf "$root/node" && mkdir -p "$root/node" + fetch "$base/$file" | tar -xz -C "$root/node" --strip-components=1 +fi + +if ! command -v git >/dev/null; then + if command -v sudo >/dev/null; then sudo -n apt-get update -qq && sudo -n apt-get install -y -qq git + else apt-get update -qq && apt-get install -y -qq git; fi +fi + # OpenCode's CLI, for \`vb opencode\`, in the background: setup does not wait for it, and OpenCode's start waits only # if it is still installing then. mkdir -p ${openCodeDir} setsid nohup bash -c ${quote(installOpenCodeCli)} > ${openCodeDir}/install.log 2>&1 < /dev/null & -# Images usually have Node and the agent CLIs already: install only what is missing, in one npm run. -missing=() +# Images usually have Node and the agent CLIs already: install only what is missing. T3 goes first, on its own: its +# npm launcher downloads T3's runtime on first use, which takes about as long as installing the agent CLIs, so that +# download runs beside their npm install rather than during a request. +npm_install() { npm install -g --prefix "$root/npm" --no-audit --no-fund --loglevel=error "$@"; } installed="$(node -p "require('$root/npm/lib/node_modules/t3/package.json').version" 2>/dev/null || true)" -[ "$installed" = "$version" ] || missing+=("t3@$version") -command -v codex >/dev/null || missing+=(@openai/codex) -command -v claude >/dev/null || missing+=(@anthropic-ai/claude-code) -[ \${#missing[@]} -eq 0 ] || npm install -g --prefix "$root/npm" --no-audit --no-fund --loglevel=error "\${missing[@]}" +[ "$installed" = "$version" ] || npm_install "t3@$version" +# Tried twice: the launcher does not resume a download cut off partway, and the second try starts it over. +{ t3 --version >/dev/null || t3 --version >/dev/null; } & +t3_pid=$! +agents=() +command -v codex >/dev/null || agents+=(@openai/codex) +command -v claude >/dev/null || agents+=(@anthropic-ai/claude-code) +[ \${#agents[@]} -eq 0 ] || npm_install "\${agents[@]}" mkdir -p "$root/codex" "$root/claude" -# The npm launcher downloads the T3 runtime on first use. Do it now rather than during a request. -t3 --version >/dev/null +wait "$t3_pid" [ -z "\${gh_pid:-}" ] || wait "$gh_pid" git config --global --get-all include.path | grep -Fxq "$root/gitconfig" || git config --global --add include.path "$root/gitconfig" diff --git a/apps/server/test/setup.test.ts b/apps/server/test/setup.test.ts index dfe4e78e..89cab4b9 100644 --- a/apps/server/test/setup.test.ts +++ b/apps/server/test/setup.test.ts @@ -149,23 +149,42 @@ describe("VM setup", () => { expect(log("curl.log")).toHaveLength(1); }); - test("installs only what is missing in one npm run, then skips setup until the T3 version changes", async () => { + test("installs only what is missing, then skips setup until the T3 version changes", async () => { // OpenCode's CLI installs in the background, and may or may not have started by the time the log is read. const installs = () => log("npm.log").filter((line) => !line.includes("@opencode/cli@")); await prepareVm(box, "1.0.0", {}, "fingerprint"); - expect(installs()).toEqual([expect.stringMatching(/ t3@1\.0\.0 @anthropic-ai\/claude-code$/)]); + expect(installs()).toEqual([expect.stringMatching(/ t3@1\.0\.0$/), expect.stringMatching(/ @anthropic-ai\/claude-code$/)]); expect(readFileSync(vmFile("setup-stamp"), "utf8")).toBe(setupStamp("1.0.0")); await prepareVm(box, "1.0.0", {}, "fingerprint"); - expect(installs()).toHaveLength(1); + expect(installs()).toHaveLength(2); expect(log("curl.log")).toHaveLength(1); await prepareVm(box, "1.0.1", {}, "fingerprint"); - expect(installs()).toHaveLength(2); - expect(installs()[1]).toContain(" t3@1.0.1 "); + expect(installs().slice(2)).toEqual([expect.stringMatching(/ t3@1\.0\.1$/), expect.stringMatching(/ @anthropic-ai\/claude-code$/)]); expect(readFileSync(vmFile("setup-stamp"), "utf8")).toBe(setupStamp("1.0.1")); }); + test("T3's runtime downloads while npm installs the agent CLIs, and setup waits for both", async () => { + // A launcher that takes a moment to download, and an npm that notes when it runs. Each writes to the same log. + writeFileSync(join(dir, "bin", "t3"), '#!/bin/sh\necho "t3 start" >> "$NPM_LOG"; sleep 1; echo "t3 done" >> "$NPM_LOG"\n'); + await prepareVm(box, "1.0.0", {}, "fingerprint"); + const order = log("npm.log").filter((line) => !line.includes("@opencode/cli@")).map((line) => line.replace(/^install .* /, "npm ")); + expect(order.toSorted()).toEqual(["npm @anthropic-ai/claude-code", "npm t3@1.0.0", "t3 done", "t3 start"]); + // The download starts once T3 is installed, and the agents' install starts before it ends. + expect(order.indexOf("npm t3@1.0.0")).toBeLessThan(order.indexOf("t3 start")); + expect(order.indexOf("npm @anthropic-ai/claude-code")).toBeLessThan(order.indexOf("t3 done")); + expect(readFileSync(vmFile("setup-stamp"), "utf8")).toBe(setupStamp("1.0.0")); + }, 15_000); + + test("a T3 runtime download cut off partway is tried once more", async () => { + // Fails the first time, as the launcher does when the connection drops, then works. + writeFileSync(join(dir, "bin", "t3"), `#!/bin/sh\n[ -e "${dir}/tried" ] && exit 0\ntouch "${dir}/tried"; echo "t3: terminated" >&2; exit 1\n`); + await prepareVm(box, "1.0.0", {}, "fingerprint"); + expect(runs.at(-1)!.stderr).toContain("t3: terminated"); + expect(readFileSync(vmFile("setup-stamp"), "utf8")).toBe(setupStamp("1.0.0")); + }); + test("one exec writes the sign-ins from stdin and reports T3, its sign-ins and the skills manifest", async () => { const credentials: VmCredentials = { github: { token: "github_pat_secret", login: "octo", name: "Octo Cat", email: "octo@example.test" }, From 4306c93494a2c92e22faa4a243b60311e6432051 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Mon, 30 Nov 2026 18:00:23 +0530 Subject: [PATCH 10/10] fix: an agent CLI npm installs without its binary is installed again --- apps/server/src/vm/runtime.ts | 22 +++++++++++++--- apps/server/test/setup.test.ts | 46 +++++++++++++++++++++++++++++++--- 2 files changed, 61 insertions(+), 7 deletions(-) diff --git a/apps/server/src/vm/runtime.ts b/apps/server/src/vm/runtime.ts index 683db4e2..26cce6d0 100644 --- a/apps/server/src/vm/runtime.ts +++ b/apps/server/src/vm/runtime.ts @@ -255,10 +255,24 @@ installed="$(node -p "require('$root/npm/lib/node_modules/t3/package.json').vers # Tried twice: the launcher does not resume a download cut off partway, and the second try starts it over. { t3 --version >/dev/null || t3 --version >/dev/null; } & t3_pid=$! -agents=() -command -v codex >/dev/null || agents+=(@openai/codex) -command -v claude >/dev/null || agents+=(@anthropic-ai/claude-code) -[ \${#agents[@]} -eq 0 ] || npm_install "\${agents[@]}" +# An agent CLI counts only if it runs: when the download of a package's native binary fails, npm leaves the package +# without it and reports success. One that does not run is installed again, once, after removing what npm left. +agents_to_install() { + agents=() + codex --version >/dev/null 2>&1 || agents+=(@openai/codex) + claude --version >/dev/null 2>&1 || agents+=(@anthropic-ai/claude-code) +} +agents_to_install +if [ \${#agents[@]} -gt 0 ]; then + npm_install "\${agents[@]}" + agents_to_install + if [ \${#agents[@]} -gt 0 ]; then + for package in "\${agents[@]}"; do rm -rf "$root/npm/lib/node_modules/$package"; done + npm_install "\${agents[@]}" + agents_to_install + [ \${#agents[@]} -eq 0 ] || { echo "\${agents[*]} installed but does not run, twice. Setup will try again on the next connect." >&2; exit 1; } + fi +fi mkdir -p "$root/codex" "$root/claude" wait "$t3_pid" [ -z "\${gh_pid:-}" ] || wait "$gh_pid" diff --git a/apps/server/test/setup.test.ts b/apps/server/test/setup.test.ts index 89cab4b9..3794a891 100644 --- a/apps/server/test/setup.test.ts +++ b/apps/server/test/setup.test.ts @@ -21,6 +21,27 @@ case "$url" in esac `; +// An npm that logs what it was asked to install and leaves each agent CLI in the prefix. The first BROKEN of those +// do not run, as npm leaves a package when the download of its native binary fails. +const fakeNpm = [ + "#!/bin/bash", + 'echo "$*" >> "$NPM_LOG"', + "prefix=", + "while [ $# -gt 0 ]; do", + ' case "$1" in', + ' --prefix) prefix="$2"; shift ;;', + " @openai/codex|@anthropic-ai/claude-code)", + ' name=codex; [ "$1" = @openai/codex ] || name=claude', + ' mkdir -p "$prefix/bin" "$prefix/lib/node_modules/$1"', + ' count=$(cat "$NPM_LOG.broken" 2>/dev/null || echo 0)', + ' if [ "$count" -lt "${BROKEN:-0}" ]; then echo $((count + 1)) > "$NPM_LOG.broken"; code=1; else code=0; fi', + ' printf \'#!/bin/sh\\nexit %s\\n\' "$code" > "$prefix/bin/$name"; chmod +x "$prefix/bin/$name" ;;', + " esac", + " shift", + "done", + "", +].join("\n"); + let dir: string; let t3: ReturnType; let t3Up: boolean; @@ -57,8 +78,8 @@ beforeEach(() => { }); const bin = join(dir, "bin"); mkdirSync(bin); - // npm logs what it was asked to install. t3 and codex are on the image; claude is not. - for (const [name, text] of Object.entries({ curl: fakeCurl, npm: '#!/bin/sh\necho "$*" >> "$NPM_LOG"\n', t3: "#!/bin/sh\n", codex: "#!/bin/sh\n" })) { + // t3 and codex are on the image; claude is not. + for (const [name, text] of Object.entries({ curl: fakeCurl, npm: fakeNpm, t3: "#!/bin/sh\n", codex: "#!/bin/sh\n" })) { writeFileSync(join(bin, name), text); chmodSync(join(bin, name), 0o755); } @@ -161,7 +182,8 @@ describe("VM setup", () => { expect(log("curl.log")).toHaveLength(1); await prepareVm(box, "1.0.1", {}, "fingerprint"); - expect(installs().slice(2)).toEqual([expect.stringMatching(/ t3@1\.0\.1$/), expect.stringMatching(/ @anthropic-ai\/claude-code$/)]); + // Claude Code went in with the first setup and still runs, so only T3 is installed. + expect(installs().slice(2)).toEqual([expect.stringMatching(/ t3@1\.0\.1$/)]); expect(readFileSync(vmFile("setup-stamp"), "utf8")).toBe(setupStamp("1.0.1")); }); @@ -177,6 +199,24 @@ describe("VM setup", () => { expect(readFileSync(vmFile("setup-stamp"), "utf8")).toBe(setupStamp("1.0.0")); }, 15_000); + test("an agent CLI npm left without its binary is installed again, and setup fails if it still does not run", async () => { + const claudeInstalls = () => log("npm.log").filter((line) => line.endsWith(" @anthropic-ai/claude-code")); + env.BROKEN = "1"; + await prepareVm(box, "1.0.0", {}, "fingerprint"); + expect(claudeInstalls()).toHaveLength(2); + expect(Bun.spawnSync([vmFile("npm/bin/claude"), "--version"]).exitCode).toBe(0); + expect(readFileSync(vmFile("setup-stamp"), "utf8")).toBe(setupStamp("1.0.0")); + + // Broken every time: setup stops before its stamp, so the next connect runs it again. + rmSync(join(dir, "npm.log.broken")); + rmSync(vmFile("npm/bin/claude")); + env.BROKEN = "9"; + await expect(prepareVm(box, "1.0.1", {}, "fingerprint")).rejects.toThrow(); + expect(runs.at(-1)!.stderr).toContain("@anthropic-ai/claude-code installed but does not run, twice."); + expect(claudeInstalls()).toHaveLength(4); + expect(readFileSync(vmFile("setup-stamp"), "utf8")).toBe(setupStamp("1.0.0")); + }); + test("a T3 runtime download cut off partway is tried once more", async () => { // Fails the first time, as the launcher does when the connection drops, then works. writeFileSync(join(dir, "bin", "t3"), `#!/bin/sh\n[ -e "${dir}/tried" ] && exit 0\ntouch "${dir}/tried"; echo "t3: terminated" >&2; exit 1\n`);