Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
This computer file tools: no app-side path restrictions; the approval level decides (#6221)
Milind Soni817ae89cfb65
diff --git a/server/drivers/chat-host-computer.test.ts b/server/drivers/chat-host-computer.test.tsindex 95cea613ef..1edfcd5ee5 100644--- a/server/drivers/chat-host-computer.test.ts+++ b/server/drivers/chat-host-computer.test.ts@@ -84,7 +84,7 @@ describe("this desktop's own computer in a chat turn", () => {expect(hostComputerKey(one)).toBe(hostComputerKey(two));expect(hostComputerKey(one)).not.toBe(hostComputerKey({ ...one, env: { ...one.env, OMB_CUA_ARGS: '["mcp","--embedded"]' } }));// A list remembered with the file tools is never offered by a bridge without them, nor the other way round.- expect(hostComputerKey(one)).not.toBe(hostComputerKey({ ...one, env: { ...one.env, OMB_HOST_FILES: '{"appData":[]}' } }));+ expect(hostComputerKey(one)).not.toBe(hostComputerKey({ ...one, env: { ...one.env, OMB_HOST_FILES: "1" } }));});it("is not skipped when slow, and the next turn lists its last tools after a short wait and its first call waits for the start", async () => {diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex c9023695d1..c220ebb614 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -4,7 +4,7 @@ import { createHash, randomBytes } from "node:crypto";import { lstat, mkdir, readdir, unlink, writeFile } from "node:fs/promises";import { join } from "node:path";import type { ValidateFunction } from "ajv";-import { DATA_DIR, stripControlPlaneEnv } from "../config.ts";+import { stripControlPlaneEnv } from "../config.ts";import type { SendTurnInput } from "../contracts.ts";import { cloudRole } from "../bot-box/detect.ts";import { redactSecretsInText } from "../redact.ts";@@ -872,7 +872,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]};}-/** A chat runtime has no file tools of its own, so on this desktop's own computer its bridge answers them (host-files.ts). */+/** A chat runtime has no file tools of its own, so on this desktop's own computer its bridge answers them (host-file-tools.ts). */export function withHostFileTools(integrations: SendTurnInput["integrations"]): SendTurnInput["integrations"] {- return integrations?.localComputer ? { ...integrations, localComputer: withHostFiles(integrations.localComputer, [DATA_DIR]) } : integrations;+ return integrations?.localComputer ? { ...integrations, localComputer: withHostFiles(integrations.localComputer) } : integrations;}diff --git a/server/host-file-tools.ts b/server/host-file-tools.tsindex cd8a2b5fb8..2569ae3d47 100644--- a/server/host-file-tools.ts+++ b/server/host-file-tools.ts@@ -1,10 +1,12 @@+// File tools a chat bot gets on this desktop's own computer. The app adds no rules of its own about which paths: the OS+// account decides what can be opened, and the person's approval level (the bridge's gate) decides what is asked.import { randomUUID } from "node:crypto";import { constants, promises as fs } from "node:fs";import path from "node:path";import type { ToolCall } from "./mcp-bridge.ts";-import { HostFileRefusal, resolveHostPath, writeRefusal, type HostFolders } from "./host-files.ts";+/** Size caps only so one call cannot stall a turn. */export const HOST_FILE_READ_LIMIT = 10 * 1024 * 1024;export const HOST_FILE_WRITE_LIMIT = 25 * 1024 * 1024;const LISTED = 500;@@ -15,17 +17,17 @@ const encoding = { type: "string", enum: ["utf8", "base64"], description: "utf8export const HOST_FILE_TOOLS = [{name: "list_files",- description: "List a folder on this computer. With no path, shows the person's own folders (home, Desktop, Documents, Downloads…) with their real paths, which may be inside OneDrive or iCloud.",+ description: "List a folder on this computer. With no path, lists the person's home folder.",inputSchema: { type: "object", properties: { path: { type: "string", description: "Full path of the folder." } }, additionalProperties: false },},{name: "read_file",- description: "Read a file in the person's folders on this computer, up to 10 MB.",+ description: "Read a file on this computer, up to 10 MB.",inputSchema: { type: "object", properties: { path: { type: "string", description: "Full path of the file." }, encoding }, required: ["path"], additionalProperties: false },},{name: "write_file",- description: "Save a file in the person's folders on this computer, up to 25 MB, making any missing folders. An existing file is replaced only with overwrite: true. Programs, scripts and hidden folders are refused. Answers with the real path saved.",+ description: "Save a file on this computer, up to 25 MB, making any missing folders. An existing file is replaced only with overwrite: true. Answers with the real path saved.",inputSchema: {type: "object",properties: {@@ -40,7 +42,7 @@ export const HOST_FILE_TOOLS = [},{name: "make_folder",- description: "Make a folder, and any missing folders above it, in the person's folders on this computer.",+ description: "Make a folder, and any missing folders above it, on this computer.",inputSchema: { type: "object", properties: { path: { type: "string", description: "Full path of the folder." } }, required: ["path"], additionalProperties: false },},] as const;@@ -51,66 +53,36 @@ type Result = { content: Array<{ type: "text"; text: string }>; isError?: true }const said = (text: string): Result => ({ content: [{ type: "text", text }] });const refused = (text: string): Result => ({ ...said(text), isError: true });+class Mistake extends Error {}+function sizeText(bytes: number): string {if (bytes < 1024) return `${bytes} bytes`;if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;return `${(bytes / 1024 / 1024).toFixed(1)} MB`;}-function failure(error: unknown, at: string): Result {- if (error instanceof HostFileRefusal) return refused(error.message);- const code = (error as NodeJS.ErrnoException | null)?.code;- if (code === "EACCES" || code === "EPERM") return refused(`This computer did not allow access to ${at}.`);- if (code === "EBUSY") return refused(`${at} is open in another app. Ask the person to close it, then try again.`);- if (code === "ENOSPC") return refused("The disk is full.");- if (code === "ENAMETOOLONG") return refused("That path is too long.");- return refused(`Could not do that at ${at}: ${error instanceof Error ? error.message : String(error)}`);+function fullPath(home: string, raw: unknown): string {+ if (typeof raw !== "string" || !raw) throw new Mistake("Give the full path.");+ const text = raw === "~" || /^~[\\/]/.test(raw) ? home + raw.slice(1) : raw;+ if (!path.isAbsolute(text)) throw new Mistake(`Give a full path, like ${path.join(home, "Documents", "notes.txt")}.`);+ return path.resolve(text);}function wanted(value: unknown): "utf8" | "base64" {if (value === undefined || value === "utf8") return "utf8";if (value === "base64") return "base64";- throw new HostFileRefusal('encoding is "utf8" or "base64".');-}--async function sameEntry(target: string, stat: { dev: number; ino: number }): Promise<boolean> {- const named = await fs.lstat(target).catch(() => null);- return Boolean(named && !named.isSymbolicLink() && named.dev === stat.dev && named.ino === stat.ino);+ throw new Mistake('encoding is "utf8" or "base64".');}-/** One folder at a time, each checked as it is made, so a folder swapped for a link meanwhile is refused, not followed. */-async function makeFolders(folders: HostFolders, target: string): Promise<void> {- const { target: real, exists } = await resolveHostPath(folders, target);- if (exists) {- if (!(await fs.lstat(real)).isDirectory()) throw new HostFileRefusal(`${real} is a file, not a folder.`);- return;- }- const p = folders.platform === "win32" ? path.win32 : path.posix;- const parent = p.dirname(real);- if (parent !== real) await makeFolders(folders, parent);- try {- await fs.mkdir(real);- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;- }- const again = await resolveHostPath(folders, real);- if (!again.exists || !(await fs.lstat(again.target)).isDirectory()) throw new HostFileRefusal(`${real} could not be made as a folder.`);-}--async function listFiles(folders: HostFolders, args: Record<string, unknown>): Promise<Result> {- if (args.path === undefined || args.path === "") {- return said(["The person's folders on this computer:", ...folders.places.map((place) => `${place.name}: ${place.path}`)].join("\n"));- }- const { target, exists } = await resolveHostPath(folders, args.path);- if (!exists) return refused(`There is no folder at ${target}.`);+async function listFiles(home: string, args: Record<string, unknown>): Promise<Result> {+ const target = await fs.realpath(args.path === undefined || args.path === "" ? home : fullPath(home, args.path));const entries = await fs.readdir(target, { withFileTypes: true });- const p = folders.platform === "win32" ? path.win32 : path.posix;const lines: string[] = [];for (const entry of entries.slice(0, LISTED)) {if (entry.isSymbolicLink()) lines.push(`link ${entry.name}`);else if (entry.isDirectory()) lines.push(`folder ${entry.name}`);else {- const stat = await fs.lstat(p.join(target, entry.name)).catch(() => null);+ const stat = await fs.lstat(path.join(target, entry.name)).catch(() => null);lines.push(`file ${entry.name}${stat ? ` (${sizeText(stat.size)})` : ""}`);}}@@ -118,76 +90,47 @@ async function listFiles(folders: HostFolders, args: Record<string, unknown>): Preturn said(`${target}\n${lines.join("\n") || "(empty)"}${more}`);}-async function readFile(folders: HostFolders, args: Record<string, unknown>): Promise<Result> {+async function readFile(home: string, args: Record<string, unknown>): Promise<Result> {const as = wanted(args.encoding);- const { target, exists } = await resolveHostPath(folders, args.path);- if (!exists) return refused(`There is no file at ${target}.`);- const file = await fs.open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));- try {- const stat = await file.stat();- if (stat.isDirectory()) return refused(`${target} is a folder: list it with list_files.`);- if (!stat.isFile() || stat.nlink > 1) return refused(`${target} is not an ordinary file.`);- if (stat.size > HOST_FILE_READ_LIMIT) return refused(`${target} is ${sizeText(stat.size)}; files up to 10 MB can be read.`);- if (!(await sameEntry(target, stat)) || (await resolveHostPath(folders, target)).target !== target) return refused(`${target} changed while it was opened. Try again.`);- const data = await file.readFile();- if (data.length > HOST_FILE_READ_LIMIT) return refused(`${target} grew past 10 MB while it was read.`);- const text = as === "base64" ? data.toString("base64") : data.toString("utf8");- if (as === "utf8" && !Buffer.from(text, "utf8").equals(data)) return refused(`${target} is not plain text. Read it with encoding base64.`);- return said(`${target} (${sizeText(data.length)}):\n${text}`);- } finally {- await file.close();- }+ const target = await fs.realpath(fullPath(home, args.path));+ const stat = await fs.stat(target);+ if (stat.isDirectory()) return refused(`${target} is a folder: list it with list_files.`);+ // A pipe or device could block the turn forever.+ if (!stat.isFile()) return refused(`${target} is not an ordinary file.`);+ if (stat.size > HOST_FILE_READ_LIMIT) return refused(`${target} is ${sizeText(stat.size)}; files up to 10 MB can be read.`);+ const data = await fs.readFile(target);+ const text = as === "base64" ? data.toString("base64") : data.toString("utf8");+ if (as === "utf8" && !Buffer.from(text, "utf8").equals(data)) return refused(`${target} is not plain text. Read it with encoding base64.`);+ return said(`${target} (${sizeText(data.length)}):\n${text}`);}-async function writeFile(folders: HostFolders, args: Record<string, unknown>): Promise<Result> {+const alreadyThere = (target: string) => new Mistake(`${target} already exists. To replace it, call write_file again with overwrite: true.`);++async function writeFile(home: string, args: Record<string, unknown>): Promise<Result> {const as = wanted(args.encoding);- if (typeof args.content !== "string") throw new HostFileRefusal("Give the file's content.");- if (args.overwrite !== undefined && typeof args.overwrite !== "boolean") throw new HostFileRefusal("overwrite is true or false.");+ if (typeof args.content !== "string") throw new Mistake("Give the file's content.");+ if (args.overwrite !== undefined && typeof args.overwrite !== "boolean") throw new Mistake("overwrite is true or false.");const data = Buffer.from(args.content, as);- if (data.length > HOST_FILE_WRITE_LIMIT) throw new HostFileRefusal("Files up to 25 MB can be saved.");- const { target, exists } = await resolveHostPath(folders, args.path);- const refusedWrite = writeRefusal(folders, target);- if (refusedWrite) throw new HostFileRefusal(refusedWrite);- const overwrite = args.overwrite === true;- const mode = exists ? await replaceable(folders.platform, target, overwrite) : undefined;- const p = folders.platform === "win32" ? path.win32 : path.posix;- const folder = p.dirname(target);- await makeFolders(folders, folder);+ if (data.length > HOST_FILE_WRITE_LIMIT) throw new Mistake("Files up to 25 MB can be saved.");+ const asked = fullPath(home, args.path);+ await fs.mkdir(path.dirname(asked), { recursive: true });+ const named = path.join(await fs.realpath(path.dirname(asked)), path.basename(asked));+ const existing = await fs.stat(named).catch(() => null);+ if (existing?.isDirectory()) throw new Mistake(`${named} is a folder. Give a file name inside it.`);+ if (existing && args.overwrite !== true) throw alreadyThere(named);+ // A link is followed: the file it points at is the one replaced.+ const target = existing ? await fs.realpath(named) : named;// A temp file beside it, then a rename: a reader sees the whole old file or the whole new one.- const temp = p.join(folder, `.${p.basename(target)}.${randomUUID().slice(0, 8)}.tmp`);- const file = await fs.open(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), mode ?? 0o644);+ const temp = path.join(path.dirname(target), `.${path.basename(target)}.${randomUUID().slice(0, 8)}.tmp`);try {- try {- await file.writeFile(data);- await file.sync();- } finally {- await file.close();- }- const again = await resolveHostPath(folders, target);- if (again.target !== target) throw new HostFileRefusal(`${target} changed while it was saved. Try again.`);- if (!overwrite) await placeNew(temp, target);- else {- if (again.exists) await replaceable(folders.platform, target, true);- await renameWithRetry(temp, target);- }+ await fs.writeFile(temp, data, { flag: "wx", flush: true, ...(existing ? { mode: existing.mode & 0o777 } : {}) });+ if (existing) await renameWithRetry(temp, target);+ else await placeNew(temp, target);} catch (error) {await fs.unlink(temp).catch(() => {});throw error;}- return said(`Saved ${sizeText(data.length)} to ${target}${exists ? " (replaced the file that was there)" : ""}.`);-}--const alreadyThere = (target: string) => new HostFileRefusal(`${target} already exists. To replace it, call write_file again with overwrite: true.`);--/** The mode of a file that may be replaced: an ordinary single-link file that nothing runs. */-async function replaceable(platform: HostFolders["platform"], target: string, overwrite: boolean): Promise<number> {- const stat = await fs.lstat(target);- if (stat.isDirectory()) throw new HostFileRefusal(`${target} is a folder. Give a file name inside it.`);- if (!overwrite) throw alreadyThere(target);- if (!stat.isFile() || stat.nlink > 1) throw new HostFileRefusal(`${target} is not an ordinary file, so it is not replaced.`);- // Windows reports no execute bits; the file types it runs are refused by name.- if (platform !== "win32" && (stat.mode & 0o111) !== 0) throw new HostFileRefusal(`${target} is a program or script (it can be run), so bots cannot replace it.`);- return stat.mode & 0o777;+ return said(`Saved ${sizeText(data.length)} to ${target}${existing ? " (replaced the file that was there)" : ""}.`);}/** A finished temp file put at a path nothing may hold yet: a link fails if anything got there meanwhile, and where a@@ -222,32 +165,22 @@ async function renameWithRetry(from: string, to: string): Promise<void> {}}-async function makeFolder(folders: HostFolders, args: Record<string, unknown>): Promise<Result> {- const { target, exists } = await resolveHostPath(folders, args.path);- const refusedFolder = writeRefusal(folders, target, "folder");- if (refusedFolder) return refused(refusedFolder);- if (exists) {- if (!(await fs.lstat(target)).isDirectory()) return refused(`${target} is a file, not a folder.`);- return said(`${target} is already there.`);- }- await makeFolders(folders, target);- return said(`Made the folder ${target}.`);+async function makeFolder(home: string, args: Record<string, unknown>): Promise<Result> {+ const asked = fullPath(home, args.path);+ const existing = await fs.stat(asked).catch(() => null);+ if (existing && !existing.isDirectory()) return refused(`${asked} is a file, not a folder.`);+ await fs.mkdir(asked, { recursive: true });+ const target = await fs.realpath(asked);+ return said(existing ? `${target} is already there.` : `Made the folder ${target}.`);}const RUN = { list_files: listFiles, read_file: readFile, write_file: writeFile, make_folder: makeFolder } as const;-/** The bridge's relay for these tools: null for any other call. `folders` is asked once, at the first file call. */-export function hostFileRelay(folders: () => Promise<HostFolders>): (call: ToolCall) => Promise<Result> | null {- let found: Promise<HostFolders> | undefined;+/** The bridge's relay for these tools: null for any other call. Failures come back as the OS worded them. */+export function hostFileRelay(home: string): (call: ToolCall) => Promise<Result> | null {return (call) => {if (!HOST_FILE_TOOL_NAMES.has(call.name)) return null;- const at = typeof call.arguments.path === "string" && call.arguments.path ? call.arguments.path : "that path";- found ??= folders().catch((error: unknown) => {- found = undefined;- throw error;- });- return found- .then((ready) => RUN[call.name as keyof typeof RUN](ready, call.arguments))- .catch((error: unknown) => failure(error, at));+ return RUN[call.name as keyof typeof RUN](home, call.arguments)+ .catch((error: unknown) => refused(error instanceof Error ? error.message : String(error)));};}diff --git a/server/host-files.e2e.test.ts b/server/host-files.e2e.test.tsindex 5e5c91d993..2b31a7954e 100644--- a/server/host-files.e2e.test.ts+++ b/server/host-files.e2e.test.ts@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSyncimport { createServer } from "node:http";import type { AddressInfo } from "node:net";import { tmpdir } from "node:os";-import { delimiter, dirname, join } from "node:path";+import { dirname, join } from "node:path";import { createInterface } from "node:readline";import { describe, expect, it } from "vitest";@@ -49,12 +49,12 @@ async function controlServer() {const driver = (env: Record<string, string> = {}) =>({ command: process.execPath, args: ["-e", FAKE_DRIVER], env, platform: process.platform as "darwin" | "linux" | "win32", scope: "local-computer" as const });-async function thisComputer(home: string, appData: string, files: boolean, env: Record<string, string> = {}) {+async function thisComputer(home: string, files: boolean) {const gate = await controlServer();const gated = gatedLocalComputer(driver(), gate.control);- const connection = files ? withHostFiles(gated, [appData]) : gated;+ const connection = files ? withHostFiles(gated) : gated;const child: ChildProcess = spawn(connection.command, connection.args, {- env: { ...process.env, ...connection.env, HOME: home, USERPROFILE: home, OMB_EXTRA_PATH: dirname(process.execPath), ...env },+ env: { ...process.env, ...connection.env, HOME: home, USERPROFILE: home, OMB_EXTRA_PATH: dirname(process.execPath) },stdio: ["pipe", "pipe", "pipe"],});const replies = new Map<number, (value: any) => void>();@@ -89,28 +89,26 @@ async function thisComputer(home: string, appData: string, files: boolean, env:}describe("file tools on this computer, through its bridge", () => {- it("lists them beside the screen tools, saves into the person's folders, and refuses everything else", async () => {+ it("lists them beside the screen tools, asks the approval gate, and saves on any full path", async () => {const root = mkdtempSync(join(tmpdir(), "omb-host-files-e2e-"));const home = join(root, "home");- const appData = join(home, "AppDataElsewhere");- for (const dir of ["OneDrive/Documentos", "Desktop", ".ssh", "AppDataElsewhere"]) mkdirSync(join(home, dir), { recursive: true });+ for (const dir of ["OneDrive/Documentos", "Desktop"]) mkdirSync(join(home, dir), { recursive: true });mkdirSync(join(root, "outside"));symlinkSync(join(root, "outside"), join(home, "Desktop", "elsewhere"), "junction");- const programs = join(home, "bin");- mkdirSync(programs);- const computer = await thisComputer(home, appData, true, { PATH: [programs, process.env.PATH ?? ""].join(delimiter) });+ const computer = await thisComputer(home, true);try {const real = realpathSync(home);const listed = (await computer.rpc("tools/list")).tools;expect(listed.map((tool: { name: string }) => tool.name)).toEqual(["screenshot", ...FILE_TOOLS]);expect(listed.find((tool: { name: string }) => tool.name === "read_file").description).not.toBe("driver's own");- const places = await computer.call("list_files");+ const homeListed = await computer.call("list_files");expect(computer.asked.at(-1)).toContain("files=1");- expect(places.text).toContain(`Home: ${real}`);+ expect(homeListed.text.split("\n")).toEqual(expect.arrayContaining([real, "folder Desktop", "folder OneDrive"]));const target = join(home, "OneDrive", "Documentos", "My Agents", "Vendas", "resumo.md");const saved = await computer.call("write_file", { path: target, content: "# Resumo\nolá" });+ expect(computer.asked.at(-1)).toContain("files=1");const written = join(real, "OneDrive", "Documentos", "My Agents", "Vendas", "resumo.md");expect(saved).toEqual({ text: `Saved 13 bytes to ${written}.`, error: false });expect(readFileSync(written, "utf8")).toBe("# Resumo\nolá");@@ -132,41 +130,18 @@ describe("file tools on this computer, through its bridge", () => {const folder = await computer.call("list_files", { path: join(home, "Desktop") });expect(folder.text.split("\n")).toEqual(expect.arrayContaining([join(real, "Desktop"), "folder Novo", "link elsewhere", "file image.bin (3 bytes)"]));- for (const [args, why] of [- [{ path: join(home, ".ssh", "authorized_keys"), content: "key" }, /settings, keys or app data/],- [{ path: join(appData, "config.json"), content: "{}" }, /settings, keys or app data/],- [{ path: join(home, "Desktop", "elsewhere", "x.txt"), content: "x" }, /link or shortcut/],- [{ path: join(root, "outside", "x.txt"), content: "x" }, /outside the person's own folders/],- [{ path: "notes.txt", content: "x" }, /full path/],- ] as const) {- const refused = await computer.call("write_file", args);- expect(refused.error, args.path).toBe(true);- expect(refused.text, args.path).toMatch(why);- }- expect(readdirSync(join(root, "outside"))).toEqual([]);- expect(readdirSync(join(home, ".ssh"))).toEqual([]);-- // Hidden at any depth, things that run, and what is already there and runnable.- mkdirSync(join(home, "Projects", "site", ".git", "hooks"), { recursive: true });- writeFileSync(join(home, "Projects", "site", ".env"), "SECRET=1");- const read = await computer.call("read_file", { path: join(home, "Projects", "site", ".env") });- expect(read.error).toBe(true);- expect(read.text).not.toContain("SECRET");- const runnable = process.platform === "win32" ? "run.bat" : process.platform === "darwin" ? "go.command" : "launch.desktop";- writeFileSync(join(home, "Desktop", "run.sh"), "#!/bin/sh\necho hi\n", { mode: 0o755 });- for (const [args, why] of [- [{ path: join(home, "Projects", "site", ".git", "hooks", "pre-commit"), content: "x" }, /settings, keys or app data/],- [{ path: join(home, "Desktop", runnable), content: "x" }, /runs as a program/],- [{ path: join(programs, "git"), content: "x" }, /runs as a program/],- ...(process.platform === "win32" ? [] : [[{ path: join(home, "Desktop", "run.sh"), content: "rm -rf ~", overwrite: true }, /can be run/]] as const),+ // No app-side path rules: hidden folders, a link out, outside home and script files all save.+ const realRoot = realpathSync(root);+ for (const [path, at] of [+ [join(home, ".ssh", "config"), join(real, ".ssh", "config")],+ [join(home, "Projects", "site", ".git", "hooks", "pre-commit"), join(real, "Projects", "site", ".git", "hooks", "pre-commit")],+ [join(home, "Desktop", "elsewhere", "x.txt"), join(realRoot, "outside", "x.txt")],+ [join(root, "outside", "run.bat"), join(realRoot, "outside", "run.bat")],] as const) {- const refusedRun = await computer.call("write_file", args);- expect(refusedRun.error, args.path).toBe(true);- expect(refusedRun.text, args.path).toMatch(why);+ expect(await computer.call("write_file", { path, content: "x" }), path).toEqual({ text: `Saved 1 bytes to ${at}.`, error: false });}- expect(readFileSync(join(home, "Desktop", "run.sh"), "utf8")).toBe("#!/bin/sh\necho hi\n");- expect(readdirSync(join(home, "Projects", "site", ".git", "hooks"))).toEqual([]);- expect(readdirSync(programs)).toEqual([]);+ expect(readdirSync(join(root, "outside")).sort()).toEqual(["run.bat", "x.txt"]);+ expect((await computer.call("write_file", { path: "notes.txt", content: "x" })).text).toMatch(/full path/);computer.hold(true);const gated = await computer.call("write_file", { path: join(home, "Desktop", "while-held.txt"), content: "x" });@@ -217,7 +192,7 @@ describe("file tools on this computer, through its bridge", () => {it("lists no file tools on a bridge that was not given them", async () => {const root = mkdtempSync(join(tmpdir(), "omb-host-files-e2e-"));- const computer = await thisComputer(root, join(root, "data"), false);+ const computer = await thisComputer(root, false);try {expect((await computer.rpc("tools/list")).tools.map((tool: { name: string }) => tool.name)).toEqual(["screenshot", "read_file"]);} finally {diff --git a/server/host-files.test.ts b/server/host-files.test.tsindex 6ca7af20ef..dbd8409abe 100644--- a/server/host-files.test.ts+++ b/server/host-files.test.ts@@ -1,178 +1,22 @@-import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import {- OUTSIDE,- hostFilesSetting,- hostFolders,- knownFolders,- placeOf,- refusalFor,- resolveHostPath,- windowsFoldersFrom,- writeRefusal,- type HostFolders,-} from "./host-files.ts";import { listsComputerTool } from "./computer-tool-list.ts";import { withHostFileTools } from "./drivers/chat-mcp-tools.ts";-import { HOST_FILE_TOOLS, placeNew } from "./host-file-tools.ts";+import { HOST_FILE_READ_LIMIT, HOST_FILE_TOOLS, HOST_FILE_WRITE_LIMIT, hostFileRelay, placeNew } from "./host-file-tools.ts";import { withHostFiles } from "./local-computer.ts";-const WINDOWS: HostFolders = {- platform: "win32",- places: [- { name: "Home", path: "C:\\Users\\ana", given: "C:\\Users\\ana" },- { name: "Documents", path: "C:\\Users\\ana\\OneDrive\\Documentos", given: "C:\\Users\\ana\\OneDrive\\Documentos" },- { name: "Desktop", path: "D:\\Mesa", given: "D:\\Mesa" },- ],- denied: ["E:\\OpenMausBotData"],- programs: ["C:\\Users\\ana\\AppData\\Local\\Microsoft\\WindowsApps", "C:\\Users\\ana\\bin"],-};--const MAC: HostFolders = {- platform: "darwin",- places: [{ name: "Home", path: "/Users/ana", given: "/Users/ana" }],- denied: [],- programs: ["/Users/ana/.local/bin", "/Users/ana/tools"],-};--const LINUX: HostFolders = { platform: "linux", places: [{ name: "Home", path: "/home/ana", given: "/home/ana" }], denied: [], programs: [] };--const refusal = (folders: HostFolders, raw: unknown) => {- try {- placeOf(folders, raw);- return null;- } catch (error) {- return (error as Error).message;- }-};--describe("which paths a bot may name on Windows", () => {- it("finds the redirected Documents folder, however the bot spells it", () => {- expect(placeOf(WINDOWS, "C:\\Users\\ana\\OneDrive\\Documentos\\My Agents\\Vendas\\resumo.md"))- .toEqual({ place: WINDOWS.places[1], parts: ["My Agents", "Vendas", "resumo.md"] });- expect(placeOf(WINDOWS, "c:/users/ANA/onedrive/documentos/a.txt")).toMatchObject({ place: { name: "Documents" }, parts: ["a.txt"] });- expect(placeOf(WINDOWS, "D:\\Mesa\\x.txt")).toMatchObject({ place: { name: "Desktop" }, parts: ["x.txt"] });- expect(placeOf(WINDOWS, "~\\notes.txt")).toMatchObject({ place: { name: "Home" }, parts: ["notes.txt"] });- });-- it("refuses network, device and relative paths, other accounts, the system and odd names", () => {- for (const raw of ["\\\\server\\share\\a.txt", "\\\\?\\C:\\Users\\ana\\a.txt", "\\\\.\\PhysicalDrive0", "C:relative.txt", "Documents\\a.txt", "/Users/ana/a.txt"]) {- expect(refusal(WINDOWS, raw), raw).toMatch(/drive letter/);- }- expect(refusal(WINDOWS, "C:\\Users\\ana\\a.txt:hidden")).toMatch(/':'/);- for (const raw of ["C:\\Users\\bob\\Documents\\a.txt", "C:\\Users\\ana\\..\\bob\\a.txt", "C:\\Windows\\System32\\drivers\\etc\\hosts", "C:\\Users", "D:\\Other\\a.txt"]) {- expect(refusal(WINDOWS, raw), raw).toBe(OUTSIDE);- }- for (const raw of ["C:\\Users\\ana\\CON", "C:\\Users\\ana\\nul.txt", "C:\\Users\\ana\\a.txt.", "C:\\Users\\ana\\a<b.txt", "C:\\Users\\ana\\x\u0007y"]) {- expect(refusal(WINDOWS, raw), raw).toMatch(/cannot have/);- }- expect(refusal(WINDOWS, 42)).toMatch(/full path/);- expect(refusal(WINDOWS, "")).toMatch(/full path/);- });-- it("keeps settings, keys, app data and PowerShell profiles closed inside allowed folders", () => {- for (const target of ["C:\\Users\\ana\\AppData\\Roaming\\Microsoft\\Credentials\\x", "C:\\Users\\ana\\appdata\\Local\\Google\\Chrome\\User Data",- "C:\\Users\\ana\\.ssh\\id_ed25519", "C:\\Users\\ana\\.openmausbot\\config.json", "C:\\Users\\ana\\OneDrive\\Documentos\\WindowsPowerShell\\profile.ps1"]) {- expect(refusalFor(WINDOWS, target), target).toMatch(/settings, keys or app data/);- }- expect(refusalFor(WINDOWS, "C:\\Users\\ana\\OneDrive\\Documentos\\My Agents\\a.md")).toBeNull();- expect(refusalFor(WINDOWS, "C:\\Users\\ana\\Downloads\\a.zip")).toBeNull();- expect(refusalFor(WINDOWS, "E:\\OpenMausBotData\\x")).toBe(OUTSIDE);- });-- it("reads Windows' own answer for its folders, OneDrive's move included, and only drive paths", () => {- const answer = "\uFEFF" + JSON.stringify({- Desktop: "C:\\Users\\ana\\OneDrive\\Área de Trabalho", MyDocuments: "C:\\Users\\ana\\OneDrive\\Documentos",- Downloads: "C:\\Users\\ana\\Downloads", MyPictures: "\\\\server\\pics", MyMusic: "", Other: "C:\\x",- });- expect(windowsFoldersFrom(answer)).toEqual([- { name: "Desktop", path: "C:\\Users\\ana\\OneDrive\\Área de Trabalho" },- { name: "Documents", path: "C:\\Users\\ana\\OneDrive\\Documentos" },- { name: "Downloads", path: "C:\\Users\\ana\\Downloads" },- ]);- expect(windowsFoldersFrom("not json")).toEqual([]);- });-- it("asks PowerShell by its full path with a time limit, and falls back to the usual folders when it fails", async () => {- const calls: Array<{ file: string; args: string[]; timeoutMs: number }> = [];- const env = { SystemRoot: "C:\\WINDOWS", OneDrive: "C:\\Users\\ana\\OneDrive", OneDriveCommercial: "relative" };- const asked = await knownFolders("win32", "C:\\Users\\ana", env, async (file, args, timeoutMs) => {- calls.push({ file, args, timeoutMs });- return JSON.stringify({ MyDocuments: "C:\\Users\\ana\\OneDrive\\Documentos" });- });- expect(calls).toHaveLength(1);- expect(calls[0]!.file).toBe("C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");- expect(calls[0]!.args).toContain("-EncodedCommand");- expect(calls[0]!.timeoutMs).toBeGreaterThan(0);- expect(Buffer.from(calls[0]!.args.at(-1)!, "base64").toString("utf16le")).toContain("GetFolderPath");- expect(asked[0]).toEqual({ name: "Documents", path: "C:\\Users\\ana\\OneDrive\\Documentos" });- expect(asked).toContainEqual({ name: "OneDrive", path: "C:\\Users\\ana\\OneDrive" });- const fallback = await knownFolders("win32", "C:\\Users\\ana", { SystemRoot: "..\\evil" }, async (file) => {- expect(file).toBe("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");- throw new Error("timed out");- });- expect(fallback.map((entry) => entry.path)).toEqual(["C:\\Users\\ana\\Desktop", "C:\\Users\\ana\\Documents", "C:\\Users\\ana\\Downloads"]);- });-});--describe("what stays closed at any depth, and what is never saved", () => {- it("refuses hidden folders and files anywhere, PowerShell's folders anywhere, and ~/snap on Linux, for reads and writes", () => {- for (const target of ["/Users/ana/Projects/site/.git/hooks/pre-commit", "/Users/ana/Projects/site/.git/config", "/Users/ana/Documents/app/.env",- "/Users/ana/Projects/x/.vscode/settings.json", "/Users/ana/Projects/x/.husky/pre-push", "/Users/ana/Projects/x/.github/workflows/ci.yml",- "/Users/ana/Projects/x/node_modules/.bin/vite", "/Users/ana/Documents/PowerShell/profile.ps1", "/Users/ana/Projects/x/windowspowershell/a.txt"]) {- expect(refusalFor(MAC, target), target).toMatch(/settings, keys or app data/);- }- for (const target of ["C:\\Users\\ana\\Projetos\\WindowsPowerShell\\x.txt", "D:\\Mesa\\PowerShell\\Modules\\a.psm1", "C:\\Users\\ana\\OneDrive\\Documentos\\windowspowershell\\Microsoft.PowerShell_profile.ps1"]) {- expect(refusalFor(WINDOWS, target), target).toMatch(/settings, keys or app data/);- }- expect(refusalFor(LINUX, "/home/ana/snap/firefox/common/.mozilla/x")).toMatch(/settings, keys or app data/);- expect(refusalFor(LINUX, "/home/ana/Documents/snap/notes.txt")).toBeNull();- expect(refusalFor(MAC, "/Users/ana/snap/notes.txt")).toBeNull();- expect(refusalFor(MAC, "/Users/ana/Projects/site/index.html")).toBeNull();- });-- it("never saves a file type the system runs, nor anything in an app bundle or a folder on PATH", () => {- for (const name of ["run.bat", "RUN.CMD", "a.vbs", "a.vbe", "a.js", "a.jse", "a.wsf", "a.wsh", "a.hta", "setup.exe", "a.scr", "a.com", "a.pif", "a.msi",- "a.dll", "a.Ps1", "a.psm1", "Atalho.lnk", "a.url", "a.scf", "a.library-ms", "a.searchConnector-ms", "desktop.ini", "Desktop.INI"]) {- expect(writeRefusal(WINDOWS, `C:\\Users\\ana\\OneDrive\\Documentos\\${name}`), name).toMatch(/runs as a program/);- }- for (const name of ["notes.txt", "resumo.md", "contrato.docx", "a.pdf", "dados.csv", "foto.png", "planilha.xlsx"]) {- expect(writeRefusal(WINDOWS, `C:\\Users\\ana\\OneDrive\\Documentos\\${name}`), name).toBeNull();- expect(writeRefusal(MAC, `/Users/ana/Documents/${name}`), name).toBeNull();- expect(writeRefusal(LINUX, `/home/ana/Documents/${name}`), name).toBeNull();- }- for (const name of ["go.command", "a.terminal", "x.tool", "Do It.workflow", "Thing.app"]) {- expect(writeRefusal(MAC, `/Users/ana/Desktop/${name}`), name).toMatch(/runs as a program/);- }- expect(writeRefusal(MAC, "/Users/ana/Applications/Thing.app/Contents/MacOS/Thing")).toMatch(/runs as a program/);- expect(writeRefusal(MAC, "/Users/ana/Applications/Thing.APP/Contents/Info.plist")).toMatch(/runs as a program/);- expect(writeRefusal(MAC, "/Users/ana/Projects/Thing.app", "folder")).toMatch(/runs as a program/);- expect(writeRefusal(MAC, "/Users/ana/Projects/new", "folder")).toBeNull();- expect(writeRefusal(LINUX, "/home/ana/Desktop/launch.desktop")).toMatch(/runs as a program/);- expect(writeRefusal(LINUX, "/home/ana/Desktop/run.bat")).toBeNull();- expect(writeRefusal(MAC, "/Users/ana/tools/ls")).toMatch(/runs as a program/);- expect(writeRefusal(MAC, "/Users/ana/tools/sub/notes.txt")).toBeNull();- expect(writeRefusal(WINDOWS, "c:\\users\\ana\\BIN\\git.txt")).toMatch(/runs as a program/);- });-});-describe("the bridge's switch", () => {- it("turns on only for this desktop's own gated computer, carrying the app's data folder", () => {+ it("turns on only for this desktop's own gated computer", () => {const gated = { command: "node", args: [], env: { OMB_CUA_COMMAND: "cua-driver" } as Record<string, string>, platform: "win32" as const, scope: "local-computer" as const };- const on = withHostFiles(gated, ["C:\\Users\\ana\\.openmausbot"]);- expect(hostFilesSetting(on.env.OMB_HOST_FILES, "win32")).toEqual({ platform: "win32", appData: ["C:\\Users\\ana\\.openmausbot"] });+ expect(withHostFiles(gated).env.OMB_HOST_FILES).toBe("1");const vm = { command: "node", args: [], env: {}, platform: "linux" as const };- expect(withHostFiles(vm, [])).toBe(vm);- expect(withHostFiles({ ...gated, env: {} }, []).env).toEqual({});- expect(hostFilesSetting(undefined, "darwin")).toBeNull();- expect(hostFilesSetting('{"appData":["/x"]}', "freebsd")).toBeNull();- expect(hostFilesSetting('{"appData":[1]}', "darwin")).toBeNull();- expect(hostFilesSetting("{", "darwin")).toBeNull();+ expect(withHostFiles(vm)).toBe(vm);+ expect(withHostFiles({ ...gated, env: {} }).env).toEqual({});const turn = withHostFileTools({ localComputer: gated, agents: { command: "agents", args: [], env: {} } });- expect(hostFilesSetting(turn?.localComputer?.env.OMB_HOST_FILES, "win32")?.appData).toHaveLength(1);+ expect(turn?.localComputer?.env.OMB_HOST_FILES).toBe("1");expect(turn?.agents).toEqual({ command: "agents", args: [], env: {} });const none = { agents: { command: "agents", args: [], env: {} } };expect(withHostFileTools(none)).toBe(none);@@ -183,62 +27,97 @@ describe("the bridge's switch", () => {});});-describe("paths on disk", () => {+describe("file tools on disk", () => {const made: string[] = [];afterEach(() => {for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true });});- const posix = process.platform === "win32" ? null : (process.platform as "darwin" | "linux");const fixture = () => {- const root = mkdtempSync(join(tmpdir(), "omb-host-files-"));+ const root = realpathSync(mkdtempSync(join(tmpdir(), "omb-host-files-")));made.push(root);const home = join(root, "home");- const outside = join(root, "outside");- for (const dir of ["Documents", "Desktop", ".ssh", "Library/Keychains", "Library/Mobile Documents/com~apple~CloudDocs", ".openmausbot"]) mkdirSync(join(home, dir), { recursive: true });- mkdirSync(outside);- writeFileSync(join(outside, "secret.txt"), "outside");- writeFileSync(join(home, ".ssh", "id_ed25519"), "key");- return { root, home, outside };+ mkdirSync(join(home, "Documents"), { recursive: true });+ mkdirSync(join(root, "outside"));+ const relay = hostFileRelay(home);+ const call = async (name: string, args: Record<string, unknown> = {}) => {+ const result = await relay({ name, arguments: args })!;+ return { text: result.content.map((part) => part.text).join("\n"), error: result.isError === true };+ };+ return { root, home, call };};- const reason = (promise: Promise<unknown>) => promise.then(() => null, (error: Error) => error.message);- it.skipIf(!posix)("finds the person's folders, with an XDG redirect, and leaves out folders outside home", async () => {- const { home, outside } = fixture();- mkdirSync(join(home, "Dokumente"));- mkdirSync(join(home, ".config"), { recursive: true });- writeFileSync(join(home, ".config", "user-dirs.dirs"), `XDG_DOCUMENTS_DIR="$HOME/Dokumente"\nXDG_DESKTOP_DIR="${outside}"\nXDG_DOWNLOAD_DIR="$HOME/$(rm -rf x)"\n`);- const folders = await hostFolders({ platform: "linux", home, env: {}, appData: [join(home, ".openmausbot")] });- const real = realpathSync(home);- expect(folders.places.map((place) => [place.name, place.path])).toEqual([- ["Home", real], ["Documents", join(real, "Dokumente")], ["Desktop", join(real, "Desktop")],- ]);- expect(folders.denied).toContain(join(real, ".openmausbot"));+ it("answers only its own four tools", () => {+ expect(hostFileRelay("/")({ name: "screenshot", arguments: {} })).toBeNull();});- it.skipIf(!posix)("resolves real paths, refuses links out (or anywhere) and closed folders", async () => {- const { home, outside, root } = fixture();- symlinkSync(outside, join(home, "Documents", "escape"));- symlinkSync(join(home, "Desktop"), join(home, "Documents", "inside-link"));- symlinkSync(join(home, ".ssh", "id_ed25519"), join(home, "Documents", "key.txt"));- symlinkSync(join(home, "Documents"), join(root, "home-link"));- const folders = await hostFolders({ platform: posix!, home, env: {}, appData: [join(home, ".openmausbot")] });- const real = realpathSync(home);+ it("reads and saves on any full path: hidden folders, outside home, scripts and programs included", async () => {+ const { root, home, call } = fixture();+ const posix = process.platform !== "win32";+ for (const target of [join(home, "Projects", "site", ".git", "hooks", "pre-commit"), join(home, ".ssh", "config"), join(root, "outside", "run.bat"),+ join(home, "Library", "x.txt"), join(home, "AppData", "Roaming", "x.ps1"), join(home, "Documents", "WindowsPowerShell", "profile.ps1"),+ join(home, "Applications", "Thing.app", "Contents", "Info.plist"), join(home, "Desktop", "launch.desktop"), join(home, "snap", "x", "a.txt")]) {+ expect(await call("write_file", { path: target, content: "x" }), target).toEqual({ text: `Saved 1 bytes to ${target}.`, error: false });+ expect(await call("read_file", { path: target })).toEqual({ text: `${target} (1 bytes):\nx`, error: false });+ }+ if (posix) {+ writeFileSync(join(home, "run.sh"), "#!/bin/sh\necho hi\n", { mode: 0o755 });+ expect((await call("write_file", { path: join(home, "run.sh"), content: "#!/bin/sh\necho new\n", overwrite: true })).error).toBe(false);+ expect(readFileSync(join(home, "run.sh"), "utf8")).toBe("#!/bin/sh\necho new\n");+ expect(statSync(join(home, "run.sh")).mode & 0o777).toBe(0o755);+ }+ expect(await call("make_folder", { path: join(home, ".config", "tool") })).toEqual({ text: `Made the folder ${join(home, ".config", "tool")}.`, error: false });+ expect(await call("make_folder", { path: join(home, ".config", "tool") })).toEqual({ text: `${join(home, ".config", "tool")} is already there.`, error: false });+ expect((await call("write_file", { path: "~/Documents/a.md", content: "a" })).text).toBe(`Saved 1 bytes to ${join(home, "Documents", "a.md")}.`);+ });- expect(await resolveHostPath(folders, join(home, "Documents", "My Agents", "x", "a.md")))- .toEqual({ target: join(real, "Documents", "My Agents", "x", "a.md"), exists: false });- expect(await resolveHostPath(folders, "~/Documents")).toEqual({ target: join(real, "Documents"), exists: true });- expect(await resolveHostPath(folders, join(real, "Desktop"))).toEqual({ target: join(real, "Desktop"), exists: true });+ it.skipIf(process.platform === "win32")("follows links and reports the real path", async () => {+ const { root, home, call } = fixture();+ writeFileSync(join(root, "outside", "secret.txt"), "outside");+ symlinkSync(join(root, "outside"), join(home, "Documents", "elsewhere"));+ symlinkSync(join(root, "outside", "secret.txt"), join(home, "Documents", "key.txt"));+ const real = join(root, "outside", "secret.txt");+ expect(await call("read_file", { path: join(home, "Documents", "key.txt") })).toEqual({ text: `${real} (7 bytes):\noutside`, error: false });+ expect(await call("read_file", { path: join(home, "Documents", "elsewhere", "secret.txt") })).toEqual({ text: `${real} (7 bytes):\noutside`, error: false });+ expect((await call("write_file", { path: join(home, "Documents", "key.txt"), content: "new" })).text).toMatch(/already exists.*overwrite: true/);+ expect(await call("write_file", { path: join(home, "Documents", "key.txt"), content: "new", overwrite: true }))+ .toEqual({ text: `Saved 3 bytes to ${real} (replaced the file that was there).`, error: false });+ expect(readFileSync(real, "utf8")).toBe("new");+ expect(await call("write_file", { path: join(home, "Documents", "elsewhere", "b.txt"), content: "b" }))+ .toEqual({ text: `Saved 1 bytes to ${join(root, "outside", "b.txt")}.`, error: false });+ expect((await call("list_files", { path: join(home, "Documents") })).text.split("\n")).toEqual(expect.arrayContaining(["link elsewhere", "link key.txt"]));+ });- for (const raw of [join(home, "Documents", "escape", "secret.txt"), join(home, "Documents", "inside-link", "a.txt"), join(home, "Documents", "key.txt")]) {- expect(await reason(resolveHostPath(folders, raw)), raw).toMatch(/link or shortcut/);- }- expect(await reason(resolveHostPath(folders, join(root, "home-link", "a.txt")))).toBe(OUTSIDE);- expect(await reason(resolveHostPath(folders, join(outside, "secret.txt")))).toBe(OUTSIDE);- expect(await reason(resolveHostPath(folders, join(home, "Documents", "..", "..", "outside", "secret.txt")))).toBe(OUTSIDE);- for (const raw of [join(home, ".ssh", "id_ed25519"), join(home, ".openmausbot", "config.json"), join(home, "Library", "Keychains", "login.keychain-db")]) {- expect(await reason(resolveHostPath(folders, raw)), raw).toMatch(/settings, keys or app data/);+ it("keeps the overwrite flag, the size caps and full paths, and passes the OS's own errors on", async () => {+ const { home, call } = fixture();+ const target = join(home, "Documents", "a.txt");+ expect((await call("write_file", { path: target, content: "one" })).error).toBe(false);+ const again = await call("write_file", { path: target, content: "two" });+ expect(again).toEqual({ text: `${target} already exists. To replace it, call write_file again with overwrite: true.`, error: true });+ expect(readFileSync(target, "utf8")).toBe("one");+ expect((await call("write_file", { path: target, content: "two", overwrite: true })).error).toBe(false);+ expect(readFileSync(target, "utf8")).toBe("two");+ expect(readdirSync(join(home, "Documents"))).toEqual(["a.txt"]);++ writeFileSync(join(home, "big.bin"), Buffer.alloc(HOST_FILE_READ_LIMIT + 1));+ expect((await call("read_file", { path: join(home, "big.bin") })).text).toMatch(/files up to 10 MB can be read/);+ expect(await call("write_file", { path: join(home, "huge.txt"), content: "x".repeat(HOST_FILE_WRITE_LIMIT + 1) })).toEqual({ text: "Files up to 25 MB can be saved.", error: true });+ expect(existsSync(join(home, "huge.txt"))).toBe(false);++ expect((await call("write_file", { path: "notes.txt", content: "x" })).text).toMatch(/full path/);+ expect((await call("read_file", { path: join(home, "missing.txt") })).text).toMatch(/ENOENT: no such file or directory/);+ expect((await call("write_file", { path: join(home, "Documents"), content: "x", overwrite: true })).text).toMatch(/is a folder/);+ expect((await call("make_folder", { path: target })).text).toBe(`${target} is a file, not a folder.`);+ if (process.platform !== "win32" && process.getuid?.() !== 0) {+ mkdirSync(join(home, "locked"));+ chmodSync(join(home, "locked"), 0o500);+ expect((await call("write_file", { path: join(home, "locked", "a.txt"), content: "x" })).text).toMatch(/EACCES: permission denied/);+ chmodSync(join(home, "locked"), 0o700);}- expect(await reason(resolveHostPath(folders, "Documents/a.txt"))).toMatch(/starts with \//);+ });++ it("lists the home folder when given no path", async () => {+ const { home, call } = fixture();+ expect(await call("list_files")).toEqual({ text: `${home}\nfolder Documents`, error: false });});it("puts a new file in place only while nothing is there, with or without links, and never overwrites what appeared", async () => {@@ -250,6 +129,7 @@ describe("paths on disk", () => {expect(readFileSync(target, "utf8")).toBe("new");expect(existsSync(temp)).toBe(false);+ const reason = (promise: Promise<unknown>) => promise.then(() => null, (error: Error) => error.message);writeFileSync(temp, "late");expect(await reason(placeNew(temp, target))).toMatch(/already exists.*overwrite: true/);expect(readFileSync(target, "utf8")).toBe("new");@@ -264,23 +144,4 @@ describe("paths on disk", () => {expect(readFileSync(join(home, "Documents", "b.txt"), "utf8")).toBe("copied");expect(existsSync(temp)).toBe(false);});-- it.skipIf(!posix)("knows the folders on PATH by their real paths", async () => {- const { home, root } = fixture();- mkdirSync(join(home, "bin"));- symlinkSync(join(home, "bin"), join(root, "bin-link"));- const folders = await hostFolders({ platform: posix!, home, env: { PATH: `${join(root, "bin-link")}:relative/bin:` }, appData: [] });- expect(folders.programs).toEqual([join(root, "bin-link"), join(realpathSync(home), "bin")]);- expect(writeRefusal(folders, join(realpathSync(home), "bin", "tool"))).toMatch(/runs as a program/);- });-- it.skipIf(process.platform !== "darwin")("opens iCloud Drive inside Library on macOS, and nothing else there", async () => {- const { home } = fixture();- const folders = await hostFolders({ platform: "darwin", home, env: {}, appData: [] });- const real = realpathSync(home);- expect(folders.places.find((place) => place.name === "iCloud Drive")?.path).toBe(join(real, "Library", "Mobile Documents", "com~apple~CloudDocs"));- expect((await resolveHostPath(folders, join(home, "Library", "Mobile Documents", "com~apple~CloudDocs", "a.txt"))).exists).toBe(false);- expect(await reason(resolveHostPath(folders, join(home, "library", "Keychains", "x")))).toMatch(/settings, keys or app data/);- expect(await reason(resolveHostPath(folders, join(home.toUpperCase(), ".SSH", "id_ed25519")))).toMatch(/settings, keys or app data/);- });});diff --git a/server/host-files.ts b/server/host-files.tsdeleted file mode 100644index 7f34a177c0..0000000000--- a/server/host-files.ts+++ /dev/null@@ -1,289 +0,0 @@-// Security: a bot reaches the person's files here only inside their own folders: their home and the places Windows,-// macOS or the desktop name as their Desktop, Documents, Downloads (which OneDrive or iCloud may keep elsewhere). Never-// the system, another account, anything hidden at any depth (.git, .env, .ssh), Library or AppData, PowerShell's-// folders, the app's own data, nor anything through a link. A write never makes or changes something that runs: no-// script or program file type, no file with an execute bit, nothing in an app bundle or in a folder on PATH.-import { execFile } from "node:child_process";-import { promises as fs } from "node:fs";-import path from "node:path";--export type HostFilePlatform = "darwin" | "linux" | "win32";--export interface HostPlace {- name: string;- /** Real path, every link resolved. */- path: string;- /** The spelling it was found under, which a bot may use too (macOS /tmp is /private/tmp). */- given: string;-}--export interface HostFolders {- platform: HostFilePlatform;- /** Home first. */- places: HostPlace[];- denied: string[];- /** The folders on PATH, real paths. */- programs: string[];-}--/** The bridge's reading of `withHostFiles`; null leaves the file tools off. */-export function hostFilesSetting(value: string | undefined, platform: string | undefined): { platform: HostFilePlatform; appData: string[] } | null {- if (!value || (platform !== "darwin" && platform !== "linux" && platform !== "win32")) return null;- try {- const parsed: unknown = JSON.parse(value);- const appData = (parsed as { appData?: unknown })?.appData;- if (!Array.isArray(appData) || !appData.every((entry) => typeof entry === "string")) return null;- return { platform, appData };- } catch {- return null;- }-}--export class HostFileRefusal extends Error {}--export const OUTSIDE =- "That path is outside the person's own folders on this computer. Files can be read and saved only in their home folder and its subfolders, Desktop, Documents and Downloads included: call list_files with no path to see where those are.";-const SETTINGS = "That is a folder of settings, keys or app data, which bots cannot open. Use a folder such as Documents or Desktop.";-const RUNS = "Bots cannot save a file that runs as a program or script there. Save it as text (.txt, .md) or a document instead.";-const LINKED = "That path goes through a link or shortcut to another place, which is not followed. Use the real folder's path: list_files with no path shows it.";--const pathFor = (platform: HostFilePlatform) => (platform === "win32" ? path.win32 : path.posix);-/** Windows and macOS compare paths without case; macOS also without Unicode form. */-const fold = (platform: HostFilePlatform, value: string) => (platform === "linux" ? value : value.normalize("NFC").toLowerCase());--function trimmed(platform: HostFilePlatform, value: string): string {- const { sep, parse } = pathFor(platform);- return value.length > parse(value).root.length && value.endsWith(sep) ? value.slice(0, -1) : value;-}--export function sameOrInside(platform: HostFilePlatform, child: string, parent: string): boolean {- const { sep } = pathFor(platform);- const c = fold(platform, trimmed(platform, child));- const p = fold(platform, trimmed(platform, parent));- return c === p || c.startsWith(p.endsWith(sep) ? p : p + sep);-}--const WINDOWS_DEVICE = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$)(?:\..*)?$/i;--function badName(platform: HostFilePlatform, part: string): boolean {- if (part === "." || part === ".." || [...part].some((char) => char.charCodeAt(0) < 0x20)) return true;- return platform === "win32" && (WINDOWS_DEVICE.test(part) || /[<>:"|?*]/.test(part) || /[. ]$/.test(part));-}--/** The place a requested path is in and its names below it, or why it is refused. Pure: nothing on disk is read. */-export function placeOf(folders: HostFolders, raw: unknown): { place: HostPlace; parts: string[] } {- const { platform } = folders;- const p = pathFor(platform);- if (typeof raw !== "string" || !raw || raw.length > 4096 || raw.includes("\0")) throw new HostFileRefusal("Give the file's full path.");- const home = folders.places[0];- if (!home) throw new HostFileRefusal(OUTSIDE);- let text = raw;- if (text === "~" || text.startsWith("~/") || (platform === "win32" && text.startsWith("~\\"))) text = home.given + text.slice(1);- if (platform === "win32") {- // Drive-letter paths only: never \\server\share, \\?\ or \\.\ device paths, nor C:relative or a file:stream.- if (!/^[A-Za-z]:[\\/]/.test(text)) throw new HostFileRefusal("Give a full path that starts with a drive letter, like C:\\Users\\name\\Documents\\notes.txt.");- if (text.slice(2).includes(":")) throw new HostFileRefusal("A path cannot contain ':' after its drive letter.");- } else if (!text.startsWith("/")) {- throw new HostFileRefusal("Give a full path that starts with /, like " + p.join(home.given, "Documents", "notes.txt") + ".");- }- const normal = trimmed(platform, p.normalize(text)).normalize("NFC");- let best: { place: HostPlace; base: string } | undefined;- for (const place of folders.places) {- for (const base of [place.path, place.given]) {- if (sameOrInside(platform, normal, base) && (!best || base.length > best.base.length)) best = { place, base: trimmed(platform, base).normalize("NFC") };- }- }- if (!best) throw new HostFileRefusal(OUTSIDE);- const parts = normal.slice(best.base.length).split(p.sep).filter(Boolean);- if (parts.some((part) => badName(platform, part))) throw new HostFileRefusal("That path has a name a file cannot have here.");- return { place: best.place, parts };-}--/** Folders the shell and PowerShell run code from, at any depth. */-const RUNS_FROM = new Set(["powershell", "windowspowershell"]);-/** Opened by the system as a program, script or shortcut when double-clicked or listed. */-const RUNNABLE_TYPES: Record<HostFilePlatform, readonly string[]> = {- win32: [".bat", ".cmd", ".vbs", ".vbe", ".js", ".jse", ".wsf", ".wsh", ".hta", ".exe", ".scr", ".com", ".pif", ".msi", ".dll", ".ps1",- ".psm1", ".lnk", ".url", ".scf", ".library-ms", ".searchconnector-ms"],- darwin: [".command", ".terminal", ".app", ".tool", ".workflow"],- linux: [".desktop"],-};--/** The innermost place holding a real path, and the names below it. */-function within(folders: HostFolders, target: string): { place: HostPlace; parts: string[] } | null {- const { platform } = folders;- const holding = folders.places.filter((place) => sameOrInside(platform, target, place.path));- const place = holding.sort((a, b) => b.path.length - a.path.length)[0];- return place ? { place, parts: target.slice(trimmed(platform, place.path).length).split(pathFor(platform).sep).filter(Boolean) } : null;-}--/** Why a real path is off limits to read or write, or null. Pure. */-export function refusalFor(folders: HostFolders, target: string): string | null {- const { platform } = folders;- const found = within(folders, target);- if (!found) return OUTSIDE;- if (folders.denied.some((denied) => sameOrInside(platform, target, denied))) return SETTINGS;- const names = found.parts.map((part) => part.normalize("NFC").toLowerCase());- if (names.some((name) => name.startsWith(".") || RUNS_FROM.has(name))) return SETTINGS;- const top = found.place === folders.places[0] ? names[0] : undefined;- if (top === "library" || top === "appdata" || (platform === "linux" && top === "snap")) return SETTINGS;- return null;-}--/** Why a file may not be saved at this real path, beyond `refusalFor`, or null. Pure. */-export function writeRefusal(folders: HostFolders, target: string, kind: "file" | "folder" = "file"): string | null {- const { platform } = folders;- const p = pathFor(platform);- const names = trimmed(platform, target).split(p.sep).filter(Boolean).map((part) => part.normalize("NFC").toLowerCase());- if (platform === "darwin" && names.some((name) => name.endsWith(".app"))) return RUNS;- if (kind === "folder") return null;- const name = names.at(-1) ?? "";- if (RUNNABLE_TYPES[platform].some((type) => name.endsWith(type)) || (platform === "win32" && name === "desktop.ini")) return RUNS;- const folder = fold(platform, p.dirname(trimmed(platform, target)));- if (folders.programs.some((program) => fold(platform, trimmed(platform, program)) === folder)) return RUNS;- return null;-}--/** The real path of a requested one, refusing any link on the way, and whether it exists yet. Names past the first missing- * one are new and so cannot be links. */-export async function resolveHostPath(folders: HostFolders, raw: unknown): Promise<{ target: string; exists: boolean }> {- const { platform } = folders;- const p = pathFor(platform);- const { place, parts } = placeOf(folders, raw);- let current = place.path;- let walked = 0;- for (const part of parts) {- const next = p.join(current, part);- let stat;- try {- stat = await fs.lstat(next);- } catch (error) {- const code = (error as NodeJS.ErrnoException).code;- if (code === "ENOENT") break;- if (code === "ENOTDIR") throw new HostFileRefusal(`${current} is a file, not a folder.`);- throw error;- }- // Windows junctions and symlinks both read as links here.- if (stat.isSymbolicLink()) throw new HostFileRefusal(LINKED);- if (!stat.isDirectory() && walked < parts.length - 1) throw new HostFileRefusal(`${next} is a file, not a folder.`);- current = next;- walked += 1;- }- const real = await fs.realpath(current);- if (!sameOrInside(platform, real, place.path)) throw new HostFileRefusal(LINKED);- const target = p.join(real, ...parts.slice(walked));- const refused = refusalFor(folders, target);- if (refused) throw new HostFileRefusal(refused);- return { target, exists: walked === parts.length };-}--export type RunCommand = (file: string, args: string[], timeoutMs: number) => Promise<string>;--const runCommand: RunCommand = (file, args, timeoutMs) => new Promise((resolve, reject) => {- execFile(file, args, { timeout: timeoutMs, windowsHide: true, encoding: "utf8", maxBuffer: 256 * 1024 }, (error, stdout) => (error ? reject(error) : resolve(stdout)));-});--/** Windows' own answer for where each folder is, which OneDrive's backup moves (C:\Users\name\OneDrive\Documentos), as UTF-8 JSON. */-const WINDOWS_FOLDERS_SCRIPT = [- "[Console]::OutputEncoding = [Text.Encoding]::UTF8",- "$f = [ordered]@{}",- "foreach ($n in 'Desktop','MyDocuments','MyPictures','MyMusic','MyVideos') { $f[$n] = [Environment]::GetFolderPath($n) }",- "$d = (Get-ItemProperty -LiteralPath 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders' -ErrorAction SilentlyContinue).'{374DE290-123F-4565-9164-39C4925E467B}'",- "if ($d) { $f['Downloads'] = [Environment]::ExpandEnvironmentVariables($d) }",- "$f | ConvertTo-Json -Compress",-].join("\n");-const WINDOWS_NAMES: Record<string, string> = {- Desktop: "Desktop", MyDocuments: "Documents", Downloads: "Downloads", MyPictures: "Pictures", MyMusic: "Music", MyVideos: "Videos",-};-/** Cold PowerShell under an antivirus scan can take seconds on a slow PC. */-const WINDOWS_FOLDERS_MS = 15_000;--export function windowsFoldersFrom(output: string): Array<{ name: string; path: string }> {- let parsed: unknown;- try {- parsed = JSON.parse(output.trim().replace(/^\uFEFF/, ""));- } catch {- return [];- }- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return [];- return Object.entries(parsed as Record<string, unknown>).flatMap(([key, value]) => {- const name = WINDOWS_NAMES[key];- return name && typeof value === "string" && /^[A-Za-z]:\\/.test(value) ? [{ name, path: value }] : [];- });-}--function linuxFoldersFrom(text: string, home: string): Array<{ name: string; path: string }> {- const names: Record<string, string> = { DESKTOP: "Desktop", DOCUMENTS: "Documents", DOWNLOAD: "Downloads", PICTURES: "Pictures", MUSIC: "Music", VIDEOS: "Videos" };- const found: Array<{ name: string; path: string }> = [];- for (const line of text.split("\n")) {- const match = /^XDG_([A-Z]+)_DIR="(\$HOME\/[^"$`\\]*|\/[^"$`\\]*)"\s*$/.exec(line.trim());- const name = match && names[match[1]!];- if (name) found.push({ name, path: match[2]!.startsWith("$HOME/") ? path.posix.join(home, match[2]!.slice(6)) : match[2]! });- }- return found;-}--/** Where the person's named folders are, as found; not yet checked. */-export async function knownFolders(platform: HostFilePlatform, home: string, env: NodeJS.ProcessEnv, run: RunCommand = runCommand): Promise<Array<{ name: string; path: string }>> {- const p = pathFor(platform);- const under = (...names: string[]) => names.map((name) => ({ name, path: p.join(home, name) }));- if (platform === "darwin") {- return [...under("Desktop", "Documents", "Downloads", "Pictures", "Music", "Movies"),- { name: "iCloud Drive", path: p.join(home, "Library", "Mobile Documents", "com~apple~CloudDocs") },- { name: "Cloud storage", path: p.join(home, "Library", "CloudStorage") }];- }- if (platform === "linux") {- const configHome = env.XDG_CONFIG_HOME && p.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : p.join(home, ".config");- const listed = await fs.readFile(p.join(configHome, "user-dirs.dirs"), "utf8").then((text) => linuxFoldersFrom(text, home), () => []);- return [...listed, ...under("Desktop", "Documents", "Downloads")];- }- const systemRoot = env.SystemRoot && /^[A-Za-z]:\\/.test(env.SystemRoot) ? env.SystemRoot : "C:\\Windows";- const powershell = p.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");- const asked = await run(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(WINDOWS_FOLDERS_SCRIPT, "utf16le").toString("base64")], WINDOWS_FOLDERS_MS)- .then(windowsFoldersFrom, () => []);- const oneDrive = ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"].flatMap((key) => {- const value = env[key];- return value && /^[A-Za-z]:\\/.test(value) ? [{ name: "OneDrive", path: value }] : [];- });- return [...asked, ...oneDrive, ...under("Desktop", "Documents", "Downloads")];-}--/** A named folder may stand beside home (D:\Documents) on Windows, never as a drive, a parent of home or a system folder. */-function acceptablePlace(platform: HostFilePlatform, place: string, home: string, env: NodeJS.ProcessEnv): boolean {- const p = pathFor(platform);- if (!p.isAbsolute(place) || trimmed(platform, place) === p.parse(place).root || sameOrInside(platform, home, place)) return false;- if (sameOrInside(platform, place, home)) return true;- if (platform !== "win32" || sameOrInside(platform, place, p.dirname(trimmed(platform, home)))) return false;- const system = [env.SystemRoot, env.ProgramFiles, env["ProgramFiles(x86)"], env.ProgramData, "C:\\Windows", "C:\\Program Files", "C:\\Program Files (x86)", "C:\\ProgramData"];- return !system.some((folder) => folder && sameOrInside(platform, place, folder));-}--/** This person's folders, each real and checked, and what inside them stays closed: `appData` is the app's own data. */-export async function hostFolders(options: { platform: HostFilePlatform; home: string; env: NodeJS.ProcessEnv; appData: readonly string[]; run?: RunCommand }): Promise<HostFolders> {- const { platform, home, env } = options;- const p = pathFor(platform);- const realHome = await fs.realpath(home).catch(() => null);- if (!realHome) return { platform, places: [], denied: [], programs: [] };- const places: HostPlace[] = [{ name: "Home", path: realHome, given: home }];- for (const found of await knownFolders(platform, home, env, options.run)) {- if (!acceptablePlace(platform, found.path, home, env)) continue;- const real = await fs.realpath(found.path).catch(() => null);- if (!real || !acceptablePlace(platform, real, realHome, env) || places.some((place) => place.name === found.name || fold(platform, real) === fold(platform, place.path))) continue;- places.push({ name: found.name, path: real, given: found.path });- }- const denied = new Set<string>();- for (const entry of options.appData) {- if (!entry || !p.isAbsolute(entry)) continue;- denied.add(entry);- const real = await fs.realpath(entry).catch(() => null);- if (real) denied.add(real);- }- const programs = new Set<string>();- for (const entry of (env.PATH ?? env.Path ?? "").split(platform === "win32" ? ";" : ":")) {- if (!entry || !p.isAbsolute(entry)) continue;- programs.add(entry);- const real = await fs.realpath(entry).catch(() => null);- if (real) programs.add(real);- }- return { platform, places, denied: [...denied], programs: [...programs] };-}diff --git a/server/local-computer-proxy.ts b/server/local-computer-proxy.tsindex 62a8f53459..d031e3abc8 100644--- a/server/local-computer-proxy.ts+++ b/server/local-computer-proxy.ts@@ -3,7 +3,6 @@ import { homedir } from "node:os";import { runMcpBridge } from "./mcp-bridge.ts";import { augmentedPath } from "./env-path.ts";import { HOST_FILE_TOOLS, hostFileRelay } from "./host-file-tools.ts";-import { hostFilesSetting, hostFolders } from "./host-files.ts";import { localComputerCallQuery, localComputerRelay, localComputerResultLine } from "./local-computer-guidance.ts";import { journalUrl } from "./saved-steps/journal-tap.ts";import { COMPUTER_HELPER_STOPPED } from "../shared/your-computer.ts";@@ -36,8 +35,7 @@ try {}const screenRelay = localComputerRelay(platform ?? process.platform);-const files = hostFilesSetting(hostFiles, platform);-const fileRelay = files && hostFileRelay(() => hostFolders({ platform: files.platform, home: homedir(), env: process.env, appData: files.appData }));+const fileRelay = hostFiles === "1" ? hostFileRelay(homedir()) : null;runMcpBridge({command: command!,diff --git a/server/local-computer.ts b/server/local-computer.tsindex a4b67f1cfc..5ea1789ebf 100644--- a/server/local-computer.ts+++ b/server/local-computer.ts@@ -49,13 +49,10 @@ export function gatedLocalComputer(};}-/** This computer's bridge also answers file tools in the person's own folders (host-files.ts); `appData` stays closed. */-export function withHostFiles<T extends { env: Record<string, string>; scope?: "local-computer"; platform?: LocalComputerConnection["platform"] }>(- connection: T,- appData: readonly string[],-): T {+/** This computer's bridge also answers file tools (host-file-tools.ts); the person's approval level gates each call. */+export function withHostFiles<T extends { env: Record<string, string>; scope?: "local-computer"; platform?: LocalComputerConnection["platform"] }>(connection: T): T {if (connection.scope !== "local-computer" || !connection.env.OMB_CUA_COMMAND || !connection.platform) return connection;- return { ...connection, env: { ...connection.env, OMB_HOST_FILES: JSON.stringify({ appData }) } };+ return { ...connection, env: { ...connection.env, OMB_HOST_FILES: "1" } };}type LegacyConnectionDescriptor = {