Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(approvals): a bot reading its own files never asks, at any level (#3791)
Milind Soni267fa44f9fe4
diff --git a/docs/approval-levels.md b/docs/approval-levels.mdindex a5690252f4..e3d3a7ec8b 100644--- a/docs/approval-levels.md+++ b/docs/approval-levels.md@@ -5,9 +5,21 @@ when that provider resumes an existing native thread. You can also change onewhile the bot is working (see below). Each level is one of theprovider's own permission modes, passed through. A native tool request thatreaches you is one the provider left for you. OpenMausBot only answers from an-explicit grant: Full Access, a saved exact command or MCP read-shaped tool, or-the narrow built-in web-search allowance under Approve for me. In Full Access,-OMB also applies its own configuration tools without another approval.+explicit grant: Full Access, a saved exact command or MCP read-shaped tool,+the narrow built-in web-search allowance under Approve for me, or a bot reading+its own files. In Full Access, OMB also applies its own configuration tools+without another approval.++**A bot reading its own files never asks**, at any level: its standing+instructions (`SOUL.md`), its skills with every saved revision, its memory and+its conversation folders. That covers a plain reading command (`cat`, `head`,+`tail`, `grep`, `rg`, `sed -n`, `ls`, `wc`, `nl`, `stat`) made of plain words+alone, and Claude's Read, Grep, Glob, LS and NotebookRead, when every path is+inside the bot's own folders once links are followed. Anything else in the+command (a pipe, a redirect, a second command, a variable, a glob) asks as+before, and so does every read in a guest's turn, since a bot's folder holds its+owner's memory. On a Cloud the bot's box also shows it its own `SOUL.md`,+read-only.Every bot and conversation starts at **Full access**, the default T3 Code usestoo: each engine runs in its own most permissive mode, and a real question ordiff --git a/server/auto-approve.test.ts b/server/auto-approve.test.tsindex ac70c92694..e52d982a50 100644--- a/server/auto-approve.test.ts+++ b/server/auto-approve.test.ts@@ -121,6 +121,17 @@ describe("autoVerdict", () => {source: "command-allowlist",});});++ it("answers a bot's plain read of its own files at every level, but never a sandbox widening or a question", () => {+ for (const mode of ["ask", "edits", "auto", "custom"] as const) {+ expect(autoVerdict(mode, "Bash", { ownFilesRead: true }), mode).toEqual({ approve: "approved Bash (its own files)", source: "own-files" });+ }+ expect(autoVerdict("ask", "Read", { ownFilesRead: true })).toEqual({ approve: "approved Read (its own files)", source: "own-files" });+ expect(autoVerdict("ask", "Bash", { ownFilesRead: true, requiresExplicitApproval: true })).toEqual({ approve: null, source: "explicit-approval-block" });+ expect(autoVerdict("ask", "AskUserQuestion", { ownFilesRead: true })).toEqual({ approve: null, source: "no-grant" });+ expect(autoVerdict("full", "Read", { ownFilesRead: true }).source).toBe("full-access");+ expect(autoVerdict("ask", "Bash", { ownFilesRead: false })).toEqual({ approve: null, source: "no-grant" });+ });});describe("approvalModeForOrigin", () => {diff --git a/server/auto-approve.ts b/server/auto-approve.tsindex c4ffd2edea..494979c845 100644--- a/server/auto-approve.ts+++ b/server/auto-approve.ts@@ -1,6 +1,7 @@// Nothing here decides whether an action is safe: each level is the provider's own permission mode passed through, and a// request reaching this process is one the provider left for a person. The app's own grants are Full access, the person's-// exact saved commands and remembered MCP read tools, and Approve for me's web search. A bot's question always reaches a human.+// exact saved commands and remembered MCP read tools, Approve for me's web search, and a bot's plain reads of its own files+// at every level (own-file-reads.ts). A bot's question always reaches a human.import { supportsApprovalMode, type ApprovalMode } from "../shared/approval-mode.ts";import { failedTurnTool, type FailedTurnTool } from "../shared/failed-turn.ts";@@ -76,6 +77,7 @@ export type AutoVerdictSource =| "command-allowlist"| "tool-allowlist"| "web-search"+ | "own-files"| "native-approval"| "explicit-approval-block"| "outbound-guard"@@ -98,6 +100,8 @@ export function autoVerdict(commandAllowed?: boolean;/** Exact provider/server/tool/config match against a person's saved MCP read grant. */toolAllowed?: boolean;+ /** The request only reads the bot's own files: its SOUL.md, skills, memory and conversation folders. */+ ownFilesRead?: boolean;},): AutoVerdict {if (ASKS_A_PERSON.has(bareToolName(tool))) {@@ -109,6 +113,7 @@ export function autoVerdict(if (isOutboundTool(tool)) return { approve: null, source: "outbound-guard" };if (context?.commandAllowed) return { approve: `approved ${tool} (saved command)`, source: "command-allowlist" };if (context?.toolAllowed) return { approve: `approved ${tool} (always allowed)`, source: "tool-allowlist" };+ if (context?.ownFilesRead) return { approve: `approved ${tool} (its own files)`, source: "own-files" };if (mode === "auto" && WEB_SEARCH.has(bareToolName(tool))) {return { approve: `approved ${tool} (web search)`, source: "web-search" };}diff --git a/server/bot-box/plan.test.ts b/server/bot-box/plan.test.tsindex 3cb21edfed..2bcd01c554 100644--- a/server/bot-box/plan.test.ts+++ b/server/bot-box/plan.test.ts@@ -26,6 +26,7 @@ linuxBox("the box plan", () => {const plan = turn();expect(plan.botId).toBe("bot-a");expect(visibleInBox(plan, cwd)).toBe("rw");+ expect(visibleInBox(plan, join(dataDir, "bots", "bot-a", "SOUL.md")), "its own standing instructions, never writable").toBe("ro");expect(visibleInBox(plan, join(dataDir, "workspaces", "bot-a", "MEMORY.md"))).toBe("rw");expect(visibleInBox(plan, join(dataDir, "perm-abc.sock"))).toBe("rw");expect(visibleInBox(plan, "/data/.claude/settings.json")).toBe("rw");@@ -34,7 +35,8 @@ linuxBox("the box plan", () => {expect(visibleInBox(plan, "/app/dist-server/index.js")).toBe("ro");expect(visibleInBox(plan, "/usr/local/bin/claude")).toBe("ro");for (const hidden of ["messages.db", "config.json", "logins.json", "providers/x", "tools/y", "box/egress.sock",- "workspaces/bot-b/MEMORY.md", "task-workspaces/bot-b/thread-9/notes.md", "task-workspaces/bot-a/thread-2/notes.md"]) {+ "workspaces/bot-b/MEMORY.md", "task-workspaces/bot-b/thread-9/notes.md", "task-workspaces/bot-a/thread-2/notes.md",+ "bots/bot-b/SOUL.md", "bots/bot-a/other.json"]) {expect(visibleInBox(plan, join(dataDir, hidden)), hidden).toBe("none");}expect(visibleInBox(plan, "/tmp/other-turn/mcp.json")).toBe("none");diff --git a/server/bot-box/plan.ts b/server/bot-box/plan.tsindex 11f3e08084..7cd260c4b0 100644--- a/server/bot-box/plan.ts+++ b/server/bot-box/plan.ts@@ -10,7 +10,8 @@// sign-ins bound into it, so no other audience's transcripts are there;// - put back inside that empty folder: this turn's working folder, the bot's own folder (workspaces/<bot>) and what the// caller names (the turn's permission socket, a read-only file the command line points at); and, read-only, the-// engines OpenMausBot installed there, whole, since npm's bin links point into the prefix by relative paths;+// bot's own SOUL.md (bots/<bot>/SOUL.md, which it may read but never write) and the engines OpenMausBot installed+// there, whole, since npm's bin links point into the prefix by relative paths;// - a private /proc (its own PID namespace: other turns' processes do not exist for it), /dev, /tmp and /run;// - a network namespace with loopback only. Two loopback ports inside are bridged to unix sockets bound in from outside:// the egress gate (every connection to the internet goes through it) and the harness gate (only /api/internal/@@ -187,7 +188,7 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {mounts.push({ kind: mutate.has("engines-rw") ? "bind" : "ro", source: engines, target: engines, optional: true });}const readOnly = new Set<string>();- for (const path of [...(request.ro ?? []), ...argvPaths(request.args)]) {+ for (const path of [...(request.ro ?? []), ...argvPaths(request.args), ...(botId && ID.test(botId) ? [join(dataDir, "bots", botId, "SOUL.md")] : [])]) {const full = resolve(path);// Code and the system are already there; a file under HOME or /tmp the command line names is put back read-only.if (covered(full) || readOnly.has(full)) continue;diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 0c5237f5bd..c9a2ac3a74 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -54,7 +54,7 @@ import { supportsApprovalMode } from "../../../shared/approval-mode.ts";import { MAX_QUESTION_TEXT, parseAskQuestions, parseChoices, questionAnswersByQuestion } from "../../../shared/ask-question.ts";import { appendNative } from "../native.ts";-import { acpSessionOperationKey, acpShellRequest, answersAlone, permissionLaunchCwd } from "../permission-command.ts";+import { acpSessionOperationKey, acpShellRequest, answersAlone, permissionLaunchCwd } from "../permission-command.ts"; import { acpReadPaths } from "../../own-file-reads.ts";import { openQuestionRequest, questionRequestFor, type AcpQuestionRequest } from "./question-requests.ts";import { commandSummary, toolDetailPreview } from "../../tool-summary.ts";import { acpToolEndEvents } from "./tool-items.ts";@@ -865,7 +865,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>requestType: isQuestion ? "question" : "permission",tool,summary,- ...acpShellRequest(isShellCommand, isQuestion ? undefined : toolCall.rawInput, commandCwd),+ ...acpShellRequest(isShellCommand, isQuestion ? undefined : toolCall.rawInput, commandCwd), ...(!isQuestion && acpReadPaths(toolCall) ? { reads: acpReadPaths(toolCall) } : {}),requiresExplicitApproval: isShellCommand && (toolCall.rawInput?.dangerouslyDisableSandbox === true || toolCall.rawInput?.sandbox_permissions === "require_escalated") || undefined,diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 936f5defe9..99843cc2d1 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -53,7 +53,7 @@ import {import { appendNative } from "./native.ts";import { runKeepWarmPing, type KeepWarmContract } from "./claude-keepwarm.ts";import { BACKGROUND_CALL_TIMEOUT_MS, backgroundCallArgs, spawnBackgroundCall } from "./claude-background.ts";-import { permissionLaunchCwd, shellRequest } from "./permission-command.ts";+import { permissionLaunchCwd, shellRequest } from "./permission-command.ts"; import { readToolPaths } from "../own-file-reads.ts";import { SPAWNED_PROXIES } from "../proxy-paths.ts"; import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";import { extractMcpImages } from "../mcp-tool-images.ts"; import { claudeToolDraft } from "./tool-progress.ts";import {@@ -1305,7 +1305,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {tool: ask.tool,summary: askSummary(ask),// The Bash command, for exact-command grants and for the safety floor.- ...shellRequest(ask.kind === "permission" && ask.tool === "Bash" ? ask.input.command : undefined, commandCwd),+ ...shellRequest(ask.kind === "permission" && ask.tool === "Bash" ? ask.input.command : undefined, commandCwd), ...(ask.kind === "permission" && readToolPaths(ask.tool, ask.input) ? { reads: readToolPaths(ask.tool, ask.input) } : {}),requiresExplicitApproval: ask.kind === "permission" && ask.tool === "Bash" && ask.input.dangerouslyDisableSandbox === true || undefined,nativeReview,allowSession: ask.kind === "permission" && !(controlsHost && typeof ask.tool === "string" && ask.tool.startsWith("mcp__computer")) ? true : undefined,diff --git a/server/index.ts b/server/index.tsindex 11d4a483db..452f4a3436 100644--- a/server/index.ts+++ b/server/index.ts@@ -45,7 +45,7 @@ import { isPendingSignInRequest, normalizeSignInSite, signInFallbackText, signInimport { createRoomTurnLevels } from "./room-turn-level.ts";import { createSignInSettle } from "./host/sign-in-settle.ts";import { RoomMemberLock } from "./room-member-lock.ts";-import { approvalHeldNote, approvalHeldReason, approvalModeForOrigin, autoVerdict, deliverFullAccessApproval, undeliveredApprovalTool } from "./auto-approve.ts";+import { approvalHeldNote, approvalHeldReason, approvalModeForOrigin, autoVerdict, deliverFullAccessApproval, undeliveredApprovalTool } from "./auto-approve.ts"; import { readsOwnFiles } from "./own-file-reads.ts";import { bindSafetyFloor, denyAtSafetyFloor, heldAtSafetyFloor, safetyFloorOn } from "./safety-floor-gate.ts";import { CommandAllowlistStore, commandAllowlistCandidate } from "./command-allowlist.ts";import { providerMcpTool, providerToolAllowKey } from "./provider-tool-allow.ts";@@ -6470,7 +6470,7 @@ bus.subscribe((event: RuntimeEvent) => {const privateImageEvent = event.type === "item.completed" && event.itemType === "assistant_image";if (!privateImageEvent) {// Exact executable input is internal; the bus's persistence redactor does not scrub the live event.- const publicEvent = event.type === "request.opened" ? { ...event, command: undefined, commandLine: undefined } : event;+ const publicEvent = event.type === "request.opened" ? { ...event, command: undefined, commandLine: undefined, reads: undefined } : event;broadcast({ kind: "runtime", event: publicEvent });}const routineRun = privateImageEvent ? null : (routines?.handleRuntimeEvent(event) ?? null);@@ -6616,7 +6616,7 @@ bus.subscribe((event: RuntimeEvent) => {? heldAtSafetyFloor(event, autoVerdict(effectiveApprovalMode, event.tool, {requiresExplicitApproval: event.requiresExplicitApproval,commandAllowed: Boolean(command && commandAllowlist.matches(asker.id, command)),- toolAllowed: Boolean(toolAllowKey && asker.alwaysAllow?.includes(toolAllowKey)),+ toolAllowed: Boolean(toolAllowKey && asker.alwaysAllow?.includes(toolAllowKey)), ownFilesRead: !guestDriven && readsOwnFiles(DATA_DIR, asker.id, event), // never in a guest's turn: the folder holds its owner's memory})): null;// Claude accepts --permission-mode auto for any model but silently starts in Manual where auto is unavailable (Haiku 4.5, Sonnet 4.5, an org that disabled it).diff --git a/server/own-file-reads.e2e.test.ts b/server/own-file-reads.e2e.test.tsnew file mode 100644index 0000000000..684f08d9af--- /dev/null+++ b/server/own-file-reads.e2e.test.ts@@ -0,0 +1,85 @@+// Real isolated server + native Claude permission broker, as command-allowlist.e2e.test.ts drives it: a bot on Ask that+// reads its own files (its SOUL.md, a skill revision, its memory) gets no card at all, while a read of anything else,+// or a command that does more than read, still asks. No real model calls, user profiles or shell commands are used.+import { randomUUID } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { connect, type Socket } from "node:net";+import { join } from "node:path";+import { expect, it } from "vitest";++import { launchVerificationServer } from "../scripts/control-omb.ts";++// The reads asked about are a POSIX shell's commands on POSIX paths.+it.skipIf(process.platform === "win32")("answers a bot's plain reads of its own files at Ask with no card, and still asks for anything else", async () => {+ const fixture = await launchVerificationServer({ FAKE_CLAUDE_MODE: "hang" });+ const { url, dataDir } = fixture.info;+ const sockets: Socket[] = [];+ const api = async (method: string, path: string, body?: unknown, status = 200) => {+ const response = await fetch(url + path, { method, headers: { origin: url, "content-type": "application/json" },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(10_000) });+ const result = await response.json() as any;+ expect(response.status, `${method} ${path}: ${JSON.stringify(result)}`).toBe(status);+ return result;+ };+ const messages = async (thread: string): Promise<any[]> => (await api("GET", `/api/threads/${thread}/messages?limit=100`)).messages;+ const card = async (thread: string, id: string) => (await messages(thread)).find((message) => message.card?.requestId === id)?.card;+ const ask = async (socketPath: string, tool: string, input: Record<string, unknown>) => {+ const socket = connect(socketPath);+ sockets.push(socket);+ await new Promise<void>((resolve, reject) => { socket.once("connect", resolve); socket.once("error", reject); });+ const id = randomUUID();+ let buffer = "";+ const reply = new Promise<any>((resolve, reject) => {+ socket.once("error", reject);+ socket.on("data", (chunk) => {+ buffer += chunk;+ if (buffer.includes("\n")) resolve(JSON.parse(buffer.split("\n")[0]!));+ });+ });+ void reply.catch(() => {});+ socket.write(JSON.stringify({ t: "ask", id, tool, input }) + "\n");+ return { id, reply };+ };+ try {+ const bot = (await api("POST", "/api/bots", { name: "Own files fixture", soul: "Answer plainly.", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } }, 201)).bot;+ await api("PATCH", `/api/bots/${bot.id}`, { approvalMode: "ask" });+ const own = join(dataDir, "workspaces", bot.id);+ const revision = join(own, "skills", ".revisions", "a".repeat(64));+ mkdirSync(revision, { recursive: true });+ writeFileSync(join(revision, "SKILL.md"), "# Morning email\n");+ writeFileSync(join(own, "MEMORY.md"), "notes\n");+ const soul = join(dataDir, "bots", bot.id, "SOUL.md");+ await expect.poll(() => existsSync(soul)).toBe(true);++ const dump = join(dataDir, "fake-claude-dump.json");+ rmSync(dump, { force: true });+ await api("POST", `/api/bots/${bot.id}/messages`, { threadId: bot.threadId, text: "Hold this turn while its reads are asked about." }, 202);+ await expect.poll(() => existsSync(dump), { timeout: 15_000 }).toBe(true);+ const socket = JSON.parse(readFileSync(dump, "utf8")).mcpConfig.mcpServers.ogb.args.at(-1) as string;++ for (const [tool, input] of [+ ["Bash", { command: `cat ${soul}` }],+ ["Bash", { command: `head -n 20 ${join(revision, "SKILL.md")}` }],+ ["Bash", { command: `grep -rn "notes" ${own}` }],+ ["Read", { file_path: soul }],+ ] as const) {+ const asked = await ask(socket, tool, input);+ expect(await asked.reply, `${tool} ${JSON.stringify(input)}`).toMatchObject({ id: asked.id, behavior: "allow" });+ expect(await card(bot.threadId, asked.id)).toBeUndefined();+ }+ await expect.poll(async () => (await api("GET", "/api/decisions")).decisions.filter((row: any) => row.source === "own-files").length).toBe(4);++ for (const [tool, input] of [+ ["Bash", { command: `cat ${join(dataDir, "config.json")}` }],+ ["Bash", { command: `cat ${soul} | sh` }],+ ["Read", { file_path: join(dataDir, "config.json") }],+ ] as const) {+ const asked = await ask(socket, tool, input);+ await expect.poll(async () => Boolean(await card(bot.threadId, asked.id)), { timeout: 10_000 }).toBe(true);+ }+ await api("POST", `/api/bots/${bot.id}/interrupt`, { threadId: bot.threadId });+ } finally {+ for (const socket of sockets) socket.destroy();+ await fixture.close();+ }+}, 120_000);diff --git a/server/own-file-reads.test.ts b/server/own-file-reads.test.tsnew file mode 100644index 0000000000..88a8e9593e--- /dev/null+++ b/server/own-file-reads.test.ts@@ -0,0 +1,107 @@+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { acpReadPaths, ownReadRoots, readOnlyPaths, readToolPaths, readsOwnFiles } from "./own-file-reads.ts";++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++/** A data folder with Iris's own folder, a conversation folder, her SOUL.md and another bot's folder. */+function dataFolder() {+ const data = mkdtempSync(join(tmpdir(), "omb-own-reads-"));+ dirs.push(data);+ const own = join(data, "workspaces", "iris"), conversation = join(data, "task-workspaces", "iris", "t1");+ const revision = join(own, "skills", ".revisions", "a".repeat(64));+ for (const dir of [revision, conversation, join(data, "bots", "iris"), join(data, "workspaces", "paul")]) mkdirSync(dir, { recursive: true });+ writeFileSync(join(revision, "SKILL.md"), "# Skill\n");+ writeFileSync(join(own, "MEMORY.md"), "notes\n");+ writeFileSync(join(data, "bots", "iris", "SOUL.md"), "Be kind.\n");+ writeFileSync(join(data, "bots", "iris", "other.json"), "{}\n");+ writeFileSync(join(data, "workspaces", "paul", "MEMORY.md"), "paul's\n");+ writeFileSync(join(data, "config.json"), "{}\n");+ return { data, own, conversation, revision };+}++describe("the shell commands that only read", () => {+ it("reads the paths of a plain reader with its plain flags", () => {+ expect(readOnlyPaths("cat SOUL.md")).toEqual(["SOUL.md"]);+ expect(readOnlyPaths("cat -n /a/b.md '/c d/e.md'")).toEqual(["/a/b.md", "/c d/e.md"]);+ expect(readOnlyPaths("head -n 20 /a/SKILL.md")).toEqual(["/a/SKILL.md"]);+ expect(readOnlyPaths("tail -5 notes.md")).toEqual(["notes.md"]);+ expect(readOnlyPaths("grep -rn \"standing rules\" skills")).toEqual(["skills"]);+ expect(readOnlyPaths("rg -n -g '*.md' rules skills")).toEqual(["skills"]);+ expect(readOnlyPaths("sed -n '1,40p' SKILL.md")).toEqual(["SKILL.md"]);+ expect(readOnlyPaths("ls -la skills/.revisions")).toEqual(["skills/.revisions"]);+ expect(readOnlyPaths("wc -l -- -odd-name.md")).toEqual(["-odd-name.md"]);+ });++ it("is nothing for anything else a command line could do", () => {+ for (const command of [+ "cat a.md | sh", "cat a.md > b.md", "cat a.md; rm -rf b", "cat a.md && curl x", "cat $(echo a.md)", "cat `x`", "cat $HOME/a",+ "cat *.md", "cat a?.md", "cat a.md\nrm b.md", "FOO=1 cat a.md", "cat", "cat -", "tail -f a.md", "grep -R x .", "rg -L x .",+ "rg --pre sh x .", "sed -i 's/a/b/' a.md", "sed -n '1w out' a.md", "grep -f patterns a.md", "rm a.md", "python3 -c 'print(1)'",+ "cat \"$(id)\"", "cat 'unclosed", "ls", "cat 'a'b", "cat a.md\tb\t|\tsh",+ "cat ~/a.md", "cat ~root/.ssh/id_rsa", "cat ~-/a.md", "cat ~+/a.md", "cat a.md ~1/b.md", "cat foo=~/x", "cat a=b:~/x", "cat =ls",+ ]) expect(readOnlyPaths(command), command).toBeNull();+ expect(readOnlyPaths("cat 'foo=~/x' \"=ls\""), "quoted, neither shell expands them").toEqual(["foo=~/x", "=ls"]);+ });+});++describe("the read tools' paths", () => {+ it("takes Claude's read tools' own path, and no search that could reach past it", () => {+ expect(readToolPaths("Read", { file_path: "/data/bots/iris/SOUL.md" })).toEqual(["/data/bots/iris/SOUL.md"]);+ expect(readToolPaths("Grep", { pattern: "rules", path: "/data/workspaces/iris" })).toEqual(["/data/workspaces/iris"]);+ expect(readToolPaths("Glob", { pattern: "**/*.md", path: "/data/workspaces/iris" })).toEqual(["/data/workspaces/iris"]);+ expect(readToolPaths("Glob", { pattern: "../paul/**", path: "/data/workspaces/iris" })).toBeUndefined();+ expect(readToolPaths("Glob", { pattern: "/data/**", path: "/data/workspaces/iris" })).toBeUndefined();+ expect(readToolPaths("Grep", { pattern: "rules" }), "no path: the working folder, which never asks").toBeUndefined();+ expect(readToolPaths("Read", { file_path: "SOUL.md" })).toBeUndefined();+ expect(readToolPaths("Write", { file_path: "/data/workspaces/iris/x.md" })).toBeUndefined();+ expect(acpReadPaths({ kind: "read", locations: [{ path: "/data/workspaces/iris/MEMORY.md" }], rawInput: { filePath: "/data/workspaces/iris/MEMORY.md" } }))+ .toEqual(["/data/workspaces/iris/MEMORY.md"]);+ expect(acpReadPaths({ kind: "edit", locations: [{ path: "/data/workspaces/iris/MEMORY.md" }] })).toBeUndefined();+ expect(acpReadPaths({ kind: "read", rawInput: { filePath: "MEMORY.md" } })).toBeUndefined();+ });+});++// The reading commands are a POSIX shell's, with POSIX paths; a read tool's own paths count on every platform.+const posix = it.skipIf(process.platform === "win32");++describe("a bot's own files", () => {+ it("count a read tool's own paths inside them, and nothing outside, on every platform", () => {+ const { data, own } = dataFolder();+ expect(readsOwnFiles(data, "iris", { reads: [join(own, "MEMORY.md")] })).toBe(true);+ expect(readsOwnFiles(data, "iris", { reads: [join(data, "bots", "iris", "SOUL.md")] })).toBe(true);+ expect(readsOwnFiles(data, "iris", { reads: [join(data, "config.json")] })).toBe(false);+ expect(readsOwnFiles(data, "paul", { reads: [join(own, "MEMORY.md")] })).toBe(false);+ });++ posix("are its folder, its conversation folders and its SOUL.md, and nothing else of the data folder", () => {+ const { data, own, conversation, revision } = dataFolder();+ const command = (line: string, cwd = conversation) => readsOwnFiles(data, "iris", { command: { command: line, cwd } });+ expect(command(`cat ${join(data, "bots", "iris", "SOUL.md")}`)).toBe(true);+ expect(command(`cat ${join(revision, "SKILL.md")}`)).toBe(true);+ expect(command("cat MEMORY.md", own)).toBe(true);+ expect(command(`grep -rn notes ${own}`)).toBe(true);+ expect(readsOwnFiles(data, "iris", { reads: [join(data, "bots", "iris", "SOUL.md")] })).toBe(true);+ expect(command(`cat ${join(data, "bots", "iris", "other.json")}`), "only SOUL.md of the bot's record folder").toBe(false);+ expect(command(`cat ${join(data, "workspaces", "paul", "MEMORY.md")}`), "another bot's").toBe(false);+ expect(command(`cat ${join(data, "config.json")}`)).toBe(false);+ expect(command(`cat ${join(own, "missing.md")}`), "only files that exist").toBe(false);+ expect(command(`cat ${join(own, "MEMORY.md")} ${join(data, "config.json")}`), "every path").toBe(false);+ expect(readsOwnFiles(data, "paul", { command: { command: `cat ${join(own, "MEMORY.md")}`, cwd: conversation } }), "Iris's files are not Paul's").toBe(false);+ expect(readsOwnFiles(data, "../iris", { reads: [join(own, "MEMORY.md")] })).toBe(false);+ expect(ownReadRoots(data, "iris")).toHaveLength(3);+ });++ posix("follow every link before they count", () => {+ const { data, own, conversation } = dataFolder();+ symlinkSync(join(data, "config.json"), join(own, "config-link.json"));+ symlinkSync(join(data, "workspaces", "paul"), join(conversation, "paul"));+ expect(readsOwnFiles(data, "iris", { command: { command: "cat config-link.json", cwd: own } })).toBe(false);+ expect(readsOwnFiles(data, "iris", { command: { command: "cat paul/MEMORY.md", cwd: conversation } })).toBe(false);+ expect(readsOwnFiles(data, "iris", { reads: [join(conversation, "paul", "MEMORY.md")] })).toBe(false);+ });+});diff --git a/server/own-file-reads.ts b/server/own-file-reads.tsnew file mode 100644index 0000000000..a3a00a428a--- /dev/null+++ b/server/own-file-reads.ts@@ -0,0 +1,121 @@+// A bot reading its own files never needs the person: its standing instructions (SOUL.md), its skills with every+// revision, its memory and its conversation folders are its own, and an unattended run that waits for an approval to+// read them only stalls. Only plain reads count: one of the reading commands below made of plain words alone, or a read+// tool's own paths, with every path inside the bot's own folders once every link is followed.+import { realpathSync } from "node:fs";+import { isAbsolute, join, relative, resolve } from "node:path";++/** Commands that only read the files they name, with the flags that keep them that way: none that follows links out+ * (grep -R, rg -L), runs a program (rg --pre), follows a file forever (tail -f) or writes (sed -i). */+const READERS: Record<string, { flags: RegExp; valued?: RegExp; pattern?: boolean; script?: RegExp }> = {+ cat: { flags: /^-[nbsvAET]+$/ },+ head: { flags: /^-(?:[nqv]+|\d+)$/, valued: /^-[nc]$/ },+ tail: { flags: /^-(?:[nqv]+|\d+)$/, valued: /^-[nc]$/ },+ wc: { flags: /^-[lwcmL]+$/ },+ ls: { flags: /^-[laAhRt1SrdFpG]+$/ },+ nl: { flags: /^-[ba]+$/ },+ stat: { flags: /^-L$/ },+ grep: { flags: /^-(?:[nilcrvwxHhEFsoq]+|-color=never)$/, valued: /^-[ABCm]$/, pattern: true },+ rg: { flags: /^-(?:[nilcvwxHhFsS]+|-no-heading|-color=never)$/, valued: /^-[ABCmg]$/, pattern: true },+ sed: { flags: /^-n$/, script: /^(?:\d+|\$)(?:,(?:\d+|\$))?p$/ },+};++/** One plain word: letters, digits and the punctuation of paths and numbers, or a whole quoted string the shell expands+ * nothing in, each ending at a space or the end. No glob, variable, substitution, redirection, pipe or second command can+ * be one. */+const WORD = /[ \t]*(?:'([^']*)'|"([^"$`\\!]*)"|([\w./~+@%:,=-]+))(?=[ \t]|$)/y;++function words(command: string): string[] | null {+ if (/[\0\r\n]/.test(command)) return null;+ const text = command.trim(), out: string[] = [];+ for (let index = 0; index < text.length;) {+ WORD.lastIndex = index;+ const found = WORD.exec(text);+ if (!found) return null;+ // A bare word with a ~ anywhere (bash expands one after an =, as in foo=~/x) or starting with = (zsh's =cmd) is the+ // shell's to expand, to a home, the folder it was in before or a command's own path, none of which is checked here.+ if (found[3] !== undefined && (found[3].includes("~") || found[3].startsWith("="))) return null;+ out.push(found[1] ?? found[2] ?? found[3]!);+ index = WORD.lastIndex;+ }+ return out.length ? out : null;+}++/** The paths a shell command reads when it is one of the plain readers, or null when it might do anything else. */+export function readOnlyPaths(command: string): string[] | null {+ const parts = words(command);+ if (!parts) return null;+ const [name, ...rest] = parts;+ const reader = READERS[name!];+ if (!reader) return null;+ const paths: string[] = [];+ let patternTaken = !reader.pattern, scriptTaken = !reader.script, endOfFlags = false;+ for (let index = 0; index < rest.length; index++) {+ const word = rest[index]!;+ if (!endOfFlags && word === "--") { endOfFlags = true; continue; }+ if (!endOfFlags && word.startsWith("-") && word !== "-") {+ if (reader.valued?.test(word)) { if (++index >= rest.length) return null; continue; }+ if (!reader.flags.test(word)) return null;+ continue;+ }+ if (!scriptTaken) { if (!reader.script!.test(word)) return null; scriptTaken = true; continue; }+ if (!patternTaken) { patternTaken = true; continue; }+ if (word === "-") return null;+ paths.push(word);+ }+ return scriptTaken && patternTaken && paths.length ? paths : null;+}++/** The files a read tool's ask names (Claude's Read, Grep, Glob, LS, NotebookRead), or undefined for any other tool or+ * a search that could reach past the path it names. */+export function readToolPaths(tool: unknown, input: unknown): string[] | undefined {+ if (typeof tool !== "string" || !input || typeof input !== "object" || Array.isArray(input)) return undefined;+ const fields = input as Record<string, unknown>;+ const path = tool === "Read" ? fields.file_path : tool === "NotebookRead" ? fields.notebook_path+ : tool === "Grep" || tool === "LS" ? fields.path+ : tool === "Glob" && typeof fields.pattern === "string" && !fields.pattern.split(/[\\/]/).includes("..") && !isAbsolute(fields.pattern) ? fields.path+ : undefined;+ return typeof path === "string" && isAbsolute(path) ? [path] : undefined;+}++/** The files an ACP read call names: its locations and the usual path fields of its input. */+export function acpReadPaths(toolCall: { kind?: unknown; locations?: unknown; rawInput?: unknown }): string[] | undefined {+ if (toolCall.kind !== "read") return undefined;+ const input = toolCall.rawInput && typeof toolCall.rawInput === "object" && !Array.isArray(toolCall.rawInput) ? toolCall.rawInput as Record<string, unknown> : {};+ const located = Array.isArray(toolCall.locations) ? toolCall.locations.map((location) => (location as { path?: unknown })?.path) : [];+ const paths = [...located, input.filePath, input.file_path, input.path].filter((path): path is string => typeof path === "string");+ return paths.length && paths.every((path) => isAbsolute(path)) ? [...new Set(paths)] : undefined;+}++const inside = (path: string, root: string) => {+ const rel = relative(root, path);+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));+};++function real(path: string): string | null {+ try { return realpathSync(path); } catch { return null; }+}++/** The bot's own folders and files, as they are on disk: its folder, its conversation folders and its SOUL.md. */+export function ownReadRoots(dataDir: string, botId: string): string[] {+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(botId)) return [];+ return [join(dataDir, "workspaces", botId), join(dataDir, "task-workspaces", botId), join(dataDir, "bots", botId, "SOUL.md")]+ .flatMap((root) => real(root) ?? []);+}++/** Every path exists and is inside one of `roots` once its links are followed. */+export function readsOnly(paths: readonly string[], cwd: string, roots: readonly string[]): boolean {+ if (!paths.length || !roots.length) return false;+ return paths.every((path) => {+ const full = real(resolve(cwd, path));+ return full !== null && roots.some((root) => inside(full, root));+ });+}++/** Whether this ask only reads the bot's own files: a plain reading command in its shell, or a read tool's paths. */+export function readsOwnFiles(dataDir: string, botId: string, ask: { command?: { command: string; cwd: string }; reads?: readonly string[] }): boolean {+ const roots = ownReadRoots(dataDir, botId);+ if (ask.reads?.length) return readsOnly(ask.reads, "/", roots);+ const paths = ask.command ? readOnlyPaths(ask.command.command) : null;+ return Boolean(paths && ask.command && readsOnly(paths, ask.command.cwd, roots));+}diff --git a/shared/runtime-events.ts b/shared/runtime-events.tsindex 4024eeb19f..baf32225ea 100644--- a/shared/runtime-events.ts+++ b/shared/runtime-events.ts@@ -134,6 +134,9 @@ export type RuntimeEvent = RuntimeEventBase &/** The shell command line exactly as the engine sent it, even when `command` is absent for want of a cwd.* Read only by the safety floor; no grant is ever made from it, and like `command` it is never broadcast. */commandLine?: string;+ /** The files a read tool's ask reads (absolute): a request that reads only the bot's own files is answered+ * without the person. Like `command`, never broadcast. */+ reads?: string[];choices?: string[];/** A provider's structured ask (Claude's AskUserQuestion): the whole* set of questions, each with its own options, so the card can offer