Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud computer: copy files to and from the bot's working folder
milind-sonib2b7b29e8fe7
diff --git a/apps/docs/content/docs/computers/cloud-and-vps.mdx b/apps/docs/content/docs/computers/cloud-and-vps.mdxindex e3adac0ed3..cb5cdd395a 100644--- a/apps/docs/content/docs/computers/cloud-and-vps.mdx+++ b/apps/docs/content/docs/computers/cloud-and-vps.mdx@@ -20,6 +20,12 @@ at native resolution; tool approvals and **Take control** still apply. A modelwithout computer tools can't use the cloud computer: choose another model, or set**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.+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 orcreates a Boat, so it adds no cloud computer calls to an ordinary message.diff --git a/server/boat.ts b/server/boat.tsindex de8f0107eb..0f90503f26 100644--- a/server/boat.ts+++ b/server/boat.ts@@ -136,7 +136,7 @@ function snapshotBoatConfig(cfg: AppConfig): AppConfig {}/** An own token goes to Boat; Cloud Pro's included token only to its relay. */-function boatFetch(cfg: AppConfig, path: string, opts: RequestInit = {}) {+export function boatFetch(cfg: AppConfig, path: string, opts: RequestInit = {}) {const account = boatAccount(cfg);return fetch(`${account?.api ?? boatProviderApi()}${relayPath(account, path)}`, {...opts,@@ -722,7 +722,7 @@ function deletionFenceError(): Error & { status: number } {);}-function assertBoatNotDeleting(boxId: string): void {+export function assertBoatNotDeleting(boxId: string): void {if (getBoatDeletion(boxId)) throw deletionFenceError();}diff --git a/server/cloud-computer-files.test.ts b/server/cloud-computer-files.test.tsnew file mode 100644index 0000000000..d256b16e05--- /dev/null+++ b/server/cloud-computer-files.test.ts@@ -0,0 +1,285 @@+// 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";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+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;+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. */+const disk = new Map<string, { bytes: Buffer; declared?: boolean; lies?: number }>();+/** Runs while the fixture answers a download, before any byte is sent. */+let duringDownload: (() => void) | undefined;+let dataDir: string;+let root: string;+let folder: string;+let outside: string;+const own: AppConfig = { box: { token: OWN } } as AppConfig;+const signal = () => new AbortController().signal;++beforeAll(async () => {+ dataDir = mkdtempSync(join(tmpdir(), "omb-computer-files-data-"));+ vi.stubEnv("OMB_DATA_DIR", dataDir);+ server = createServer(async (req, res) => {+ 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 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 }));+ return;+ }+ res.writeHead(404); res.end();+ });+ await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("fixture did not bind");+ base = `http://127.0.0.1:${address.port}`;+ files = await import("./cloud-computer-files.ts");+ tools = await import("./cloud-computer-tools.ts");+ journal = await import("./boat-delete-journal.ts");+});+beforeEach(() => {+ vi.stubEnv("OMB_BOAT_API", `${base}/boat/api/v1`);+ vi.stubEnv("OMB_CLOUD_BOAT_URL", `${base}/relay/api/box/v1`);+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", INCLUDED);+ calls.length = 0;+ disk.clear();+ duringDownload = undefined;+ root = mkdtempSync(join(tmpdir(), "omb-computer-files-"));+ folder = join(root, "folder");+ outside = join(root, "outside");+ mkdirSync(folder);+ mkdirSync(outside);+});+afterEach(() => { rmSync(root, { recursive: true, force: true }); });+afterAll(async () => {+ vi.unstubAllEnvs();+ server.closeAllConnections();+ await new Promise<void>(resolve => server.close(() => resolve()));+ rmSync(dataDir, { recursive: true, force: true });+});++const leftovers = (dir = folder) => readdirSync(dir, { recursive: true }).map(String).filter(name => name.endsWith(".part"));++describe("copy_from_computer", () => {+ it("brings a file into the working folder, under its own name or the one asked for", 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 });+ 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(readFileSync(join(folder, "data", "2026", "rows.json"), "utf8")).toBe('{"rows":3}');+ });++ 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());+ 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 });+ expect(existsSync(join(outside, "missing.csv"))).toBe(false);+ expect(readFileSync(join(folder, "dangling.csv"), "utf8")).toBe("new");+ expect(leftovers()).toEqual([]);+ });++ it.each([+ ["a parent step", "../escaped.json", /without "\.\."/],+ ["a parent step further in", "data/../../escaped.json", /without "\.\."/],+ ["an absolute path", "/etc/escaped.json", /relative to your working folder/],+ ["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) => {+ 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(calls).toEqual([]);+ expect(existsSync(join(root, "escaped.json"))).toBe(false);+ });++ it("refuses a link that leads out of the folder, to a folder or to a file", async () => {+ disk.set("/tmp/x", { bytes: Buffer.from("x") });+ 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.` });+ }+ 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 () => {+ 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." });+ 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." });+ 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(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") });+ }+ expect(readdirSync(folder)).toEqual([]);+ });++ 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 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([]);+ });+});++describe("copy_to_computer", () => {+ it("sends a file from the working folder as base64", 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" } }]);+ });++ 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/) });+ expect(calls).toEqual([]);+ });++ it("reads nothing outside the folder, under its secret folder, or that is not a file", async () => {+ writeFileSync(join(outside, "secret.txt"), "private");+ symlinkSync(join(outside, "secret.txt"), join(folder, "linked.txt"));+ symlinkSync(outside, join(folder, "linked"));+ mkdirSync(join(folder, ".openmausbot-secrets"));+ writeFileSync(join(folder, ".openmausbot-secrets", "token"), "secret");+ mkdirSync(join(folder, "dir"));+ for (const [from, message] of [+ ["../outside/secret.txt", /without "\.\."/],+ [join(outside, "secret.txt"), /relative to your working folder/],+ ["linked.txt", /leads outside/],+ ["linked/secret.txt", /leads outside/],+ [".openmausbot-secrets/token", /holds a secret/],+ ["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(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 () => {+ 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}`],+ ]);+ });+});++describe("as cloud computer tools", () => {+ const rpc = (name: string, args: unknown, folderOf: () => string | null | undefined = () => folder) => {+ let gated = 0;+ const done = tools.cloudComputerRpc({ method: "tools/call", params: { name, arguments: args } }, {+ cfg: own, boxId: () => BOX, folder: folderOf, signal: signal(),+ gate: async () => { gated++; return { held: false }; }, assertActive: () => {},+ }) as Promise<{ isError?: boolean; content: Array<{ text: string }> }>;+ return { done, gated: () => gated };+ };++ it("lists both copies, and runs them after the control gate", async () => {+ const listed = await tools.cloudComputerRpc({ method: "tools/list" }, { cfg: own, boxId: () => BOX, signal: signal(), gate: async () => ({ held: false }), assertActive: () => {} });+ expect(("tools" in listed ? listed.tools : []).map(tool => tool.name).slice(-2)).toEqual(["copy_from_computer", "copy_to_computer"]);+ disk.set("/tmp/a.txt", { bytes: Buffer.from("abc") });+ const call = rpc("copy_from_computer", { path: "/tmp/a.txt" });+ expect(await call.done).toEqual({ content: [{ type: "text", text: JSON.stringify({ path: "a.txt", bytes: 3 }) }] });+ expect(call.gated()).toBe(1);+ });++ it.each([+ ["no path", "copy_from_computer", {}],+ ["an extra field", "copy_from_computer", { path: "/tmp/a", overwrite: false }],+ ["no destination", "copy_to_computer", { from: "a.txt" }],+ ])("refuses %s before the gate", async (_label, name, args) => {+ const call = rpc(name, args);+ expect(await call.done).toMatchObject({ isError: true, content: [{ text: expect.stringContaining("input schema") }] });+ expect(call.gated()).toBe(0);+ expect(calls).toEqual([]);+ });++ 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)+ .toEqual({ isError: true, content: [{ type: "text", text: "This turn has no working folder to copy into or out of." }] });+ expect(calls).toEqual([]);+ });++ it("touches no Boat that is being deleted", async () => {+ journal.prepareBoatDeletion({ boxId: "bx_3456789a", name: "ogb-bot-abc123", ownerBotId: "bot-1" });+ writeFileSync(join(folder, "a.txt"), "a");+ try {+ await expect(files.copyFromComputer(own, "bx_3456789a", folder, { path: "/tmp/a" }, signal())).rejects.toThrow(/being deleted/);+ await expect(files.copyToComputer(own, "bx_3456789a", folder, { from: "a.txt", path: "/tmp/a" }, signal())).rejects.toThrow(/being deleted/);+ expect(calls).toEqual([]);+ } finally {+ journal.retireBoatDeletion("bx_3456789a");+ }+ });+});diff --git a/server/cloud-computer-files.ts b/server/cloud-computer-files.tsnew file mode 100644index 0000000000..5a95537e4d--- /dev/null+++ b/server/cloud-computer-files.ts@@ -0,0 +1,145 @@+// 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.+import { randomBytes } from "node:crypto";+import { constants, lstatSync, mkdirSync, realpathSync, renameSync, rmSync } 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 { 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;++export type CopyOutcome = { path: string; bytes: number } | { error: string };++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;++type Placed = { root: string; file: string } | { error: string };++function placeInFolder(folder: string, wanted: string): Placed {+ if (isAbsolute(wanted) || win32.isAbsolute(wanted) || wanted.split(/[\\/]/).includes("..")) {+ return { error: `${wanted} must be a path relative to your working folder, without "..".` };+ }+ let root: string;+ try { root = realpathSync(folder); } catch { return { error: "Your working folder is not available right now." }; }+ const file = resolveThroughLinks(join(root, wanted));+ if (file === root) return { error: "Name a file inside your working folder, not the folder itself." };+ if (!isInside(file, root)) return { error: `${wanted} leads outside your working folder.` };+ if (inSecretFolder(file)) return { error: SECRET_FILE_REFUSAL };+ 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;+ try {+ mkdirSync(dirname(placed.file), { recursive: true });+ parent = realpathSync(dirname(placed.file));+ } catch {+ return { error: `${wanted} cannot be made in your working folder.` };+ }+ if (!isInside(parent, placed.root)) return { error: `${wanted} leads outside your working folder.` };+ const target = join(parent, basename(placed.file));+ if (lstatSync(target, { throwIfNoEntry: false })?.isDirectory()) return { error: `${wanted} is a folder in your working folder; name a file instead.` };+ return { parent, target };+}++/** 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,+ boxId: string,+ folder: string,+ args: { path: string; to?: string },+ signal: AbortSignal,+): 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);+ if ("error" in landed) {+ await response.body?.cancel().catch(() => {});+ return landed;+ }+ const { parent, target } = landed;+ const temporary = join(parent, `.${basename(target)}.${randomBytes(6).toString("hex")}.part`);+ const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow, 0o644);+ let bytes = 0;+ let written = false;+ try {+ const reader = response.body?.getReader();+ try {+ for (;;) {+ 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);+ }+ } finally {+ await reader?.cancel().catch(() => {});+ }+ await handle.close();+ signal.throwIfAborted();+ renameSync(temporary, target);+ written = true;+ } finally {+ await handle.close().catch(() => {});+ if (!written) rmSync(temporary, { force: true });+ }+ return { path: relative(placed.root, target), bytes };+}++export async function copyToComputer(+ cfg: AppConfig,+ boxId: string,+ folder: string,+ args: { from: string; path: string },+ signal: AbortSignal,+): Promise<CopyOutcome> {+ const placed = placeInFolder(folder, args.from);+ if ("error" in placed) return placed;+ let content: Buffer;+ 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();+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { error: `${args.from} is not in 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 };+}diff --git a/server/cloud-computer-lazy.e2e.test.ts b/server/cloud-computer-lazy.e2e.test.tsindex 30028b9872..f3c8b80f2b 100644--- a/server/cloud-computer-lazy.e2e.test.ts+++ b/server/cloud-computer-lazy.e2e.test.ts@@ -39,6 +39,8 @@ describe("a cloud computer starts only when the bot uses it", () => {* hours are used up. */const refuse = { creates: false };const requests: Request[] = [];+ /** Files the bots wrote on their computers, by path. */+ const written = new Map<string, string>();/** Boat ids in Boat's own alphabet, one per computer created. */const boxId = (n: number) => `bx_${"23456789abcdefgh"[n]}3456789`;@@ -166,6 +168,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 === "artifacts" && req.method === "GET") {res.writeHead(200, { "content-type": "image/jpeg", "content-length": String(FRAME.length) });return res.end(FRAME);@@ -459,4 +465,33 @@ describe("a cloud computer starts only when the bot uses it", () => {refuse.creates = false;}}, 60_000);++ it("copies files between the cloud computer and the folder the turn works in, in a chat and in a room", async () => {+ const bot = await cloudBot("Copier");+ const sent = await startTurn(bot.id, "Bring the results back");+ const call = (turn: any, name: string, args: unknown) => computerCall(turn, "tools/call", { name, arguments: args });+ const brought = await call(sent, "copy_from_computer", { path: "/home/user/out/frame.jpg", to: "results/frame.jpg" });+ expect(brought.body.result, JSON.stringify(brought.body)).toEqual({ content: [{ type: "text", text: JSON.stringify({ path: join("results", "frame.jpg"), bytes: FRAME.length }) }] });+ expect(readFileSync(join(sent.cwd, "results", "frame.jpg"))).toEqual(FRAME);+ writeFileSync(join(sent.cwd, "query.sql"), "select 1;");+ 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"]));+ await finish(bot.id);++ const { group } = await apiOk("POST", "/api/groups", { name: "Copy room", memberIds: [bot.id] });+ await apiOk("PATCH", `/api/groups/${group.id}/setup`, { action: "skip" });+ rmSync(dumpFile, { force: true });+ rmSync(finishFile, { force: true });+ await apiOk("POST", `/api/groups/${group.id}/messages`, { text: "Bring it here too" });+ const roomTurn = await dump();+ expect(roomTurn.cwd).not.toBe(sent.cwd);+ expect((await call(roomTurn, "copy_from_computer", { path: "/tmp/frame.jpg" })).body.result.isError).toBeFalsy();+ expect(readFileSync(join(roomTurn.cwd, "frame.jpg"))).toEqual(FRAME);+ await finish(bot.id);+ await apiOk("DELETE", `/api/groups/${group.id}`);+ await apiOk("DELETE", `/api/bots/${bot.id}`);+ }, 60_000);});diff --git a/server/cloud-computer-tools.test.ts b/server/cloud-computer-tools.test.tsindex 95b45814aa..a3acf39c42 100644--- a/server/cloud-computer-tools.test.ts+++ b/server/cloud-computer-tools.test.ts@@ -47,10 +47,11 @@ const rpc = (request: unknown, gate: { held: boolean; reason?: "person"; blocked};describe("cloud computer tools", () => {- it("lists the same ten tools for every engine", async () => {+ it("lists the same twelve tools for every engine", async () => {const listed = await rpc({ method: "tools/list", params: {} }).done as { tools: Array<{ name: string }> };expect(listed.tools.map(tool => tool.name)).toEqual(["screenshot", "get_screen_size", "click", "move", "drag", "type_text", "key_press", "scroll", "open_url", "exec",+ "copy_from_computer", "copy_to_computer",]);expect(calls).toEqual([]);});diff --git a/server/cloud-computer-tools.ts b/server/cloud-computer-tools.tsindex 4af20414a5..b2bbfd2f2d 100644--- a/server/cloud-computer-tools.ts+++ b/server/cloud-computer-tools.ts@@ -2,6 +2,7 @@import type { ValidateFunction } from "ajv";import { isolatedRemoteCommand, runCommand, screenshotBoat } from "./boat.ts";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";@@ -21,6 +22,14 @@ 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.", {+ 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.", {+ 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"]),];/** 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.";@@ -49,17 +58,26 @@ export type CloudComputerResult = {isError?: boolean;};-/** The caller has already checked the arguments and the person's control. */+/** The caller has already checked the arguments and the person's control. `folder` is the bot's working folder for this turn. */export async function runCloudComputerTool(cfg: AppConfig,boxId: string,name: string,args: Record<string, unknown>,signal: AbortSignal,+ folder?: string | null,): Promise<CloudComputerResult> {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 (!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") {const shot = await screenshotBoat(cfg, "", boxId, { signal, nativeSize: true });signal.throwIfAborted();@@ -94,6 +112,8 @@ export async function cloudComputerRpc(cfg: AppConfig;/** The Boat this call acts on, read after the gate. */boxId(): string | null | undefined;+ /** The bot's working folder, which the copy tools read from and write into. */+ folder?(): string | null | undefined;gate(): Promise<Pick<ControlState, "held" | "reason" | "blockedReason">>;assertActive(): void;signal: AbortSignal;@@ -119,7 +139,7 @@ export async function cloudComputerRpc(const late = AbortSignal.timeout(Math.max(1, deadline - Date.now()));let result: CloudComputerResult;try {- result = await runCloudComputerTool(deps.cfg, boxId, params.name as string, args as Record<string, unknown>, AbortSignal.any([deps.signal, late]));+ 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 }] };diff --git a/server/index.ts b/server/index.tsindex ce657897b8..8a8463aa75 100644--- a/server/index.ts+++ b/server/index.ts@@ -13185,6 +13185,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 200, { result: await cloudComputerRpc(body, {cfg, signal: abort.signal,boxId: () => internalCapability.boxId ?? claimedBoatId(internalCapability),+ folder: () => messageFileRootsForThread(internalCapability.botId, internalCapability.threadId)[0],gate: () => computerCallGate(internalCapability, abort.signal),assertActive: requireActiveInternalCapability,}) });