Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud computer copies: stream through Boat's transfer links
milind-sonib83154029788
diff --git a/apps/docs/content/docs/computers/cloud-and-vps.mdx b/apps/docs/content/docs/computers/cloud-and-vps.mdxindex cb5cdd395a..e24d84d6b6 100644--- a/apps/docs/content/docs/computers/cloud-and-vps.mdx+++ b/apps/docs/content/docs/computers/cloud-and-vps.mdx@@ -21,10 +21,13 @@ without computer tools can't use the cloud computer: choose another model, or se**Works on** to Auto.A bot can copy files between the Boat and its working folder: `copy_from_computer`-brings back one file of up to 50 MiB (for example a result to load in the Data-tab or use in a page), and `copy_to_computer` sends one file of up to 5 MiB. On-the Boat, files live under `/home/user` or `/tmp`. Both work with your own Boat-key and with the cloud computers included in a Cloud plan.+brings back one file (for example a result to load in the Data tab or use in a+page), and `copy_to_computer` sends one. Each copy moves one file of up to 2 GiB+directly between the Boat and the computer the bot runs on, and may take up to 9+minutes. A download is refused when the working folder's disk can't hold it with+256 MiB to spare, and a half-finished copy never replaces a file on either side.+On the Boat, files live under `/home/user` or `/tmp`. Both work with your own+Boat key and with the cloud computers included in a Cloud plan.On **Auto**, a conversation works on the Boat only after the bot moves it there(it asks to switch with `select_computer`). Auto by itself never reads, wakes ordiff --git a/server/cloud-computer-files.test.ts b/server/cloud-computer-files.test.tsindex d256b16e05..e1c14b6930 100644--- a/server/cloud-computer-files.test.ts+++ b/server/cloud-computer-files.test.ts@@ -1,6 +1,8 @@-// A loopback Boat stands in for the provider and for the Cloud's relay; every folder is a fresh temporary one.-import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";-import { createServer, type Server } from "node:http";+// A loopback Boat stands in for the provider, for the Cloud's relay and for the sandbox that serves transfer links; every+// folder is a fresh temporary one.+import { randomBytes } from "node:crypto";+import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, truncateSync, writeFileSync, writeSync } from "node:fs";+import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";import { tmpdir } from "node:os";import { join } from "node:path";import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";@@ -9,18 +11,32 @@ import type { AppConfig } from "./config.ts";const BOX = "bx_23456789";const OWN = "synthetic-own-key";const INCLUDED = "synthetic-included-key";-const MAX_FROM = 50 * 1024 * 1024;-const MAX_TO = 5 * 1024 * 1024;+const MiB = 1024 * 1024;let server: Server;let base: string;let files: typeof import("./cloud-computer-files.ts");let tools: typeof import("./cloud-computer-tools.ts");let journal: typeof import("./boat-delete-journal.ts");-const calls: Array<{ method: string; path: string; body: any; authorization?: string }> = [];-/** What the computer holds, by path; `declared: false` streams it without a length. */+type Call = { method: string; path: string; body: any; authorization?: string; contentLength?: string };+const calls: Call[] = [];+/** What the computer holds, by path; `declared: false` streams it without a length, `lies` declares another one. */const disk = new Map<string, { bytes: Buffer; declared?: boolean; lies?: number }>();-/** Runs while the fixture answers a download, before any byte is sent. */+/** Every link minted, so a test can check none of them leaks. */+const minted: string[] = [];+/** Overrides the next mint's answer. */+let mintAnswer: ((kind: string) => { status: number; body: unknown }) | undefined;+/** Runs while the sandbox answers a download, before any byte is sent. */let duringDownload: (() => void) | undefined;+/** Runs once the sandbox has sent the first half of a download. */+let midDownload: (() => Promise<void>) | undefined;+/** Runs when the sandbox gets an upload's first bytes. */+let onFirstUploadChunk: (() => void) | undefined;+/** Holds the sandbox's answer to a transfer until released. */+let stall: Promise<void> | undefined;+/** What the sandbox received for each upload, by path. */+const uploads = new Map<string, { bytes: number; chunks: number; tail: Buffer; head: Buffer }>();+/** The sandbox turns every link away, as it does an expired one. */+let expireLinks = false;let dataDir: string;let root: string;let folder: string;@@ -28,32 +44,69 @@ let outside: string;const own: AppConfig = { box: { token: OWN } } as AppConfig;const signal = () => new AbortController().signal;+async function sandbox(req: IncomingMessage, res: ServerResponse, url: URL) {+ const [, , verb, token] = url.pathname.split("/");+ const path = Buffer.from(token ?? "", "base64url").toString("utf8").split("|")[0]!;+ if (expireLinks) {+ // A sandbox's refusal may name the link; the copy must never pass that on.+ res.writeHead(403, { "content-type": "application/json" });+ res.end(JSON.stringify({ ok: false, message: `link ${url.href} expired` }));+ req.resume();+ return;+ }+ await stall;+ if (verb === "get" && req.method === "GET") {+ duringDownload?.();+ const file = disk.get(path);+ if (!file) { res.writeHead(404); res.end(`no file behind ${url.href}`); return; }+ res.writeHead(200, { "content-type": "application/octet-stream", ...(file.declared === false ? {} : { "content-length": String(file.lies ?? file.bytes.length) }) });+ for (let at = 0; at < file.bytes.length; at += MiB) {+ if (at === Math.floor(file.bytes.length / 2 / MiB) * MiB && at > 0) await midDownload?.();+ if (!res.write(file.bytes.subarray(at, at + MiB))) await new Promise(resolve => res.once("drain", resolve));+ }+ res.end();+ return;+ }+ if (verb === "put" && req.method === "PUT") {+ let bytes = 0, chunks = 0, head = Buffer.alloc(0), tail = Buffer.alloc(0);+ for await (const part of req) {+ const chunk = part as Buffer;+ if (chunks++ === 0) onFirstUploadChunk?.();+ if (head.length < 64) head = Buffer.concat([head, chunk]).subarray(0, 64);+ tail = Buffer.concat([tail, chunk]).subarray(-64);+ bytes += chunk.length;+ }+ uploads.set(path, { bytes, chunks, head, tail });+ res.end();+ return;+ }+ res.writeHead(405); res.end();+}+beforeAll(async () => {dataDir = mkdtempSync(join(tmpdir(), "omb-computer-files-data-"));vi.stubEnv("OMB_DATA_DIR", dataDir);server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", base);+ if (url.pathname.startsWith("/sandbox/")) {+ calls.push({ method: req.method ?? "", path: url.pathname.replace(/\/[^/]+$/, "/<token>"), body: null, authorization: req.headers.authorization, contentLength: req.headers["content-length"] });+ await sandbox(req, res, url);+ return;+ }const chunks: Buffer[] = [];for await (const part of req) chunks.push(part as Buffer);- const url = new URL(req.url ?? "/", "http://fixture");const text = Buffer.concat(chunks).toString("utf8");calls.push({ method: req.method ?? "", path: url.pathname, body: text ? JSON.parse(text) : null, authorization: req.headers.authorization });- const action = /\/(?:sandboxes|boxes)\/bx_[a-z0-9]+\/(artifacts|files)$/.exec(url.pathname)?.[1];- if (action === "artifacts" && req.method === "GET") {- duringDownload?.();- const file = disk.get(url.searchParams.get("path") ?? "");- if (!file) { res.writeHead(404, { "content-type": "application/json" }); res.end(JSON.stringify({ ok: false, message: "No such file." })); return; }- res.writeHead(200, { "content-type": "application/octet-stream", ...(file.declared === false ? {} : { "content-length": String(file.lies ?? file.bytes.length) }) });- for (let at = 0; at < file.bytes.length; at += 1 << 20) {- if (!res.write(file.bytes.subarray(at, at + (1 << 20)))) await new Promise(resolve => res.once("drain", resolve));- }- res.end();- return;- }- if (action === "files" && req.method === "PUT") {+ const kind = /\/(?:sandboxes|boxes)\/bx_[a-z0-9]+\/files\/(download-url|upload-url)$/.exec(url.pathname)?.[1];+ if (kind && req.method === "POST") {+ const answer = mintAnswer?.(kind);+ if (answer) { res.writeHead(answer.status, { "content-type": "application/json" }); res.end(JSON.stringify(answer.body)); return; }const body = JSON.parse(text);- const bytes = Buffer.from(body.content, body.encoding);- disk.set(body.path, { bytes });- res.end(JSON.stringify({ ok: true, type: "file.written", path: body.path.startsWith("/") ? body.path : `/home/user/${body.path}`, encoding: body.encoding, size: bytes.length }));+ const path = body.path.startsWith("/") ? body.path : `/home/user/${body.path}`;+ const token = Buffer.from(`${path}|${randomBytes(12).toString("hex")}`).toString("base64url");+ const link = `${base}/sandbox/${kind === "download-url" ? "get" : "put"}/${token}`;+ minted.push(token);+ res.end(JSON.stringify({ ok: true, type: kind === "download-url" ? "file.download_url" : "file.upload_url", url: link, method: kind === "download-url" ? "GET" : "PUT", path, expiresAt: new Date(Date.now() + 300_000).toISOString() }));return;}res.writeHead(404); res.end();@@ -72,7 +125,9 @@ beforeEach(() => {vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", INCLUDED);calls.length = 0;disk.clear();- duringDownload = undefined;+ uploads.clear();+ expireLinks = false;+ mintAnswer = duringDownload = midDownload = onFirstUploadChunk = stall = undefined;root = mkdtempSync(join(tmpdir(), "omb-computer-files-"));folder = join(root, "folder");outside = join(root, "outside");@@ -88,27 +143,49 @@ afterAll(async () => {});const leftovers = (dir = folder) => readdirSync(dir, { recursive: true }).map(String).filter(name => name.endsWith(".part"));+const plenty = { freeBytes: () => 64 * 1024 * MiB };+const from = (path: string, to?: string, options: Parameters<typeof files.copyFromComputer>[5] = plenty, cfg = own) =>+ files.copyFromComputer(cfg, BOX, folder, { path, ...(to === undefined ? {} : { to }) }, signal(), options);+const to = (fromPath: string, path: string, cfg = own) => files.copyToComputer(cfg, BOX, folder, { from: fromPath, path }, signal());+const sandboxCalls = () => calls.filter(call => call.path.startsWith("/sandbox/"));+const boatCalls = () => calls.filter(call => !call.path.startsWith("/sandbox/"));describe("copy_from_computer", () => {- it("brings a file into the working folder, under its own name or the one asked for", async () => {+ it("mints a short-lived link on the own key, then fetches it without that key", async () => {disk.set("/home/user/out/result.json", { bytes: Buffer.from('{"rows":3}') });- await expect(files.copyFromComputer(own, BOX, folder, { path: "/home/user/out/result.json" }, signal())).resolves.toEqual({ path: "result.json", bytes: 10 });+ await expect(from("/home/user/out/result.json")).resolves.toEqual({ path: "result.json", bytes: 10 });expect(readFileSync(join(folder, "result.json"), "utf8")).toBe('{"rows":3}');- expect(calls).toEqual([{ method: "GET", path: `/boat/api/v1/sandboxes/${BOX}/artifacts`, body: null, authorization: `Bearer ${OWN}` }]);-- await expect(files.copyFromComputer(own, BOX, folder, { path: "/home/user/out/result.json", to: "data/2026/rows.json" }, signal()))- .resolves.toEqual({ path: join("data", "2026", "rows.json"), bytes: 10 });+ expect(calls).toEqual([+ { method: "POST", path: `/boat/api/v1/sandboxes/${BOX}/files/download-url`, body: { path: "/home/user/out/result.json", ttlSeconds: 300 }, authorization: `Bearer ${OWN}` },+ { method: "GET", path: "/sandbox/get/<token>", body: null, authorization: undefined, contentLength: undefined },+ ]);+ await expect(from("/home/user/out/result.json", "data/2026/rows.json")).resolves.toEqual({ path: join("data", "2026", "rows.json"), bytes: 10 });expect(readFileSync(join(folder, "data", "2026", "rows.json"), "utf8")).toBe('{"rows":3}');});+ it("writes a big file to disk as it arrives, never holding it whole", async () => {+ const size = 64 * MiB;+ disk.set("/tmp/big.bin", { bytes: Buffer.alloc(size, 7), declared: false });+ let onDisk = 0;+ // Half sent, the sandbox waits for that half to reach the disk before it sends the rest.+ midDownload = async () => {+ for (let tries = 0; tries < 300 && onDisk < size / 4; tries++) {+ await new Promise(resolve => setTimeout(resolve, 10));+ onDisk = leftovers().reduce((most, name) => Math.max(most, statSync(join(folder, name)).size), 0);+ }+ };+ await expect(from("/tmp/big.bin")).resolves.toEqual({ path: "big.bin", bytes: size });+ expect(onDisk).toBeGreaterThanOrEqual(size / 4);+ expect(statSync(join(folder, "big.bin")).size).toBe(size);+ });+it("replaces a file already there, and a link there is replaced rather than followed", async () => {disk.set("/tmp/a.csv", { bytes: Buffer.from("new") });writeFileSync(join(folder, "a.csv"), "old");- writeFileSync(join(outside, "target.csv"), "untouched");symlinkSync(join(outside, "missing.csv"), join(folder, "dangling.csv"));- await files.copyFromComputer(own, BOX, folder, { path: "/tmp/a.csv" }, signal());+ await from("/tmp/a.csv");expect(readFileSync(join(folder, "a.csv"), "utf8")).toBe("new");- await expect(files.copyFromComputer(own, BOX, folder, { path: "/tmp/a.csv", to: "dangling.csv" }, signal())).resolves.toMatchObject({ bytes: 3 });+ await expect(from("/tmp/a.csv", "dangling.csv")).resolves.toMatchObject({ bytes: 3 });expect(existsSync(join(outside, "missing.csv"))).toBe(false);expect(readFileSync(join(folder, "dangling.csv"), "utf8")).toBe("new");expect(leftovers()).toEqual([]);@@ -121,10 +198,9 @@ describe("copy_from_computer", () => {["a Windows absolute path", "C:\\escaped.json", /relative to your working folder/],["the folder itself", ".", /not the folder itself/],["the secret folder", ".openmausbot-secrets/token.txt", /holds a secret/],- ])("refuses %s before asking the Boat", async (_label, to, message) => {+ ])("refuses %s before asking the Boat", async (_label, place, message) => {disk.set("/tmp/x", { bytes: Buffer.from("x") });- const result = await files.copyFromComputer(own, BOX, folder, { path: "/tmp/x", to }, signal());- expect(result).toEqual({ error: expect.stringMatching(message) });+ expect(await from("/tmp/x", place)).toEqual({ error: expect.stringMatching(message) });expect(calls).toEqual([]);expect(existsSync(join(root, "escaped.json"))).toBe(false);});@@ -134,69 +210,121 @@ describe("copy_from_computer", () => {symlinkSync(outside, join(folder, "linked"));writeFileSync(join(outside, "file.txt"), "untouched");symlinkSync(join(outside, "file.txt"), join(folder, "file.txt"));- for (const to of ["linked/escaped.json", "linked/deeper/escaped.json", "file.txt"]) {- expect(await files.copyFromComputer(own, BOX, folder, { path: "/tmp/x", to }, signal())).toEqual({ error: `${to} leads outside your working folder.` });+ for (const place of ["linked/escaped.json", "linked/deeper/escaped.json", "file.txt"]) {+ expect(await from("/tmp/x", place)).toEqual({ error: `${place} leads outside your working folder.` });}expect(readdirSync(outside)).toEqual(["file.txt"]);expect(readFileSync(join(outside, "file.txt"), "utf8")).toBe("untouched");expect(calls).toEqual([]);});- it("refuses a link made while the file was being fetched, a dangling one, and a folder in the file's place", async () => {+ it("refuses a link made while the file was on its way, a dangling one, and a folder in the file's place", async () => {disk.set("/tmp/x", { bytes: Buffer.from("x") });duringDownload = () => symlinkSync(outside, join(folder, "late"));- expect(await files.copyFromComputer(own, BOX, folder, { path: "/tmp/x", to: "late/escaped.json" }, signal()))- .toEqual({ error: "late/escaped.json leads outside your working folder." });+ expect(await from("/tmp/x", "late/escaped.json")).toEqual({ error: "late/escaped.json leads outside your working folder." });duringDownload = undefined;symlinkSync(join(outside, "not-yet"), join(folder, "dangling"));- expect(await files.copyFromComputer(own, BOX, folder, { path: "/tmp/x", to: "dangling/escaped.json" }, signal()))- .toEqual({ error: "dangling/escaped.json cannot be made in your working folder." });+ expect(await from("/tmp/x", "dangling/escaped.json")).toEqual({ error: "dangling/escaped.json cannot be made in your working folder." });mkdirSync(join(folder, "taken"));- expect(await files.copyFromComputer(own, BOX, folder, { path: "/tmp/x", to: "taken" }, signal()))- .toEqual({ error: "taken is a folder in your working folder; name a file instead." });+ expect(await from("/tmp/x", "taken")).toEqual({ error: "taken is a folder in your working folder; name a file instead." });expect(readdirSync(outside)).toEqual([]);expect(leftovers()).toEqual([]);});- it("refuses a file over 50 MiB, whether Boat declares its length or not, and leaves nothing behind", async () => {- disk.set("/tmp/declared.bin", { bytes: Buffer.alloc(16), lies: MAX_FROM + 1 });- disk.set("/tmp/streamed.bin", { bytes: Buffer.alloc(MAX_FROM + 1), declared: false });- for (const path of ["/tmp/declared.bin", "/tmp/streamed.bin"]) {- expect(await files.copyFromComputer(own, BOX, folder, { path }, signal())).toEqual({ error: expect.stringContaining("larger than 50 MiB") });- }+ it("refuses a file that would not fit on the disk, or is over 2 GiB, saying how much is needed and free", async () => {+ disk.set("/tmp/declared.bin", { bytes: Buffer.alloc(2 * MiB) });+ disk.set("/tmp/streamed.bin", { bytes: Buffer.alloc(3 * MiB), declared: false });+ disk.set("/tmp/huge.bin", { bytes: Buffer.alloc(16), lies: 2 * 1024 * MiB + 1 });+ expect(await from("/tmp/declared.bin", undefined, { freeBytes: () => 200 * MiB })).toEqual({+ error: "Not enough space for /tmp/declared.bin: it needs 2.0 MiB with 256.0 MiB kept free, and the working folder's disk has 200.0 MiB free.",+ });+ expect(await from("/tmp/streamed.bin", undefined, { freeBytes: () => 258 * MiB })).toEqual({+ error: expect.stringMatching(/^Not enough space for \/tmp\/streamed\.bin: it needs more than 2\.\d MiB with 256\.0 MiB kept free, and the working folder's disk has 258\.0 MiB free\.$/),+ });+ expect(await from("/tmp/huge.bin")).toEqual({ error: expect.stringMatching(/^\/tmp\/huge\.bin is 2\.0 GiB; a copy moves at most 2 GiB\./) });expect(readdirSync(folder)).toEqual([]);+ await expect(from("/tmp/declared.bin", undefined, { freeBytes: () => 259 * MiB })).resolves.toEqual({ path: "declared.bin", bytes: 2 * MiB });});- it("brings back exactly 50 MiB", async () => {- disk.set("/tmp/edge.bin", { bytes: Buffer.alloc(MAX_FROM, 1), declared: false });- await expect(files.copyFromComputer(own, BOX, folder, { path: "/tmp/edge.bin" }, signal())).resolves.toEqual({ path: "edge.bin", bytes: MAX_FROM });+ it("says what went wrong without ever passing on the link: a missing file, unusable links, an older relay, Boat's refusal", async () => {+ const spies = (["log", "warn", "error", "info"] as const).map(level => vi.spyOn(console, level));+ try {+ const results: unknown[] = [await from("/tmp/missing.txt")];+ expect(results.at(-1)).toEqual({ error: "/tmp/missing.txt is not on the cloud computer." });+ disk.set("/tmp/x", { bytes: Buffer.from("x") });+ const answer = (url: string, method = "GET") => ({ status: 200, body: { ok: true, url, method, path: "/tmp/x", expiresAt: "2026-01-01T00:00:00Z" } });+ for (const unusable of [answer("http://203.0.113.9/files/get?sig=offsite"), answer(`${base}/sandbox/get/x`, "PUT"), answer("not a link"), { status: 200, body: { ok: true } }]) {+ mintAnswer = () => unusable;+ results.push(await from("/tmp/x"));+ expect(results.at(-1)).toEqual({ error: "The cloud computer answered with a transfer link that can't be used. Try the copy again in a minute." });+ }+ mintAnswer = () => ({ status: 403, body: { ok: false, type: "sandbox.error", status: 403, code: "not_available", message: "This cloud computer action is not included.", error: { code: "not_available", message: "This cloud computer action is not included.", status: 403 } } });+ results.push(await from("/tmp/x", undefined, plenty, {} as AppConfig));+ expect(results.at(-1)).toEqual({ error: expect.stringMatching(/^This Cloud's computer service can't hand out file transfer links yet/) });+ mintAnswer = () => ({ status: 400, body: { ok: false, code: "invalid_path", message: "Path must be under /home/user or /tmp." } });+ results.push(await from("/etc/passwd"));+ expect(results.at(-1)).toEqual({ error: "Copying /etc/passwd from the cloud computer failed: Path must be under /home/user or /tmp." });+ expect(sandboxCalls()).toHaveLength(1);+ expect(readdirSync(folder)).toEqual([]);+ const said = JSON.stringify(results) + spies.flatMap(spy => spy.mock.calls.map(args => args.join(" "))).join("\n");+ expect(minted.length).toBeGreaterThan(0);+ for (const token of minted) expect(said).not.toContain(token);+ expect(said).not.toContain("/sandbox/");+ } finally {+ for (const spy of spies) spy.mockRestore();+ }});- it("says what Boat said when the file cannot be read, and writes nothing", async () => {- expect(await files.copyFromComputer(own, BOX, folder, { path: "/tmp/missing.txt" }, signal()))- .toEqual({ error: "Copying /tmp/missing.txt from the cloud computer failed: No such file." });- expect(readdirSync(folder)).toEqual([]);+ it("reports an expired or refused link as such, both ways, with no link in the words", async () => {+ disk.set("/tmp/x", { bytes: Buffer.from("x") });+ writeFileSync(join(folder, "up.txt"), "up");+ expireLinks = true;+ const refused = { error: "The cloud computer refused the transfer link, which may have expired. Try the copy again." };+ const results = [await from("/tmp/x"), await to("up.txt", "/tmp/up.txt")];+ expect(results).toEqual([refused, refused]);+ for (const token of minted) expect(JSON.stringify(results)).not.toContain(token);+ expect(leftovers()).toEqual([]);+ expect(existsSync(join(folder, "x"))).toBe(false);});});describe("copy_to_computer", () => {- it("sends a file from the working folder as base64", async () => {+ it("mints an upload link, then sends the file without the key, with its length", async () => {mkdirSync(join(folder, "in"));writeFileSync(join(folder, "in", "query.sql"), "select 1;\n");- await expect(files.copyToComputer(own, BOX, folder, { from: "in/query.sql", path: "work/query.sql" }, signal()))- .resolves.toEqual({ path: "/home/user/work/query.sql", bytes: 10 });- expect(calls).toEqual([{ method: "PUT", path: `/boat/api/v1/sandboxes/${BOX}/files`, authorization: `Bearer ${OWN}`,- body: { path: "work/query.sql", content: Buffer.from("select 1;\n").toString("base64"), encoding: "base64" } }]);+ await expect(to("in/query.sql", "work/query.sql")).resolves.toEqual({ path: "/home/user/work/query.sql", bytes: 10 });+ expect(calls).toEqual([+ { method: "POST", path: `/boat/api/v1/sandboxes/${BOX}/files/upload-url`, body: { path: "work/query.sql", ttlSeconds: 300 }, authorization: `Bearer ${OWN}` },+ { method: "PUT", path: "/sandbox/put/<token>", body: null, authorization: undefined, contentLength: "10" },+ ]);+ expect(uploads.get("/home/user/work/query.sql")).toMatchObject({ bytes: 10, head: Buffer.from("select 1;\n") });+ writeFileSync(join(folder, "empty.txt"), "");+ await expect(to("empty.txt", "/tmp/empty.txt")).resolves.toEqual({ path: "/tmp/empty.txt", bytes: 0 });});- it("sends exactly 5 MiB and refuses one byte more, saying the limit, before the Boat", async () => {- writeFileSync(join(folder, "edge.bin"), Buffer.alloc(MAX_TO, 2));- writeFileSync(join(folder, "big.bin"), Buffer.alloc(MAX_TO + 1, 2));- await expect(files.copyToComputer(own, BOX, folder, { from: "edge.bin", path: "/tmp/edge.bin" }, signal())).resolves.toMatchObject({ bytes: MAX_TO });- expect(disk.get("/tmp/edge.bin")?.bytes.length).toBe(MAX_TO);- calls.length = 0;- expect(await files.copyToComputer(own, BOX, folder, { from: "big.bin", path: "/tmp/big.bin" }, signal()))- .toEqual({ error: expect.stringMatching(/^big\.bin is 5\.0 MiB; copy_to_computer sends at most 5 MiB/) });+ it("reads a big file from disk as it is sent, never holding it whole", async () => {+ const size = 64 * MiB, file = join(folder, "big.bin");+ closeSync(openSync(file, "w"));+ truncateSync(file, size);+ // Once the sandbox has the first bytes, the file's last bytes change on disk: only a copy still reading the+ // file sends the new ones.+ onFirstUploadChunk = () => {+ const fd = openSync(file, "r+");+ writeSync(fd, Buffer.from("written-after-the-upload-began"), 0, 30, size - 30);+ closeSync(fd);+ };+ await expect(to("big.bin", "/tmp/big.bin")).resolves.toEqual({ path: "/tmp/big.bin", bytes: size });+ const got = uploads.get("/tmp/big.bin")!;+ expect(got.bytes).toBe(size);+ expect(got.chunks).toBeGreaterThan(1);+ expect(got.tail.subarray(-30).toString()).toBe("written-after-the-upload-began");+ });++ it("refuses a file over 2 GiB before the Boat, saying the limit", async () => {+ const file = join(folder, "huge.bin");+ closeSync(openSync(file, "w"));+ truncateSync(file, 2 * 1024 * MiB + 1);+ expect(await to("huge.bin", "/tmp/huge.bin")).toEqual({ error: expect.stringMatching(/^huge\.bin is 2\.0 GiB; a copy moves at most 2 GiB\./) });expect(calls).toEqual([]);});@@ -207,7 +335,7 @@ describe("copy_to_computer", () => {mkdirSync(join(folder, ".openmausbot-secrets"));writeFileSync(join(folder, ".openmausbot-secrets", "token"), "secret");mkdirSync(join(folder, "dir"));- for (const [from, message] of [+ for (const [source, message] of [["../outside/secret.txt", /without "\.\."/],[join(outside, "secret.txt"), /relative to your working folder/],["linked.txt", /leads outside/],@@ -216,30 +344,31 @@ describe("copy_to_computer", () => {["dir", /is not a file/],["missing.txt", /is not in your working folder/],] as const) {- expect(await files.copyToComputer(own, BOX, folder, { from, path: "/tmp/x" }, signal()), from).toEqual({ error: expect.stringMatching(message) });+ expect(await to(source, "/tmp/x"), source).toEqual({ error: expect.stringMatching(message) });}expect(calls).toEqual([]);});});describe("through the Cloud's included Boat", () => {- it("copies both ways over the relay's box paths, with only the included token", async () => {+ it("mints links on the relay's box paths with only the included token, and moves the bytes past it", async () => {disk.set("/home/user/report.csv", { bytes: Buffer.from("a,b\n1,2\n") });writeFileSync(join(folder, "seed.txt"), "seed");- await expect(files.copyFromComputer({}, BOX, folder, { path: "/home/user/report.csv" }, signal())).resolves.toEqual({ path: "report.csv", bytes: 8 });- await expect(files.copyToComputer({}, BOX, folder, { from: "seed.txt", path: "/tmp/seed.txt" }, signal())).resolves.toEqual({ path: "/tmp/seed.txt", bytes: 4 });- expect(calls.map(call => [call.method, call.path, call.authorization])).toEqual([- ["GET", `/relay/api/box/v1/boxes/${BOX}/artifacts`, `Bearer ${INCLUDED}`],- ["PUT", `/relay/api/box/v1/boxes/${BOX}/files`, `Bearer ${INCLUDED}`],+ await expect(from("/home/user/report.csv", undefined, plenty, {} as AppConfig)).resolves.toEqual({ path: "report.csv", bytes: 8 });+ await expect(to("seed.txt", "/tmp/seed.txt", {} as AppConfig)).resolves.toEqual({ path: "/tmp/seed.txt", bytes: 4 });+ expect(boatCalls().map(call => [call.method, call.path, call.authorization])).toEqual([+ ["POST", `/relay/api/box/v1/boxes/${BOX}/files/download-url`, `Bearer ${INCLUDED}`],+ ["POST", `/relay/api/box/v1/boxes/${BOX}/files/upload-url`, `Bearer ${INCLUDED}`],]);+ expect(sandboxCalls().map(call => [call.method, call.authorization])).toEqual([["GET", undefined], ["PUT", undefined]]);});});describe("as cloud computer tools", () => {- const rpc = (name: string, args: unknown, folderOf: () => string | null | undefined = () => folder) => {+ const rpc = (name: string, args: unknown, options: { folderOf?: () => string | null | undefined; budgetMs?: number } = {}) => {let gated = 0;const done = tools.cloudComputerRpc({ method: "tools/call", params: { name, arguments: args } }, {- cfg: own, boxId: () => BOX, folder: folderOf, signal: signal(),+ cfg: own, boxId: () => BOX, folder: options.folderOf ?? (() => folder), signal: signal(), budgetMs: options.budgetMs,gate: async () => { gated++; return { held: false }; }, assertActive: () => {},}) as Promise<{ isError?: boolean; content: Array<{ text: string }> }>;return { done, gated: () => gated };@@ -254,6 +383,27 @@ describe("as cloud computer tools", () => {expect(call.gated()).toBe(1);});+ it("stops a copy that outlasts its budget, says nothing changed, and leaves nothing behind", async () => {+ disk.set("/tmp/slow.bin", { bytes: Buffer.alloc(MiB) });+ writeFileSync(join(folder, "slow.txt"), "slow");+ let release!: () => void;+ stall = new Promise(resolve => { release = resolve; });+ for (const [name, args] of [["copy_from_computer", { path: "/tmp/slow.bin" }], ["copy_to_computer", { from: "slow.txt", path: "/tmp/slow.txt" }]] as const) {+ expect(await rpc(name, args, { budgetMs: 300 }).done).toEqual({ isError: true, content: [{ type: "text", text: tools.CLOUD_COMPUTER_COPY_LATE }] });+ }+ release();+ expect(leftovers()).toEqual([]);+ expect(existsSync(join(folder, "slow.bin"))).toBe(false);+ });++ it("gives copies nine minutes, and every other call two", async () => {+ const { COMPUTER_COPY_BUDGET_MS, COMPUTER_PROXY_TIMEOUT_MS, HARNESS_CALL_BUDGET_MS, HARNESS_PROXY_TIMEOUTS_MS } = await import("./harness-budget.ts");+ expect([COMPUTER_COPY_BUDGET_MS, HARNESS_CALL_BUDGET_MS]).toEqual([540_000, 120_000]);+ expect(["copy_from_computer", "copy_to_computer", "exec", "screenshot"].map(tools.cloudComputerCallBudgetMs)).toEqual([540_000, 540_000, 120_000, 120_000]);+ expect(HARNESS_PROXY_TIMEOUTS_MS.computer).toBe(COMPUTER_PROXY_TIMEOUT_MS);+ expect(COMPUTER_PROXY_TIMEOUT_MS).toBeGreaterThan(COMPUTER_COPY_BUDGET_MS);+ });+it.each([["no path", "copy_from_computer", {}],["an extra field", "copy_from_computer", { path: "/tmp/a", overwrite: false }],@@ -266,7 +416,7 @@ describe("as cloud computer tools", () => {});it("copies nothing when the turn has no working folder", async () => {- expect(await rpc("copy_to_computer", { from: "a.txt", path: "/tmp/a" }, () => undefined).done)+ expect(await rpc("copy_to_computer", { from: "a.txt", path: "/tmp/a" }, { folderOf: () => undefined }).done).toEqual({ isError: true, content: [{ type: "text", text: "This turn has no working folder to copy into or out of." }] });expect(calls).toEqual([]);});diff --git a/server/cloud-computer-files.ts b/server/cloud-computer-files.tsindex 5a95537e4d..14989aa08c 100644--- a/server/cloud-computer-files.ts+++ b/server/cloud-computer-files.ts@@ -1,25 +1,46 @@-// Boat (docs.boat.dev/openapi/boat-v1.yaml): GET /sandboxes/{id}/artifacts streams one file of up to 50 MiB, and-// PUT /sandboxes/{id}/files takes one of up to 5 MiB after decoding, as base64 in JSON; both only under /home/user or /tmp.-// Security: a copy reads or writes only inside the bot's working folder, judged after every existing link is followed,-// and never under its secret folder.+// Boat (docs.boat.dev/openapi/boat-v1.yaml): POST /sandboxes/{id}/files/download-url and /files/upload-url answer a link+// the sandbox serves itself, bound to one path, taking no Authorization header and no size limit; a PUT replaces a file+// only once its upload completes.+// Security: the link is a secret until it expires, so no result, error or log ever carries it. A copy reads or writes+// only inside the bot's working folder, judged after every existing link is followed, and never under its secret folder.import { randomBytes } from "node:crypto";-import { constants, lstatSync, mkdirSync, realpathSync, renameSync, rmSync } from "node:fs";+import { constants, lstatSync, mkdirSync, realpathSync, renameSync, rmSync, statfsSync } from "node:fs";import { open } from "node:fs/promises";import { basename, dirname, isAbsolute, join, posix, relative, win32 } from "node:path";import { assertBoatNotDeleting, boatAccount, boatErrorMessage, boatFetch } from "./boat.ts";import type { AppConfig } from "./config.ts";+import { boatProviderApi } from "./included-services.ts";import { inSecretFolder, SECRET_FILE_REFUSAL } from "./secret-folder.ts";import { isInside, resolveThroughLinks } from "./sentinel/paths.ts";-const COPY_FROM_COMPUTER_MAX_BYTES = 50 * 1024 * 1024;-const COPY_TO_COMPUTER_MAX_BYTES = 5 * 1024 * 1024;+const MiB = 1024 * 1024;+const COPY_MAX_BYTES = 2 * 1024 * MiB;+/** Left free on the folder's disk, so a download never fills it. */+const DISK_RESERVE_BYTES = 256 * MiB;+const LINK_TTL_SECONDS = 300;+const OLD_RELAY = "This Cloud's computer service can't hand out file transfer links yet, so files can't be copied to or from the cloud computer until it updates. Use exec in the meantime.";+const UNUSABLE_LINK = "The cloud computer answered with a transfer link that can't be used. Try the copy again in a minute.";+const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;export type CopyOutcome = { path: string; bytes: number } | { error: string };+export interface CopyOptions {+ /** Bytes free on the disk that holds `dir`. */+ freeBytes?(dir: string): number;+}-const mib = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(1)} MiB`;-const tooBigToBring = (path: string) =>- `${path} is larger than 50 MiB, the most copy_from_computer brings back. Make it smaller on the cloud computer first (filter, compress or split it), then copy the result.`;-const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;+const sized = (bytes: number) => bytes >= 1024 * MiB ? `${(bytes / 1024 / MiB).toFixed(1)} GiB` : `${(bytes / MiB).toFixed(1)} MiB`;+const diskFree = (dir: string) => { const disk = statfsSync(dir); return Number(disk.bavail) * Number(disk.bsize); };+const tooBig = (path: string, bytes: number, atLeast = false) =>+ `${path} is ${atLeast ? "over " : ""}${sized(bytes)}; a copy moves at most 2 GiB. Make it smaller on the cloud computer first (filter, compress or split it), then copy the parts.`;+const noSpace = (path: string, bytes: number, free: number, atLeast = false) =>+ `Not enough space for ${path}: it needs ${atLeast ? "more than " : ""}${sized(bytes)} with ${sized(DISK_RESERVE_BYTES)} kept free, and the working folder's disk has ${sized(free)} free.`;++/** What the sandbox's own answer means; its body is never read, since it could carry the link. */+function linkRefusal(status: number, path: string): string {+ if (status === 404) return `${path} is not on the cloud computer.`;+ if (status === 401 || status === 403 || status === 410) return "The cloud computer refused the transfer link, which may have expired. Try the copy again.";+ return `The cloud computer answered ${status} to the copy. Try again in a minute.`;+}type Placed = { root: string; file: string } | { error: string };@@ -36,11 +57,6 @@ function placeInFolder(folder: string, wanted: string): Placed {return { root, file };}-async function boatProblem(cfg: AppConfig, response: Response, what: string): Promise<string> {- const body: unknown = await response.json().catch(() => null);- return boatErrorMessage(response.status, what, body, boatAccount(cfg)?.included === true);-}-/** Checked again once the download has begun: a link made in the folder meanwhile would lead the file out. */function land(placed: { root: string; file: string }, wanted: string): { parent: string; target: string } | { error: string } {let parent: string;@@ -56,6 +72,34 @@ function land(placed: { root: string; file: string }, wanted: string): { parent:return { parent, target };}+/** HTTPS, or plain HTTP only from a loopback Boat (a test fixture's), never pointed anywhere else. */+function usableLink(cfg: AppConfig, link: unknown): URL | null {+ let url: URL, api: URL;+ try {+ url = new URL(String(link));+ api = new URL(boatAccount(cfg)?.api ?? boatProviderApi());+ } catch {+ return null;+ }+ if (url.username || url.password) return null;+ if (url.protocol === "https:") return url;+ const loopback = api.protocol === "http:" && ["127.0.0.1", "[::1]", "localhost"].includes(api.hostname);+ return loopback && url.protocol === "http:" && url.hostname === api.hostname ? url : null;+}++async function transferLink(cfg: AppConfig, boxId: string, kind: "download-url" | "upload-url", path: string, signal: AbortSignal): Promise<{ url: URL; path: string } | { error: string }> {+ assertBoatNotDeleting(boxId);+ const response = await boatFetch(cfg, `/sandboxes/${boxId}/files/${kind}`, { method: "POST", body: JSON.stringify({ path, ttlSeconds: LINK_TTL_SECONDS }), signal });+ const body = await response.json().catch(() => null) as { ok?: unknown; code?: unknown; error?: { code?: unknown }; url?: unknown; method?: unknown; path?: unknown } | null;+ if (!response.ok || body?.ok === false) {+ if ((body?.error?.code ?? body?.code) === "not_available") return { error: OLD_RELAY };+ return { error: boatErrorMessage(response.status, `Copying ${path} ${kind === "download-url" ? "from" : "to"} the cloud computer`, body, boatAccount(cfg)?.included === true) };+ }+ const url = usableLink(cfg, body?.url);+ if (!url || body?.method !== (kind === "download-url" ? "GET" : "PUT")) return { error: UNUSABLE_LINK };+ return { url, path: typeof body.path === "string" ? body.path : path };+}+/** Streams the file to a temporary name beside its place and renames it there, so a failed copy never leaves half a file. */export async function copyFromComputer(cfg: AppConfig,@@ -63,15 +107,27 @@ export async function copyFromComputer(folder: string,args: { path: string; to?: string },signal: AbortSignal,+ options: CopyOptions = {},): Promise<CopyOutcome> {const wanted = args.to ?? posix.basename(args.path);if (!wanted) return { error: "Name the file to copy, or say where it goes with to." };const placed = placeInFolder(folder, wanted);if ("error" in placed) return placed;- assertBoatNotDeleting(boxId);- const response = await boatFetch(cfg, `/sandboxes/${boxId}/artifacts?path=${encodeURIComponent(args.path)}`, { signal, headers: { accept: "*/*" } });- if (!response.ok) return { error: await boatProblem(cfg, response, `Copying ${args.path} from the cloud computer`) };- const landed = Number(response.headers.get("content-length")) > COPY_FROM_COMPUTER_MAX_BYTES ? { error: tooBigToBring(args.path) } : land(placed, wanted);+ const link = await transferLink(cfg, boxId, "download-url", args.path, signal);+ if ("error" in link) return link;+ let response: Response;+ try {+ response = await fetch(link.url, { signal, redirect: "error" });+ } catch {+ signal.throwIfAborted();+ return { error: "The cloud computer could not be reached to copy the file. Try again in a minute." };+ }+ const free = (options.freeBytes ?? diskFree)(placed.root);+ const declared = Number(response.headers.get("content-length") ?? Number.NaN);+ const landed = !response.ok ? { error: linkRefusal(response.status, args.path) }+ : declared > COPY_MAX_BYTES ? { error: tooBig(args.path, declared) }+ : declared + DISK_RESERVE_BYTES > free ? { error: noSpace(args.path, declared, free) }+ : land(placed, wanted);if ("error" in landed) {await response.body?.cancel().catch(() => {});return landed;@@ -88,9 +144,19 @@ export async function copyFromComputer(const chunk = await reader?.read();if (!chunk || chunk.done) break;bytes += chunk.value.byteLength;- if (bytes > COPY_FROM_COMPUTER_MAX_BYTES) return { error: tooBigToBring(args.path) };- await handle.write(chunk.value);+ if (bytes > COPY_MAX_BYTES) return { error: tooBig(args.path, COPY_MAX_BYTES, true) };+ if (bytes + DISK_RESERVE_BYTES > free) return { error: noSpace(args.path, bytes, free, true) };+ try {+ await handle.write(chunk.value);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOSPC") return { error: noSpace(args.path, bytes, free, true) };+ throw error;+ }}+ } catch (error) {+ signal.throwIfAborted();+ if (!(error instanceof Error) || "code" in error) throw error;+ return { error: "The download from the cloud computer was interrupted; nothing was saved. Try again." };} finally {await reader?.cancel().catch(() => {});}@@ -105,6 +171,7 @@ export async function copyFromComputer(return { path: relative(placed.root, target), bytes };}+/** Streams the file from disk as the upload's body; the computer keeps its old file unless the whole upload lands. */export async function copyToComputer(cfg: AppConfig,boxId: string,@@ -114,32 +181,37 @@ export async function copyToComputer(): Promise<CopyOutcome> {const placed = placeInFolder(folder, args.from);if ("error" in placed) return placed;- let content: Buffer;+ let handle;try {- const handle = await open(placed.file, constants.O_RDONLY | noFollow);- try {- const info = await handle.stat();- if (!info.isFile()) return { error: `${args.from} is not a file.` };- if (info.size > COPY_TO_COMPUTER_MAX_BYTES) {- return { error: `${args.from} is ${mib(info.size)}; copy_to_computer sends at most 5 MiB. Split or compress it first, or have the cloud computer download it itself.` };- }- content = await handle.readFile();- } finally {- await handle.close();- }+ handle = await open(placed.file, constants.O_RDONLY | noFollow);} catch (error) {- if ((error as NodeJS.ErrnoException).code === "ENOENT") return { error: `${args.from} is not in your working folder.` };+ const code = (error as NodeJS.ErrnoException).code;+ if (code === "ENOENT") return { error: `${args.from} is not in your working folder.` };+ if (code === "ELOOP") return { error: `${args.from} leads outside your working folder.` };throw error;}- if (content.length > COPY_TO_COMPUTER_MAX_BYTES) return { error: `${args.from} grew past 5 MiB while it was read; copy_to_computer sends at most 5 MiB.` };- assertBoatNotDeleting(boxId);- signal.throwIfAborted();- const response = await boatFetch(cfg, `/sandboxes/${boxId}/files`, {- method: "PUT",- body: JSON.stringify({ path: args.path, content: content.toString("base64"), encoding: "base64" }),- signal,- });- if (!response.ok) return { error: await boatProblem(cfg, response, `Copying ${args.from} to the cloud computer`) };- const body = await response.json().catch(() => null) as { path?: unknown } | null;- return { path: typeof body?.path === "string" ? body.path : args.path, bytes: content.length };+ try {+ const info = await handle.stat();+ if (!info.isFile()) return { error: `${args.from} is not a file.` };+ if (info.size > COPY_MAX_BYTES) return { error: tooBig(args.from, info.size) };+ const link = await transferLink(cfg, boxId, "upload-url", args.path, signal);+ if ("error" in link) return link;+ // Never more than the length declared, whatever is appended meanwhile; a file that shrinks fails the upload.+ const body = info.size === 0 ? new Uint8Array() : handle.createReadStream({ start: 0, end: info.size - 1, autoClose: false });+ let response: Response;+ try {+ response = await fetch(link.url, {+ method: "PUT", body: body as unknown as RequestInit["body"], signal, redirect: "error", duplex: "half",+ headers: { "content-type": "application/octet-stream", "content-length": String(info.size) },+ } as RequestInit);+ } catch {+ signal.throwIfAborted();+ return { error: `The upload of ${args.from} was interrupted; the cloud computer still has its old file, if any. Try again.` };+ }+ await response.body?.cancel().catch(() => {});+ if (!response.ok) return { error: linkRefusal(response.status, args.path) };+ return { path: link.path, bytes: info.size };+ } finally {+ await handle.close().catch(() => {});+ }}diff --git a/server/cloud-computer-lazy.e2e.test.ts b/server/cloud-computer-lazy.e2e.test.tsindex f3c8b80f2b..800da52783 100644--- a/server/cloud-computer-lazy.e2e.test.ts+++ b/server/cloud-computer-lazy.e2e.test.ts@@ -136,6 +136,15 @@ describe("a cloud computer starts only when the bot uses it", () => {// Every request is counted, a stray own-key one included.const path = url.pathname.replace(/^\/relay\/api\/box\/v1/, "");requests.push({ method: req.method ?? "GET", path });+ // The computer's own transfer links: no key, the file's path in the link.+ const linked = /^\/sandbox\/(get|put)\/([^/]+)$/.exec(url.pathname);+ if (linked) {+ if (req.headers.authorization) return send(400, { ok: false, message: "a transfer link takes no key" });+ const file = Buffer.from(linked[2]!, "base64url").toString("utf8");+ if (linked[1] === "put") { written.set(file, raw); res.writeHead(200); return res.end(); }+ res.writeHead(200, { "content-type": "application/octet-stream", "content-length": String(FRAME.length) });+ return res.end(FRAME);+ }if (req.headers.authorization !== `Bearer ${INCLUDED}` || !url.pathname.startsWith("/relay/api/box/v1")) {return send(401, { ok: false, code: "unauthorized", message: "Unauthorized" });}@@ -168,9 +177,10 @@ describe("a cloud computer starts only when the bot uses it", () => {}if (verb === "desktop" && req.method === "POST") return send(200, { desktopUrl: `https://desktop.invalid/${row.id}` });if (verb === "commands" && req.method === "POST") return send(200, { exitCode: 0, stdout: "captured", stderr: "" });- if (verb === "files" && req.method === "PUT") {- written.set(body.path, Buffer.from(body.content, body.encoding).toString("utf8"));- return send(200, { ok: true, type: "file.written", path: body.path, encoding: body.encoding, size: written.get(body.path)!.length });+ if ((verb === "files/download-url" || verb === "files/upload-url") && req.method === "POST") {+ const get = verb === "files/download-url";+ return send(200, { ok: true, url: `http://${req.headers.host}/sandbox/${get ? "get" : "put"}/${Buffer.from(body.path).toString("base64url")}`,+ method: get ? "GET" : "PUT", path: body.path, expiresAt: new Date(Date.now() + 300_000).toISOString() });}if (verb === "artifacts" && req.method === "GET") {res.writeHead(200, { "content-type": "image/jpeg", "content-length": String(FRAME.length) });@@ -477,8 +487,9 @@ describe("a cloud computer starts only when the bot uses it", () => {expect((await call(sent, "copy_to_computer", { from: "query.sql", path: "/tmp/query.sql" })).body.result.isError).toBeFalsy();expect(written.get("/tmp/query.sql")).toBe("select 1;");expect((await call(sent, "copy_from_computer", { path: "/tmp/x", to: "../escaped" })).body.result.isError).toBe(true);- expect(requests.filter(request => /\/(artifacts|files)$/.test(request.path)).map(request => request.method))- .toEqual(expect.arrayContaining(["GET", "PUT"]));+ expect(requests.filter(request => /files\/(download|upload)-url$|^\/sandbox\//.test(request.path)).map(request => `${request.method} ${request.path.split("/").slice(0, 3).join("/")}`))+ .toEqual([`POST /boxes/${rows.at(-1)!.id}`, "GET /sandbox/get", `POST /boxes/${rows.at(-1)!.id}`, "PUT /sandbox/put"]);+ expect(JSON.stringify([brought.body])).not.toContain("/sandbox/");await finish(bot.id);const { group } = await apiOk("POST", "/api/groups", { name: "Copy room", memberIds: [bot.id] });diff --git a/server/cloud-computer-tools.ts b/server/cloud-computer-tools.tsindex b2bbfd2f2d..f944f04539 100644--- a/server/cloud-computer-tools.ts+++ b/server/cloud-computer-tools.ts@@ -5,7 +5,7 @@ import { isRedditAddress, REDDIT_REFUSAL } from "./browser/egress/reddit.ts";import { copyFromComputer, copyToComputer } from "./cloud-computer-files.ts";import type { AppConfig } from "./config.ts";import { controlRefusal, type ControlState } from "./control-client.ts";-import { HARNESS_CALL_BUDGET_MS } from "./harness-budget.ts";+import { COMPUTER_COPY_BUDGET_MS, HARNESS_CALL_BUDGET_MS } from "./harness-budget.ts";import { compileToolSchema } from "./mcp-schema-validator.ts";const coordinate = { type: "integer", minimum: 0, maximum: 32767 };@@ -22,11 +22,11 @@ export const CLOUD_COMPUTER_TOOLS = [tool("scroll", "Scroll at a point on the cloud desktop.", { x: coordinate, y: coordinate, direction: { type: "string", enum: ["up", "down", "left", "right"] }, amount: { type: "integer", minimum: 1, maximum: 30 } }, ["x", "y", "direction"]),tool("open_url", "Request opening an HTTP or HTTPS URL in the cloud desktop browser; inspect the screen to confirm it loaded.", { url: { type: "string", pattern: "^https?://", maxLength: 2000 } }, ["url"]),tool("exec", "Run a shell command on the assigned cloud computer.", { command: { type: "string", minLength: 1, maxLength: 4000 } }, ["command"]),- tool("copy_from_computer", "Copy one file of at most 50 MiB from the cloud computer into your working folder, for example to load it with data_load or use it in a page. A file already there is replaced.", {+ tool("copy_from_computer", "Copy one file of up to 2 GiB from the cloud computer into your working folder, for example to load it with data_load or use it in a page. A file already there is replaced.", {path: { type: "string", minLength: 1, maxLength: 4096, description: "The file on the cloud computer, under /home/user or /tmp." },to: { type: "string", minLength: 1, maxLength: 1000, description: "Where it goes, relative to your working folder. Default: the file's own name." },}, ["path"]),- tool("copy_to_computer", "Copy one file of at most 5 MiB from your working folder to the cloud computer. A file already there is replaced.", {+ tool("copy_to_computer", "Copy one file of up to 2 GiB from your working folder to the cloud computer. A file already there is replaced.", {from: { type: "string", minLength: 1, maxLength: 1000, description: "The file, relative to your working folder." },path: { type: "string", minLength: 1, maxLength: 4096, description: "Where it goes on the cloud computer, under /home/user or /tmp." },}, ["from", "path"]),@@ -34,6 +34,10 @@ export const CLOUD_COMPUTER_TOOLS = [/** A call the gate let through while no Boat had landed for the turn. */export const CLOUD_COMPUTER_NOT_READY = "The cloud computer is not ready. This call was not performed. Take a fresh screenshot in a moment.";export const CLOUD_COMPUTER_LATE = "The cloud computer did not answer in time. This call may still have run; take a fresh screenshot before repeating it.";+export const CLOUD_COMPUTER_COPY_LATE = "The copy did not finish within 9 minutes and was stopped; nothing was changed. Make the file smaller on the cloud computer first (filter, compress or split it), then copy the parts.";+const COPY_TOOLS = new Set(["copy_from_computer", "copy_to_computer"]);+export const cloudComputerCallBudgetMs = (name: unknown): number =>+ typeof name === "string" && COPY_TOOLS.has(name) ? COMPUTER_COPY_BUDGET_MS : HARNESS_CALL_BUDGET_MS;const quote = (value: string) => "'" + value.replace(/'/g, "'\\''") + "'";const buttons: Record<string, number> = { left: 1, middle: 2, right: 3 };const scrollButtons: Record<string, number> = { up: 4, down: 5, left: 6, right: 7 };@@ -70,12 +74,11 @@ export async function runCloudComputerTool(const problem = cloudComputerCallProblem(name, args);if (problem) return { isError: true, content: [{ type: "text", text: problem }] };signal.throwIfAborted();- if (name === "copy_from_computer" || name === "copy_to_computer") {+ if (COPY_TOOLS.has(name)) {if (!folder) return { isError: true, content: [{ type: "text", text: "This turn has no working folder to copy into or out of." }] };const copied = name === "copy_from_computer"? await copyFromComputer(cfg, boxId, folder, args as { path: string; to?: string }, signal): await copyToComputer(cfg, boxId, folder, args as { from: string; path: string }, signal);- signal.throwIfAborted();return "error" in copied ? { isError: true, content: [{ type: "text", text: copied.error }] } : { content: [{ type: "text", text: JSON.stringify(copied) }] };}if (name === "screenshot") {@@ -121,7 +124,7 @@ export async function cloudComputerRpc(budgetMs?: number;},): Promise<{ tools: typeof CLOUD_COMPUTER_TOOLS } | CloudComputerResult> {- const deadline = Date.now() + (deps.budgetMs ?? HARNESS_CALL_BUDGET_MS);+ const started = Date.now();if (request?.method === "tools/list") {deps.assertActive();return { tools: CLOUD_COMPUTER_TOOLS };@@ -129,6 +132,8 @@ export async function cloudComputerRpc(if (request?.method !== "tools/call") throw Object.assign(new Error("unsupported computer method"), { status: 400 });const params = (request.params && typeof request.params === "object" ? request.params : {}) as { name?: unknown; arguments?: unknown };const args = params.arguments ?? {};+ const copy = typeof params.name === "string" && COPY_TOOLS.has(params.name);+ const deadline = started + (deps.budgetMs ?? cloudComputerCallBudgetMs(params.name));const problem = cloudComputerCallProblem(params.name, args);if (problem) return { isError: true, content: [{ type: "text", text: problem }] };const control = await deps.gate();@@ -142,7 +147,7 @@ export async function cloudComputerRpc(result = await runCloudComputerTool(deps.cfg, boxId, params.name as string, args as Record<string, unknown>, AbortSignal.any([deps.signal, late]), deps.folder?.());} catch (error) {if (!late.aborted || deps.signal.aborted) throw error;- return { isError: true, content: [{ type: "text", text: CLOUD_COMPUTER_LATE }] };+ return { isError: true, content: [{ type: "text", text: copy ? CLOUD_COMPUTER_COPY_LATE : CLOUD_COMPUTER_LATE }] };}deps.assertActive();return result;diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex 11ed7c0bfb..776702f291 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -1812,6 +1812,8 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)const seen = JSON.parse(readFileSync(dump, "utf8"));expect(seen.argv.join(" ")).toContain("mcp_servers.computer.command");+ // Codex would end a cloud computer file copy after its own 60 s default.+ expect(seen.argv).toContain("mcp_servers.computer.tool_timeout_sec=560");expect(seen.argv.join(" ")).toContain("/tmp/container-mcp.js");expect(seen.argv.join(" ")).toContain("OMB_VM_TOKEN");expect(seen.argv.join(" ")).not.toContain("vm-secret");diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 6a37de42bf..584c2fbd9f 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -61,7 +61,7 @@ import { parseProtocolAskQuestions, questionChoices } from "../../shared/ask-queimport { codexQuestionReply, openAsyncQuestion, type CodexAsk } from "./codex-questions.ts";import { codexReleaseUpdate, codexUpdateCommand } from "./codex-update.ts";export { codexUpdateCommand };-import { effectiveApprovalPolicy, effectiveApprovalsReviewer } from "./codex-approval-config.ts"; import { AGENTS_TOOL_TIMEOUT_SECONDS } from "./agents-tool-limit.ts";+import { effectiveApprovalPolicy, effectiveApprovalsReviewer } from "./codex-approval-config.ts"; import { AGENTS_TOOL_TIMEOUT_SECONDS } from "./agents-tool-limit.ts"; import { COMPUTER_PROXY_TIMEOUT_MS } from "../harness-budget.ts";import { canUseMcpServer } from "../../shared/tool-scope.ts";import { assertToolScopeSupported } from "../../shared/tool-scope-support.ts";import { appMountFor, gateServer, mcpStdioServer } from "../mcp-gate-config.ts"; import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";@@ -628,7 +628,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {mountSelected("agents", "agents", turn.integrations.agents, "approve"); if (selectedMcp.has("agents")) appServerArgs.push("-c", `mcp_servers.agents.tool_timeout_sec=${AGENTS_TOOL_TIMEOUT_SECONDS}`);}if (turn.integrations?.localComputer) {- mountSelected("computer", "computer", turn.integrations.localComputer);+ mountSelected("computer", "computer", turn.integrations.localComputer); if (selectedMcp.has("computer")) appServerArgs.push("-c", `mcp_servers.computer.tool_timeout_sec=${COMPUTER_PROXY_TIMEOUT_MS / 1_000 + 10}`);}if (turn.integrations?.browser) {mountSelected("browser", "browser", turn.integrations.browser);diff --git a/server/harness-budget.ts b/server/harness-budget.tsindex e877931643..8225fc2451 100644--- a/server/harness-budget.ts+++ b/server/harness-budget.ts@@ -8,4 +8,11 @@ export const HARNESS_CALL_BUDGET_MS = 120_000;* Written out rather than imported, so the stdio proxy that reads this file loads neither the hold nor zod;* harness-mcp-proxy.test.ts holds it to the sum of the real constants. */export const DEVICE_PROXY_TIMEOUT_MS = 9 * 60_000 + 120_000 + 15_000 + 30_000;-export const HARNESS_PROXY_TIMEOUTS_MS: Partial<Record<"browser" | "computer" | "data" | "highlevel" | "email" | "device", number>> = { device: DEVICE_PROXY_TIMEOUT_MS };+/** A cloud computer file copy streams up to 2 GiB, so it gets longer than other calls, still under the chat engine's+ * 10-minute limit on one tool call. */+export const COMPUTER_COPY_BUDGET_MS = 9 * 60_000;+/** Outwaits the longest cloud computer call; Codex, which ends a tool call itself, waits a little longer still. */+export const COMPUTER_PROXY_TIMEOUT_MS = COMPUTER_COPY_BUDGET_MS + 10_000;+export const HARNESS_PROXY_TIMEOUTS_MS: Partial<Record<"browser" | "computer" | "data" | "highlevel" | "email" | "device", number>> = {+ device: DEVICE_PROXY_TIMEOUT_MS, computer: COMPUTER_PROXY_TIMEOUT_MS,+};diff --git a/server/index.ts b/server/index.tsindex 59b761a761..730d8b6a6d 100644--- a/server/index.ts+++ b/server/index.ts@@ -13182,9 +13182,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const abort = new AbortController();res.once("close", () => { if (!res.writableEnded) abort.abort(); });return json(res, 200, { result: await cloudComputerRpc(body, {- cfg, signal: abort.signal,+ cfg, signal: abort.signal, folder: () => messageFileRootsForThread(internalCapability.botId, internalCapability.threadId)[0],boxId: () => internalCapability.boxId ?? claimedBoatId(internalCapability),- folder: () => messageFileRootsForThread(internalCapability.botId, internalCapability.threadId)[0],gate: () => computerCallGate(internalCapability, abort.signal),assertActive: requireActiveInternalCapability,}) });