Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

This computer: file tools for bots on API models (#6211)

Milind Soni4529acf69aa1
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index 82ef55df82..44e6e78dd2 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -701,7 +701,7 @@ export interface OptionCardData extends WaitCardField, ComputerAskField, AccessR
fixedOptions?: boolean;
quotaSwitch?: QuotaSwitchCardData;
/** Asks before a bot uses the person's own computer; what its first call names, for the question in their language. */
- yourComputer?: { app?: string; site?: string };
+ yourComputer?: { app?: string; site?: string; files?: boolean };
}
/** Kept on the card so the offer survives a restart. `engines` follow the card's options; `messageId` is the
diff --git a/server/bot-box/env.ts b/server/bot-box/env.ts
index cbe8ce03c3..b415cce99b 100644
--- a/server/bot-box/env.ts
+++ b/server/bot-box/env.ts
@@ -27,7 +27,7 @@ export const BOX_ENV_OMB_NAMES: ReadonlySet<string> = new Set([
"OMB_CONNECTOR_SERVICE_SLUGS", "OMB_CONNECTOR_APP_TOOLS", "OMB_CONNECTOR_APP_TOOL_NAMES",
"OMB_GATE_NAME", "OMB_GATE_UPSTREAM", "OMB_GATE_BUDGET", "OMB_GATE_SPILL_DIR", "OMB_GATE_SPILL_HINT", "OMB_GATE_TOOL_SCOPE",
"OMB_GATE_DIRECTORY", "OMB_GATE_APPS", "OMB_REMOTE_MCP_SERVER", "OMB_REMOTE_MCP_DIRECTORY", "OMB_REMOTE_MCP_APPS",
- "OMB_CONTROL_URL", "OMB_CONTROL_TOKEN", "OMB_COMPUTER_JOURNAL", "OMB_CUA_ARGS", "OMB_CUA_COMMAND", "OMB_CUA_PLATFORM",
+ "OMB_CONTROL_URL", "OMB_CONTROL_TOKEN", "OMB_COMPUTER_JOURNAL", "OMB_CUA_ARGS", "OMB_CUA_COMMAND", "OMB_CUA_PLATFORM", "OMB_HOST_FILES",
"OMB_PHONE_TOKEN", "OMB_ADB_PATH", "OMB_RESOURCES_PATH", "OMB_CODEX_AUTH_SOCKET", "OMB_CODEX_AUTH_SECRET",
"OMB_COPILOT_MCP_CONFIG", "OMB_BROWSER_PROFILE", "OMB_BOX_PROBE", "OMB_EXTRA_PATH", "OMB_TEST_SEALED_PATH",
]);
diff --git a/server/drivers/chat-host-computer.test.ts b/server/drivers/chat-host-computer.test.ts
index 0872d85068..95cea613ef 100644
--- a/server/drivers/chat-host-computer.test.ts
+++ b/server/drivers/chat-host-computer.test.ts
@@ -83,6 +83,8 @@ describe("this desktop's own computer in a chat turn", () => {
expect(one.env.OMB_CONTROL_TOKEN).not.toBe(two.env.OMB_CONTROL_TOKEN);
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":[]}' } }));
});
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-host-computer.ts b/server/drivers/chat-host-computer.ts
index 2087cece1f..9846d1140e 100644
--- a/server/drivers/chat-host-computer.ts
+++ b/server/drivers/chat-host-computer.ts
@@ -22,8 +22,8 @@ type Server = { command: string; args: string[]; env: Record<string, string> };
/** The driver behind the turn's gate, never the turn's own capability, so every turn on the same driver shares it. */
export function hostComputerKey(server: Server): string {
- const { OMB_CUA_COMMAND, OMB_CUA_ARGS, OMB_CUA_PLATFORM } = server.env;
- return JSON.stringify(OMB_CUA_COMMAND === undefined ? [server.command, server.args] : [OMB_CUA_COMMAND, OMB_CUA_ARGS ?? "", OMB_CUA_PLATFORM ?? ""]);
+ const { OMB_CUA_COMMAND, OMB_CUA_ARGS, OMB_CUA_PLATFORM, OMB_HOST_FILES } = server.env;
+ return JSON.stringify(OMB_CUA_COMMAND === undefined ? [server.command, server.args] : [OMB_CUA_COMMAND, OMB_CUA_ARGS ?? "", OMB_CUA_PLATFORM ?? "", OMB_HOST_FILES ?? ""]);
}
const lastListed = new Map<string, unknown[]>();
diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.ts
index ba61552394..c9023695d1 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 { stripControlPlaneEnv } from "../config.ts";
+import { DATA_DIR, stripControlPlaneEnv } from "../config.ts";
import type { SendTurnInput } from "../contracts.ts";
import { cloudRole } from "../bot-box/detect.ts";
import { redactSecretsInText } from "../redact.ts";
@@ -24,6 +24,7 @@ import { fitToolList, withoutDanglingReferences } from "../mcp-tool-schema.ts";
import { listsComputerTool } from "../computer-tool-list.ts";
import { HOST_COMPUTER_QUICK_MS, HOST_COMPUTER_READY, hostComputerDidNotStart, hostComputerFailure, hostComputerKey, hostComputerNotice, hostComputerStandIn, hostComputerStarted,
hostComputerStartupMs, startHostComputer, watchHostComputerStart, type HostComputerStart } from "./chat-host-computer.ts";
+import { withHostFiles } from "../local-computer.ts";
import { READ_OPEN_PAGE_ONLY, readsAroundBrowser } from "../browser-tool-shape.ts";
import { capToolList, learnToolCountLimit, shareToolBudget, toolCountLimitFromError } from "../tool-count-limit.ts";
import type { ToolSchemaProfile } from "../tool-schema-profile.ts";
@@ -870,3 +871,8 @@ 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). */
+export function withHostFileTools(integrations: SendTurnInput["integrations"]): SendTurnInput["integrations"] {
+ return integrations?.localComputer ? { ...integrations, localComputer: withHostFiles(integrations.localComputer, [DATA_DIR]) } : integrations;
+}
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index b3814f2aff..2f8f82b7ac 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -14,7 +14,7 @@ import { ASK_USER_TOOL, ASK_USER_TOOL_DEFINITION, askQuestionSummary, parseAskQu
import { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";
import { redactSecretsInText } from "../redact.ts";
import { toolDetailPreview } from "../tool-summary.ts";
-import { ChatToolSessionError, chatToolNotices, mountChatTools, refitChatTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";
+import { ChatToolSessionError, chatToolNotices, mountChatTools, refitChatTools, withHostFileTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";
import { noteToolBudget } from "../tool-budgets.ts";
import { chatToolLimitFor, chatToolLimitKey } from "../tool-count-limit.ts";
import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent, type ChatContentPart } from "./chat-images.ts";
@@ -608,7 +608,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (!parsed.ok) throw new Error(parsed.error);
const scope = parsed.scope;
const toolsOff = options.tools === false || options.toolUse?.(model) === false;
- tools = await mountChatTools(toolsOff ? undefined : turn.integrations, abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,
+ tools = await mountChatTools(toolsOff ? undefined : withHostFileTools(turn.integrations), abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,
toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model), { conversation: turn.threadId, notice: ({ message, text }) => emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message), text }) });
noteToolBudget(turn.botId, tools.budget);
for (const message of chatToolNotices(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });
diff --git a/server/host-file-tools.ts b/server/host-file-tools.ts
new file mode 100644
index 0000000000..cd8a2b5fb8
--- /dev/null
+++ b/server/host-file-tools.ts
@@ -0,0 +1,253 @@
+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";
+
+export const HOST_FILE_READ_LIMIT = 10 * 1024 * 1024;
+export const HOST_FILE_WRITE_LIMIT = 25 * 1024 * 1024;
+const LISTED = 500;
+
+const encoding = { type: "string", enum: ["utf8", "base64"], description: "utf8 (default) for text, base64 for any other file." };
+
+/** What a bot on this computer is offered beside the screen tools. */
+export 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.",
+ 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.",
+ 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.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ path: { type: "string", description: "Full path of the file." },
+ content: { type: "string" },
+ encoding,
+ overwrite: { type: "boolean", description: "true to replace a file that is already there." },
+ },
+ required: ["path", "content"],
+ additionalProperties: false,
+ },
+ },
+ {
+ name: "make_folder",
+ description: "Make a folder, and any missing folders above it, in the person's folders on this computer.",
+ inputSchema: { type: "object", properties: { path: { type: "string", description: "Full path of the folder." } }, required: ["path"], additionalProperties: false },
+ },
+] as const;
+
+export const HOST_FILE_TOOL_NAMES: ReadonlySet<string> = new Set(HOST_FILE_TOOLS.map((tool) => tool.name));
+
+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 });
+
+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 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);
+}
+
+/** 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}.`);
+ 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);
+ lines.push(`file ${entry.name}${stat ? ` (${sizeText(stat.size)})` : ""}`);
+ }
+ }
+ const more = entries.length > LISTED ? `\n…and ${entries.length - LISTED} more` : "";
+ return said(`${target}\n${lines.join("\n") || "(empty)"}${more}`);
+}
+
+async function readFile(folders: HostFolders, 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();
+ }
+}
+
+async function writeFile(folders: HostFolders, 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.");
+ 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);
+ // 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);
+ 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);
+ }
+ } 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;
+}
+
+/** A finished temp file put at a path nothing may hold yet: a link fails if anything got there meanwhile, and where a
+ * folder takes no links (FAT, some cloud folders) a copy that fails the same way. The temp file goes either way. */
+export async function placeNew(temp: string, target: string, link: (from: string, to: string) => Promise<void> = fs.link): Promise<void> {
+ try {
+ try {
+ await link(temp, target);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === "EEXIST") throw alreadyThere(target);
+ if (!["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "ENOSYS", "EINVAL", "EMLINK"].includes(code ?? "")) throw error;
+ await fs.copyFile(temp, target, constants.COPYFILE_EXCL).catch((copyError: NodeJS.ErrnoException) => {
+ throw copyError.code === "EEXIST" ? alreadyThere(target) : copyError;
+ });
+ }
+ } finally {
+ await fs.unlink(temp).catch(() => {});
+ }
+}
+
+/** Windows refuses a rename onto a file an indexer, antivirus or sync client holds for a moment. */
+async function renameWithRetry(from: string, to: string): Promise<void> {
+ for (const wait of [0, 50, 150, 400, 1000]) {
+ if (wait) await new Promise((settle) => setTimeout(settle, wait));
+ try {
+ await fs.rename(from, to);
+ return;
+ } catch (error) {
+ if (!["EPERM", "EACCES", "EBUSY"].includes((error as NodeJS.ErrnoException).code ?? "") || wait === 1000) throw error;
+ }
+ }
+}
+
+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}.`);
+}
+
+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;
+ 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));
+ };
+}
diff --git a/server/host-files.e2e.test.ts b/server/host-files.e2e.test.ts
new file mode 100644
index 0000000000..5e5c91d993
--- /dev/null
+++ b/server/host-files.e2e.test.ts
@@ -0,0 +1,228 @@
+import { spawn, type ChildProcess } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { delimiter, dirname, join } from "node:path";
+import { createInterface } from "node:readline";
+import { describe, expect, it } from "vitest";
+
+import { mountChatTools, withHostFileTools, type ChatToolSession } from "./drivers/chat-mcp-tools.ts";
+import { gatedLocalComputer, withHostFiles } from "./local-computer.ts";
+
+// A disposable stand-in for this computer's driver: it lists one screen tool (and a read_file of its own, which the
+// bridge's must replace) and reports every call it was handed. It never opens a screen.
+const FAKE_DRIVER = `
+const readline = require("node:readline");
+const seen = [];
+readline.createInterface({ input: process.stdin }).on("line", (line) => {
+ const message = JSON.parse(line);
+ if (message.id === undefined) return;
+ let result;
+ if (message.method === "initialize") {
+ result = { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "cua-driver", version: "0.41.3" } };
+ return setTimeout(() => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }) + "\\n"), Number(process.env.FAKE_DELAY_MS ?? 0));
+ }
+ else if (message.method === "tools/list") result = { tools: [
+ { name: "screenshot", description: "Screen", inputSchema: { type: "object", properties: {} } },
+ { name: "read_file", description: "driver's own", inputSchema: { type: "object", properties: {} } },
+ ] };
+ else { seen.push(message.params.name); result = { content: [{ type: "text", text: JSON.stringify(seen) }] }; }
+ process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }) + "\\n");
+});
+`;
+
+const FILE_TOOLS = ["list_files", "read_file", "write_file", "make_folder"];
+
+async function controlServer() {
+ const state = { held: false, asked: [] as string[] };
+ const server = createServer((request, response) => {
+ state.asked.push(request.url ?? "");
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end(JSON.stringify(state.held ? { held: true, helpOpen: false, blockedReason: "Another thread is using this computer." } : { held: false, helpOpen: false }));
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const control = { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/control`, token: "fixture-token" };
+ return { state, control, close: () => new Promise<void>((resolve) => server.close(() => resolve())) };
+}
+
+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> = {}) {
+ const gate = await controlServer();
+ const gated = gatedLocalComputer(driver(), gate.control);
+ const connection = files ? withHostFiles(gated, [appData]) : 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 },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ const replies = new Map<number, (value: any) => void>();
+ createInterface({ input: child.stdout! }).on("line", (line) => {
+ const message = JSON.parse(line);
+ replies.get(message.id)?.(message);
+ replies.delete(message.id);
+ });
+ let nextId = 0;
+ const rpc = (method: string, params: Record<string, unknown> = {}): Promise<any> => {
+ const id = ++nextId;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(`no answer to ${method}`)), 20_000);
+ replies.set(id, (value) => { clearTimeout(timer); resolve(value.result); });
+ child.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
+ });
+ };
+ const call = async (name: string, args: Record<string, unknown> = {}) => {
+ const result = await rpc("tools/call", { name, arguments: args });
+ return { text: result.content.map((part: { text: string }) => part.text).join("\n") as string, error: result.isError === true };
+ };
+ await rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "fixture", version: "1" } });
+ return {
+ rpc, call,
+ hold(value: boolean) { gate.state.held = value; },
+ asked: gate.state.asked,
+ async close() {
+ child.kill("SIGKILL");
+ await gate.close();
+ },
+ };
+}
+
+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 () => {
+ 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 });
+ 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) });
+ 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");
+ expect(computer.asked.at(-1)).toContain("files=1");
+ expect(places.text).toContain(`Home: ${real}`);
+
+ const target = join(home, "OneDrive", "Documentos", "My Agents", "Vendas", "resumo.md");
+ const saved = await computer.call("write_file", { path: target, content: "# Resumo\nolá" });
+ 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á");
+
+ const again = await computer.call("write_file", { path: target, content: "other" });
+ expect(again.error).toBe(true);
+ expect(again.text).toMatch(/already exists.*overwrite: true/);
+ expect(readFileSync(written, "utf8")).toBe("# Resumo\nolá");
+ expect(await computer.call("write_file", { path: target, content: "novo", overwrite: true }))
+ .toEqual({ text: `Saved 4 bytes to ${written} (replaced the file that was there).`, error: false });
+ expect(readdirSync(dirname(written))).toEqual(["resumo.md"]);
+
+ expect(await computer.call("read_file", { path: target })).toEqual({ text: `${written} (4 bytes):\nnovo`, error: false });
+ expect((await computer.call("read_file", { path: target, encoding: "base64" })).text).toContain(Buffer.from("novo").toString("base64"));
+ writeFileSync(join(home, "Desktop", "image.bin"), Buffer.from([0xff, 0xfe, 0x00]));
+ expect((await computer.call("read_file", { path: join(home, "Desktop", "image.bin") })).text).toMatch(/encoding base64/);
+
+ expect((await computer.call("make_folder", { path: join(home, "Desktop", "Novo", "Sub") })).text).toBe(`Made the folder ${join(real, "Desktop", "Novo", "Sub")}.`);
+ 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),
+ ] 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(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([]);
+
+ computer.hold(true);
+ const gated = await computer.call("write_file", { path: join(home, "Desktop", "while-held.txt"), content: "x" });
+ expect(gated).toEqual({ text: "Another thread is using this computer.", error: true });
+ expect(readdirSync(join(home, "Desktop"))).not.toContain("while-held.txt");
+ computer.hold(false);
+
+ // The driver itself was never handed a file call.
+ expect(JSON.parse((await computer.call("screenshot")).text)).toEqual(["screenshot"]);
+ } finally {
+ await computer.close();
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ it("reach a chat bot as computer tools, and stay in the list the next turn remembers while the driver starts", async () => {
+ const root = mkdtempSync(join(tmpdir(), "omb-host-files-e2e-"));
+ const home = join(root, "home");
+ mkdirSync(join(home, "Documents"), { recursive: true });
+ const gate = await controlServer();
+ const controller = new AbortController();
+ const sessions: ChatToolSession[] = [];
+ const mount = async (env: Record<string, string>) => {
+ const turn = withHostFileTools({ localComputer: gatedLocalComputer(driver(env), gate.control) });
+ const localComputer = { ...turn!.localComputer!, env: { ...turn!.localComputer!.env, HOME: home, USERPROFILE: home } };
+ const session = await mountChatTools({ localComputer }, controller.signal, true, undefined, undefined, undefined, undefined, undefined, undefined, { startupMs: 300, hostComputerMs: 20_000 });
+ sessions.push(session);
+ return session;
+ };
+ const names = (session: ChatToolSession) => session.definitions.map((definition) => definition.function.name);
+ try {
+ const cold = await mount({});
+ expect(names(cold)).toEqual(["computer_screenshot", ...FILE_TOOLS.map((name) => `computer_${name}`)]);
+ const asked = Date.now();
+ const warm = await mount({ FAKE_DELAY_MS: "2500" });
+ expect(Date.now() - asked).toBeLessThan(2_000);
+ expect(names(warm)).toEqual(names(cold));
+ const saved = await warm.execute("computer_write_file", { path: join(home, "Documents", "nota.txt"), content: "oi" }, controller.signal);
+ expect(saved).toMatchObject({ ok: true, text: `Saved 2 bytes to ${join(realpathSync(home), "Documents", "nota.txt")}.` });
+ expect(readFileSync(join(home, "Documents", "nota.txt"), "utf8")).toBe("oi");
+ } finally {
+ controller.abort();
+ await Promise.all(sessions.map((session) => session.close().catch(() => {})));
+ await gate.close();
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ 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);
+ try {
+ expect((await computer.rpc("tools/list")).tools.map((tool: { name: string }) => tool.name)).toEqual(["screenshot", "read_file"]);
+ } finally {
+ await computer.close();
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 60_000);
+});
diff --git a/server/host-files.test.ts b/server/host-files.test.ts
new file mode 100644
index 0000000000..6ca7af20ef
--- /dev/null
+++ b/server/host-files.test.ts
@@ -0,0 +1,286 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, 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 { 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", () => {
+ 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"] });
+ 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();
+ const turn = withHostFileTools({ localComputer: gated, agents: { command: "agents", args: [], env: {} } });
+ expect(hostFilesSetting(turn?.localComputer?.env.OMB_HOST_FILES, "win32")?.appData).toHaveLength(1);
+ expect(turn?.agents).toEqual({ command: "agents", args: [], env: {} });
+ const none = { agents: { command: "agents", args: [], env: {} } };
+ expect(withHostFileTools(none)).toBe(none);
+ });
+
+ it("lists the file tools to a chat bot beside the screen tools, the built-in browser too", () => {
+ for (const tool of HOST_FILE_TOOLS) expect(listsComputerTool(tool.name, true), tool.name).toBe(true);
+ });
+});
+
+describe("paths 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-"));
+ 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 };
+ };
+ 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.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);
+
+ 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 });
+
+ 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/);
+ }
+ expect(await reason(resolveHostPath(folders, "Documents/a.txt"))).toMatch(/starts with \//);
+ });
+
+ it("puts a new file in place only while nothing is there, with or without links, and never overwrites what appeared", async () => {
+ const { home } = fixture();
+ const temp = join(home, "Documents", ".a.txt.tmp");
+ const target = join(home, "Documents", "a.txt");
+ writeFileSync(temp, "new");
+ await placeNew(temp, target);
+ expect(readFileSync(target, "utf8")).toBe("new");
+ expect(existsSync(temp)).toBe(false);
+
+ writeFileSync(temp, "late");
+ expect(await reason(placeNew(temp, target))).toMatch(/already exists.*overwrite: true/);
+ expect(readFileSync(target, "utf8")).toBe("new");
+ expect(existsSync(temp)).toBe(false);
+
+ const noLinks = async () => { throw Object.assign(new Error("links not supported"), { code: "EPERM" }); };
+ writeFileSync(temp, "copied");
+ await placeNew(temp, join(home, "Documents", "b.txt"), noLinks);
+ expect(readFileSync(join(home, "Documents", "b.txt"), "utf8")).toBe("copied");
+ writeFileSync(temp, "late");
+ expect(await reason(placeNew(temp, join(home, "Documents", "b.txt"), noLinks))).toMatch(/already exists/);
+ 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.ts
new file mode 100644
index 0000000000..7f34a177c0
--- /dev/null
+++ b/server/host-files.ts
@@ -0,0 +1,289 @@
+// 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-guidance.test.ts b/server/local-computer-guidance.test.ts
index f4b17c7912..02f006b675 100644
--- a/server/local-computer-guidance.test.ts
+++ b/server/local-computer-guidance.test.ts
@@ -78,6 +78,9 @@ describe("localComputerResultLine", () => {
const frame = { jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "launch_app", arguments: { bundle_id: "com.google.Chrome", urls: ["https://calendar.google.com/"] } } };
expect(localComputerCallQuery(frame)).toEqual({ app: "Chrome", site: "calendar.google.com" });
expect(localComputerCallQuery({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "screenshot", arguments: {} } })).toEqual({});
+ for (const name of ["list_files", "read_file", "write_file", "make_folder"]) {
+ expect(localComputerCallQuery({ jsonrpc: "2.0", id: 6, method: "tools/call", params: { name, arguments: { path: "/x", url: "https://evil.example" } } })).toEqual({ files: "1" });
+ }
});
it("passes every other frame through byte for byte", () => {
diff --git a/server/local-computer-guidance.ts b/server/local-computer-guidance.ts
index 65d0c2b263..b2f3662062 100644
--- a/server/local-computer-guidance.ts
+++ b/server/local-computer-guidance.ts
@@ -3,6 +3,7 @@
// names only those two, so a bot relays them to the person, who has no way to act on either.
import { typeOneCharacterAtATime, typesInOneBurst } from "../electron/paced-typing.mjs";
import { describeComputerCall } from "../shared/your-computer.ts";
+import { HOST_FILE_TOOL_NAMES } from "./host-file-tools.ts";
import type { ChildCalls, ToolCall } from "./mcp-bridge.ts";
import { CLICK_TOOLS, unconfirmedClickResult } from "./unconfirmed-click.ts";
@@ -64,6 +65,8 @@ export function localComputerResultLine(line: string): string {
/** The query a screen call carries to the gate: the app and site it would open, for the person's one-time question. */
export function localComputerCallQuery(frame: unknown): Record<string, string> {
+ const name = (frame as { params?: { name?: unknown } } | null)?.params?.name;
+ if (typeof name === "string" && HOST_FILE_TOOL_NAMES.has(name)) return { files: "1" };
const { app, site } = describeComputerCall(frame);
return { ...(app ? { app } : {}), ...(site ? { site } : {}) };
}
diff --git a/server/local-computer-proxy.ts b/server/local-computer-proxy.ts
index dbc3a21dfc..62a8f53459 100644
--- a/server/local-computer-proxy.ts
+++ b/server/local-computer-proxy.ts
@@ -1,6 +1,9 @@
// The descriptor and turn token travel in environment variables, never argv or logs.
+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";
@@ -12,6 +15,7 @@ const {
OMB_CONTROL_URL: url,
OMB_CONTROL_TOKEN: token,
OMB_COMPUTER_JOURNAL: journal,
+ OMB_HOST_FILES: hostFiles,
...childEnv
} = process.env;
@@ -31,6 +35,10 @@ try {
process.exit(2);
}
+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 }));
+
runMcpBridge({
command: command!,
args,
@@ -39,6 +47,7 @@ runMcpBridge({
gate: { url: url!, token: token!, describe: localComputerCallQuery },
...(journal === "1" ? { journal: { url: journalUrl(url!), token: token! } } : {}),
rewriteResponse: localComputerResultLine,
- relay: localComputerRelay(platform ?? process.platform),
+ relay: fileRelay ? (call, child) => fileRelay(call) ?? screenRelay(call, child) : screenRelay,
+ ...(fileRelay ? { ownTools: HOST_FILE_TOOLS } : {}),
respawn: { stopped: COMPUTER_HELPER_STOPPED },
});
diff --git a/server/local-computer.ts b/server/local-computer.ts
index dd63ba391a..a4b67f1cfc 100644
--- a/server/local-computer.ts
+++ b/server/local-computer.ts
@@ -49,6 +49,15 @@ 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 {
+ 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 }) } };
+}
+
type LegacyConnectionDescriptor = {
mode?: string;
socketPath?: unknown;
diff --git a/server/mcp-bridge.ts b/server/mcp-bridge.ts
index a398d6cca1..ef360f94d0 100644
--- a/server/mcp-bridge.ts
+++ b/server/mcp-bridge.ts
@@ -118,6 +118,8 @@ export interface BridgeOptions {
/** A tools/call the bridge carries out itself through the child, answering the agent with what this resolves to; null
* forwards the frame as it came. Frames after it wait, so the agent's calls still act in order. */
relay?: (call: ToolCall, child: ChildCalls) => Promise<unknown> | null;
+ /** Tools the bridge lists beside the child's, which `relay` answers. */
+ ownTools?: readonly Record<string, unknown>[];
/** The child can die and come back behind this bridge (the app restarts the driver), so the agent's connection stays up:
* calls that were waiting are answered with `stopped`, and the next call starts a new child. */
respawn?: { stopped: string };
@@ -350,7 +352,7 @@ export function runMcpBridge(options: BridgeOptions): void {
: null;
const reply = createReplyQueue(tap, (written) => process.stdout.write(written + "\n"));
const answer = (line: string) => reply(line, line);
- const toolLists = createToolListNormalizer(toolSchemaProfileFromEnv(), (line) => process.stderr.write(`${options.label}: ${line}\n`));
+ const toolLists = createToolListNormalizer(toolSchemaProfileFromEnv(), (line) => process.stderr.write(`${options.label}: ${line}\n`), options.ownTools);
// Injected responses must never land inside one of the child's half-written frames.
const rewrite = options.rewriteResponse ?? ((line: string) => line);
const respond = (line: string) => reply(line, textOnlyErrorResultLine(rewrite(toolLists.rewriteResponse(line))));
@@ -437,14 +439,15 @@ export function runMcpBridge(options: BridgeOptions): void {
/** Waits for a dead child to come back. Frames are sent one at a time, so at most one revival runs. */
const childAlive = () => (childGone ? (revival ??= reviveChild().finally(() => { revival = null; })) : Promise.resolve(true));
+ const ownNames = new Set((options.ownTools ?? []).map((tool) => tool.name));
const send = async (line: string) => {
- if (respawn && !(await childAlive())) {
- const frame = noteRequest(line);
- if (frame) answerStopped(frame.id, frame.method, frame.params?._meta, respawn.stopped);
+ const frame = line.includes('"tools/call"') ? relayableCall(line) : null;
+ if (respawn && !(frame && ownNames.has(frame.call.name)) && !(await childAlive())) {
+ const request = noteRequest(line);
+ if (request) answerStopped(request.id, request.method, request.params?._meta, respawn.stopped);
waitingOnChild.clear();
return;
}
- const frame = line.includes('"tools/call"') ? relayableCall(line) : null;
const relayed = frame && options.relay?.(frame.call, children.forCall(frame.meta));
if (!frame || !relayed) {
if (respawn) noteRequest(line);
diff --git a/server/mcp-tool-schema.ts b/server/mcp-tool-schema.ts
index 31d93699c4..f080d1f412 100644
--- a/server/mcp-tool-schema.ts
+++ b/server/mcp-tool-schema.ts
@@ -142,7 +142,8 @@ export function fitToolListResult(result: unknown, profile: ToolSchemaProfile |
}
/** Every listed schema gets a plain object root; under a profile each is also fitted to it. */
-export function createToolListNormalizer(profile?: ToolSchemaProfile, log?: (line: string) => void): {
+/** `ownTools`: listed after the child's on its last page, in place of any child tool of the same name. */
+export function createToolListNormalizer(profile?: ToolSchemaProfile, log?: (line: string) => void, ownTools: readonly JsonObject[] = []): {
observeRequest: (line: string) => void;
rewriteResponse: (line: string) => string;
} {
@@ -173,13 +174,17 @@ export function createToolListNormalizer(profile?: ToolSchemaProfile, log?: (lin
if (!isObject(frame) || "method" in frame || !pending.delete(idKey(frame.id))) return line;
if (!isObject(frame.result) || !Array.isArray(frame.result.tools)) return line;
- const listed: unknown[] = frame.result.tools;
+ const own = frame.result.nextCursor ? [] : ownTools;
+ const ownNames = new Set(own.map((tool) => tool.name));
+ const listed: unknown[] = own.length
+ ? [...frame.result.tools.filter((tool: unknown) => !isObject(tool) || !ownNames.has(tool.name)), ...own]
+ : frame.result.tools;
const tools = profile ? fitToolList(listed, profile, log) : listed.map((tool: unknown) => {
if (!isObject(tool)) return tool;
const inputSchema = providerSafeInputSchema(tool.inputSchema);
return inputSchema === tool.inputSchema ? tool : { ...tool, inputSchema };
});
- const changed = tools.length !== listed.length || tools.some((tool, index) => tool !== listed[index]);
+ const changed = own.length > 0 || tools.length !== listed.length || tools.some((tool, index) => tool !== listed[index]);
return changed ? JSON.stringify({ ...frame, result: { ...frame.result, tools } }) : line;
},
};
diff --git a/server/your-computer-consent.test.ts b/server/your-computer-consent.test.ts
index e299ddf715..269bdce9e8 100644
--- a/server/your-computer-consent.test.ts
+++ b/server/your-computer-consent.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { claimWithYourComputerConsent, YourComputerDeclined } from "./your-computer-consent.ts";
+import { claimWithYourComputerConsent, yourComputerCallFrom, YourComputerDeclined } from "./your-computer-consent.ts";
describe("claimWithYourComputerConsent", () => {
const run = (levels: boolean[], answer: "allow" | "deny" = "allow") => {
@@ -36,3 +36,12 @@ describe("claimWithYourComputerConsent", () => {
expect(steps).toEqual(["bind", "ask"]);
});
});
+
+describe("what a call on the person's computer asks about", () => {
+ it("asks about their files for a file call, and about the app or site otherwise", () => {
+ expect(yourComputerCallFrom(new URLSearchParams("files=1"))).toEqual({ files: true });
+ expect(yourComputerCallFrom(new URLSearchParams("files=1&app=Chrome"))).toEqual({ files: true });
+ expect(yourComputerCallFrom(new URLSearchParams("files=yes&app=Chrome"))).toEqual({ app: "Chrome" });
+ expect(yourComputerCallFrom(new URLSearchParams(""))).toBeUndefined();
+ });
+});
diff --git a/server/your-computer-consent.ts b/server/your-computer-consent.ts
index d4fcc1d2e9..f4dd355c0a 100644
--- a/server/your-computer-consent.ts
+++ b/server/your-computer-consent.ts
@@ -56,6 +56,7 @@ const pending = new Map<string, Pending>();
export function yourComputerCallFrom(query: URLSearchParams): YourComputerCall | undefined {
const app = cleanAppName(query.get("app"));
const site = cleanSiteName(query.get("site"));
+ if (query.get("files") === "1") return { files: true };
return app || site ? { ...(app ? { app } : {}), ...(site ? { site } : {}) } : undefined;
}
@@ -94,7 +95,7 @@ export function askToUseYourComputer(
requestId,
requestType: "permission",
tool: YOUR_COMPUTER_TOOL,
- yourComputer: call ? { ...(call.app ? { app: call.app } : {}), ...(call.site ? { site: call.site } : {}) } : {},
+ yourComputer: call?.files ? { files: true } : call ? { ...(call.app ? { app: call.app } : {}), ...(call.site ? { site: call.site } : {}) } : {},
},
});
pending.set(requestId, {
diff --git a/shared/your-computer.test.ts b/shared/your-computer.test.ts
index 61aa0fb5d9..324af7b5d2 100644
--- a/shared/your-computer.test.ts
+++ b/shared/your-computer.test.ts
@@ -23,6 +23,8 @@ describe("the one-time question before a bot uses the person's own computer", ()
expect(ask({ site: "www.opentable.com" })).toBe("I need to use your browser where you're signed in to opentable.com. Allow once?");
expect(ask({ app: "Keynote" })).toBe("I need to use Keynote on your computer. Allow once?");
expect(ask({})).toBe("I need to use your files and apps on this computer for this. Allow once?");
+ expect(ask({ files: true })).toBe("I need to read and save files in your folders on this computer. Allow once?");
+ expect(ask({ files: true, app: "Chrome" })).toBe("I need to read and save files in your folders on this computer. Allow once?");
expect(ask(undefined)).toBe("I need to use your files and apps on this computer for this. Allow once?");
});
diff --git a/shared/your-computer.ts b/shared/your-computer.ts
index 2366e371b8..b625e39c45 100644
--- a/shared/your-computer.ts
+++ b/shared/your-computer.ts
@@ -8,6 +8,8 @@ export interface YourComputerCall {
app?: string;
/** A host name only, never a path or query: "calendar.google.com". */
site?: string;
+ /** The call reads or saves files in the person's folders. */
+ files?: boolean;
}
export const YOUR_COMPUTER_WORDS = {
@@ -16,6 +18,7 @@ export const YOUR_COMPUTER_WORDS = {
"approval.yourComputer.site": "I need to use your browser where you're signed in to {site}. Allow once?",
"approval.yourComputer.app": "I need to use {app} on your computer. Allow once?",
"approval.yourComputer.screen": "I need to use your files and apps on this computer for this. Allow once?",
+ "approval.yourComputer.files": "I need to read and save files in your folders on this computer. Allow once?",
"approval.yourComputer.detail": "{name} can use your files and apps here: it sees your screen and clicks and types on it, for this request only.",
} as const;
@@ -91,6 +94,7 @@ export function describeComputerCall(frame: unknown): YourComputerCall {
/** The question for this call, as a catalog key and its values. */
export function yourComputerQuestion(call: YourComputerCall = {}): { key: YourComputerKey; params: Record<string, string> } {
+ if (call.files === true) return { key: "approval.yourComputer.files", params: {} };
const app = cleanAppName(call.app);
const site = cleanSiteName(call.site);
const browser = app && Object.values(BROWSERS).includes(app) ? app : undefined;
diff --git a/src/locales/en.json b/src/locales/en.json
index 5c5a22d2fb..f6f3906526 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -1232,6 +1232,7 @@
"approval.yourComputer.site": "I need to use your browser where you're signed in to {site}. Allow once?",
"approval.yourComputer.app": "I need to use {app} on your computer. Allow once?",
"approval.yourComputer.screen": "I need to use your files and apps on this computer for this. Allow once?",
+ "approval.yourComputer.files": "I need to read and save files in your folders on this computer. Allow once?",
"approval.yourComputer.detail": "{name} can use your files and apps here: it sees your screen and clicks and types on it, for this request only.",
"computerAsk.want.screen": "{name} wants to use your {device}'s apps and screen",
"computerAsk.want.folders": "{name} wants to use the files on your {device}",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index ba994bbaa4..9f0d3da90e 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -8074,6 +8074,7 @@
"approval.yourComputer.site": "Preciso usar seu navegador, onde você já fez login em {site}. Permitir uma vez?",
"approval.yourComputer.app": "Preciso usar {app} no seu computador. Permitir uma vez?",
"approval.yourComputer.screen": "Preciso usar seus arquivos e apps neste computador para isso. Permitir uma vez?",
+ "approval.yourComputer.files": "Preciso ler e salvar arquivos nas suas pastas neste computador. Permitir uma vez?",
"approval.yourComputer.detail": "{name} poderá usar seus arquivos e apps aqui: vê a tela, clica e digita nela, só para este pedido.",
"computerAsk.want.screen": "{name} quer usar os apps e a tela do seu {device}",
"computerAsk.want.folders": "{name} quer usar os arquivos do seu {device}",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index 0143161c0b..b85301a3b8 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -33470,6 +33470,7 @@
"approval.yourComputer.site": "4753f3101089efc83a3d57c8c6da1fc7fe22564b2c4bb80967a913f360cc6456",
"approval.yourComputer.app": "11c6d43b76517981ac5715bba5da6a8c82aba1452a168b023c1ebaa430e542f2",
"approval.yourComputer.screen": "173a105d07b838292130e293c9d2a5cb71fef9b90b95bbce1815c92b05c640fb",
+ "approval.yourComputer.files": "21d84df9f7719a6eb0cb25a3743493f9eac1ea1c3a5d976a3d996c5086d683b0",
"approval.yourComputer.detail": "bdfee9c69345702b0082d4b09ad5c2e65f87a95af5126b4390fb50a0bdfa00aa",
"computerAsk.want.screen": "efe0cfa998242450e990e1d95f9a902ca8d62ffbcfb0923428496aa60779532d",
"computerAsk.want.folders": "a85ba5200a3d98eb3a3a1da2b33da159b15cc246724c1845041b45484f2f0639",