Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(bots): relative paths can't escape a bot's folders

Salman Qureshia95d4d887506
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index 63e69997..4e7b0244 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -10,7 +10,7 @@ import type { TokenBudget } from '../utils/tokens.js';
import type { CapabilityRegistry } from '../capabilities/registry.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
import { UserMemoryStore as UserMemoryStoreImpl } from '../memory/user-memory.js';
-import { BotStore, deliverableFileName, BOT_JOURNAL_FILENAME, BOT_PERMISSIONS_FILENAME, isValidCronExpression } from './store.js';
+import { BotStore, deliverableFileName, BOT_JOURNAL_FILENAME, BOT_PERMISSIONS_FILENAME, isValidCronExpression, BOT_SHARED_SANDBOX_DIRNAME } from './store.js';
import { BotJournal, type BotTranscript, type BotUsage } from './journal.js';
import { BotQueue, idempotencyKeyFor, LEASE_SECONDS, type DurableBotJob } from './queue.js';
import { sweepSharedSandbox } from './retention.js';
@@ -32,6 +32,7 @@ import { mergePathScopes } from './registry-factory.js';
import { synthesizeSkill, MIN_TOOLS_FOR_SYNTHESIS } from './skill-synthesis.js';
import { SkillLoader } from '../skills/loader.js';
import { logger } from '../utils/logger.js';
+import { resolveToolPath, type CwdSource } from '../capabilities/filesystem/resolve-path.js';
import type {
BotLiveState,
BotManifest,
@@ -1933,7 +1934,13 @@ export class BotManager {
const options = typeof opts === 'string' ? { saveAs: opts } : opts;
const manifest = this.store.get(botId);
if (!manifest) return { accepted: false, reasonCode: 'target_unknown' };
- const candidate = resolve(filePath.replace(/^~(?=$|\/|\\)/, homedir()));
+ // Relative paths are relative to the bot's sandbox (with "_shared/…"
+ // meaning the fleet folder), never to wherever the daemon was started.
+ const sandbox = this.store.sandboxDir(botId);
+ const getCwd: CwdSource = Object.assign(() => sandbox, {
+ roots: () => [['sandbox', sandbox], [BOT_SHARED_SANDBOX_DIRNAME, this.store.sharedSandboxDir()]] as const,
+ });
+ const candidate = resolveToolPath(filePath.replace(/^~(?=$|\/|\\)/, homedir()), getCwd);
const allowedBases = [this.store.sharedSandboxDir(), this.store.sandboxDir(botId)];
const inside = allowedBases.some((base) => {
const rel = relative(resolve(base), candidate);
diff --git a/src/bots/path-confinement.test.ts b/src/bots/path-confinement.test.ts
new file mode 100644
index 00000000..207bdcaa
--- /dev/null
+++ b/src/bots/path-confinement.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { Tool } from 'ai';
+import { BotStore } from './store.js';
+import { createBotCapabilityRegistry } from './registry-factory.js';
+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';
+import type { BotManifest, BotPermissionsFile } from './types.js';
+
+/**
+ * Regression: a bot with a wide grant ("~") whose cwd was a code checkout
+ * wrote its "_shared/…" files into that repo (mercury-agent, 10 Oct 2026).
+ */
+let root: string;
+let store: BotStore;
+let repo: string;
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-paths-'));
+ store = new BotStore(join(root, 'bots'));
+ repo = join(root, 'some-repo');
+ mkdirSync(repo, { recursive: true });
+});
+afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+function buildRegistry(id: string) {
+ const manifest = store.create({ id, name: id }) as BotManifest;
+ const permissions: BotPermissionsFile = {
+ ...store.ensurePermissions(id),
+ // Wide grant, like the real article-writer: read/write everywhere under root.
+ paths: [{ scope: root, read: true, write: true, execute: true }],
+ };
+ return createBotCapabilityRegistry({
+ botId: id,
+ manifest,
+ botDir: store.botDir(id),
+ permissions,
+ userMemory: null,
+ config: getDefaultConfig() as MercuryConfig,
+ sandbox: { workspace: store.sandboxDir(id), shared: store.sharedSandboxDir() },
+ });
+}
+
+async function run(tools: Record<string, Tool>, name: string, args: Record<string, unknown>): Promise<string> {
+ const t = tools[name] as Tool & { execute: (a: unknown, o: unknown) => Promise<string> };
+ return t.execute(args, { toolCallId: 't', messages: [] });
+}
+
+describe('bot relative paths stay in the bot\'s own folders', () => {
+ it('"_shared/…" lands in the fleet-shared folder, even after cd into a repo', async () => {
+ const registry = buildRegistry('writer');
+ const tools = registry.getTools();
+ // cd into the repo is refused (outside the bot's own folders)…
+ expect(await run(tools, 'cd', { path: repo })).toMatch(/only change directory inside your own work folders/);
+ expect(registry.getCwd()).toBe(store.sandboxDir('writer'));
+ // …and even if the cwd were the repo, "_shared/" means the fleet folder.
+ (registry as unknown as { currentCwd: string }).currentCwd = repo;
+ await run(tools, 'create_file', { path: '_shared/report.md', content: 'hello' });
+ expect(existsSync(join(repo, '_shared'))).toBe(false);
+ expect(readFileSync(join(store.sharedSandboxDir(), 'report.md'), 'utf8')).toBe('hello');
+ });
+
+ it('"sandbox/…" and plain relative paths land in the private workspace', async () => {
+ const registry = buildRegistry('scout');
+ const tools = registry.getTools();
+ await run(tools, 'create_file', { path: 'sandbox/a.md', content: 'a' });
+ await run(tools, 'create_file', { path: 'b.md', content: 'b' });
+ expect(readFileSync(join(store.sandboxDir('scout'), 'a.md'), 'utf8')).toBe('a');
+ expect(readFileSync(join(store.sandboxDir('scout'), 'b.md'), 'utf8')).toBe('b');
+ });
+
+ it('cd within its own folders still works, and absolute paths under a grant still work', async () => {
+ const registry = buildRegistry('editor');
+ const tools = registry.getTools();
+ expect(await run(tools, 'cd', { path: store.sharedSandboxDir() })).toMatch(/^Changed directory/);
+ writeFileSync(join(repo, 'notes.md'), 'x');
+ expect(await run(tools, 'read_file', { path: join(repo, 'notes.md') })).toContain('x');
+ });
+});
diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.ts
index 02c8841b..fbbab191 100644
--- a/src/bots/registry-factory.ts
+++ b/src/bots/registry-factory.ts
@@ -1,6 +1,6 @@
import { homedir } from 'node:os';
import { mkdirSync } from 'node:fs';
-import { resolve } from 'node:path';
+import { isAbsolute, relative, resolve } from 'node:path';
import { CapabilityRegistry } from '../capabilities/registry.js';
import type { SkillLoader } from '../skills/loader.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
@@ -120,7 +120,17 @@ export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRe
// Relative paths and shell commands resolve inside the bot's workspace,
// never the daemon's cwd (a bot with a wide grant wrote "sandbox/…" files
// into whatever repo the daemon happened to be started from).
- registry.setCwd(deps.sandbox?.workspace ?? process.cwd());
+ const workspace = deps.sandbox?.workspace ?? deps.botDir;
+ registry.setCwd(workspace);
+ // "_shared/…" and "sandbox/…" (the names a bot's instructions use) always
+ // mean its real folders, whatever its cwd. And a bot can only move its cwd
+ // within its own folders: with a wide grant (e.g. "~"), a cwd inside a code
+ // checkout turned every relative write into a write to that repo.
+ const roots: Array<readonly [string, string]> = [['sandbox', workspace]];
+ if (deps.sandbox) roots.push([BOT_SHARED_SANDBOX_DIRNAME, deps.sandbox.shared]);
+ registry.setPathRoots(roots);
+ const ownDirs = [workspace, deps.botDir, ...(deps.sandbox ? [deps.sandbox.shared] : [])].map((d) => resolve(d));
+ registry.setCwdGuard((dir) => ownDirs.some((base) => isWithin(base, resolve(dir))));
registry.registerAll();
const tools = filterBotTools(registry.getTools(), deps.manifest, deps.permissions);
@@ -210,4 +220,9 @@ function buildBotScopes(paths: BotPathScope[] | undefined, botDir: string): Arra
scopes.push({ path: resolved, read: p.read ?? false, write: p.write ?? false, execute: p.execute || undefined });
}
return scopes;
-}
\ No newline at end of file
+}
+
+function isWithin(base: string, target: string): boolean {
+ const rel = relative(base, target);
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
+}
diff --git a/src/capabilities/filesystem/approve-scope.ts b/src/capabilities/filesystem/approve-scope.ts
index 2e390cba..b45995f5 100644
--- a/src/capabilities/filesystem/approve-scope.ts
+++ b/src/capabilities/filesystem/approve-scope.ts
@@ -1,9 +1,10 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
-import { resolve, isAbsolute } from 'node:path';
+import { resolve } from 'node:path';
import type { PermissionManager } from '../permissions.js';
+import { resolveToolPath, type CwdSource } from './resolve-path.js';
-export function createApproveScopeTool(permissions: PermissionManager, getCwd: () => string) {
+export function createApproveScopeTool(permissions: PermissionManager, getCwd: CwdSource) {
return tool({
description: 'Request user approval to access a directory outside current scopes. Use this when a file tool returns a permission denied error. The user gets an approval prompt (Allow/Always/Deny buttons on Telegram, yes/always/no on CLI). "Allow" grants session-only access. "Always" persists to disk. After approval, retry the original file operation.',
inputSchema: zodSchema(z.object({
@@ -11,7 +12,7 @@ export function createApproveScopeTool(permissions: PermissionManager, getCwd: (
mode: z.enum(['read', 'write']).describe('The access mode needed'),
})),
execute: async ({ path, mode }) => {
- const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
+ const resolved = resolveToolPath(path, getCwd);
const result = await permissions.requestScopeExternal(resolved, mode);
if (result.allowed) {
return `Access approved for ${mode} access to ${resolved}. You can now retry the file operation.`;
diff --git a/src/capabilities/filesystem/create-file.ts b/src/capabilities/filesystem/create-file.ts
index 3b8200c6..1b1a8a6b 100644
--- a/src/capabilities/filesystem/create-file.ts
+++ b/src/capabilities/filesystem/create-file.ts
@@ -1,10 +1,11 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { existsSync, writeFileSync, mkdirSync } from 'node:fs';
-import { resolve, dirname, isAbsolute } from 'node:path';
+import { resolve, dirname } from 'node:path';
import type { PermissionManager } from '../permissions.js';
+import { resolveToolPath, type CwdSource } from './resolve-path.js';
-export function createCreateFileTool(permissions: PermissionManager, getCwd: () => string) {
+export function createCreateFileTool(permissions: PermissionManager, getCwd: CwdSource) {
return tool({
description: 'Create a new file with the given content. Also creates parent directories if needed. The path must be within a writable scope.',
inputSchema: zodSchema(z.object({
@@ -12,7 +13,7 @@ export function createCreateFileTool(permissions: PermissionManager, getCwd: ()
content: z.string().describe('The content of the new file'),
})),
execute: async ({ path, content }) => {
- const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
+ const resolved = resolveToolPath(path, getCwd);
const check = await permissions.checkFsAccess(resolved, 'write');
if (!check.allowed) {
const parentDir = resolve(resolved, '..');
diff --git a/src/capabilities/filesystem/delete-file.ts b/src/capabilities/filesystem/delete-file.ts
index d89f3c4d..eef9ebf6 100644
--- a/src/capabilities/filesystem/delete-file.ts
+++ b/src/capabilities/filesystem/delete-file.ts
@@ -1,17 +1,18 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { existsSync, unlinkSync } from 'node:fs';
-import { resolve, isAbsolute } from 'node:path';
+import { resolve } from 'node:path';
import type { PermissionManager } from '../permissions.js';
+import { resolveToolPath, type CwdSource } from './resolve-path.js';
-export function createDeleteFileTool(permissions: PermissionManager, getCwd: () => string) {
+export function createDeleteFileTool(permissions: PermissionManager, getCwd: CwdSource) {
return tool({
description: 'Delete a file. This action cannot be undone. The path must be within a writable scope. Always asks for confirmation.',
inputSchema: zodSchema(z.object({
path: z.string().describe('Absolute or relative path to the file to delete'),
})),
execute: async ({ path }) => {
- const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
+ const resolved = resolveToolPath(path, getCwd);
const check = await permissions.checkFsAccess(resolved, 'write');
if (!check.allowed) {
const parentDir = resolve(resolved, '..');
diff --git a/src/capabilities/filesystem/edit-file.ts b/src/capabilities/filesystem/edit-file.ts
index d0608e3d..6717cb12 100644
--- a/src/capabilities/filesystem/edit-file.ts
+++ b/src/capabilities/filesystem/edit-file.ts
@@ -1,10 +1,11 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { readFileSync, writeFileSync } from 'node:fs';
-import { resolve, isAbsolute } from 'node:path';
+import { resolve } from 'node:path';
import type { PermissionManager } from '../permissions.js';
+import { resolveToolPath, type CwdSource } from './resolve-path.js';
-export function createEditFileTool(permissions: PermissionManager, getCwd: () => string) {
+export function createEditFileTool(permissions: PermissionManager, getCwd: CwdSource) {
return tool({
description: 'Edit a file by replacing an exact string match with new content. Use this instead of write_file when you only need to change part of a file. The old_string must match exactly (including whitespace and indentation). Fails if old_string is not found or found multiple times.',
inputSchema: zodSchema(z.object({
@@ -13,7 +14,7 @@ export function createEditFileTool(permissions: PermissionManager, getCwd: () =>
new_string: z.string().describe('The text to replace it with'),
})),
execute: async ({ path, old_string, new_string }) => {
- const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
+ const resolved = resolveToolPath(path, getCwd);
const fsCheck = await permissions.checkFsAccess(resolved, 'write');
if (!fsCheck.allowed) {
diff --git a/src/capabilities/filesystem/list-dir.ts b/src/capabilities/filesystem/list-dir.ts
index d3acc8db..111dd306 100644
--- a/src/capabilities/filesystem/list-dir.ts
+++ b/src/capabilities/filesystem/list-dir.ts
@@ -1,18 +1,19 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { existsSync, readdirSync, statSync } from 'node:fs';
-import { resolve, isAbsolute, join } from 'node:path';
+import { resolve, join } from 'node:path';
import type { PermissionManager } from '../permissions.js';
import { readDenialMessage } from './verified-read.js';
+import { resolveToolPath, type CwdSource } from './resolve-path.js';
-export function createListDirTool(permissions: PermissionManager, getCwd: () => string) {
+export function createListDirTool(permissions: PermissionManager, getCwd: CwdSource) {
return tool({
description: 'List the contents of a directory. Shows file names, types, and sizes.',
inputSchema: zodSchema(z.object({
path: z.string().describe('Absolute or relative path to the directory'),
})),
execute: async ({ path }) => {
- const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
+ const resolved = resolveToolPath(path, getCwd);
const check = await permissions.checkFsAccess(resolved, 'read');
if (!check.allowed) {
if (check.code === undefined || check.code === 'denied') {
diff --git a/src/capabilities/filesystem/read-file.ts b/src/capabilities/filesystem/read-file.ts
index 1d4b3a35..e3a66773 100644
--- a/src/capabilities/filesystem/read-file.ts
+++ b/src/capabilities/filesystem/read-file.ts
@@ -1,9 +1,10 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { readFileSync, closeSync } from 'node:fs';
-import { resolve, isAbsolute } from 'node:path';
+import { resolve } from 'node:path';
import type { PermissionManager } from '../permissions.js';
import { openVerified, readDenialMessage } from './verified-read.js';
+import { resolveToolPath, type CwdSource } from './resolve-path.js';
/** Cap on tool-result size — the full file text is echoed into the LLM
* conversation and retained for every subsequent agent step (the AI SDK
@@ -11,14 +12,14 @@ import { openVerified, readDenialMessage } from './verified-read.js';
* keeping a 75-step task's retained heap in the low tens of MB. */
const MAX_RESULT_CHARS = 64 * 1024;
-export function createReadFileTool(permissions: PermissionManager, getCwd: () => string) {
+export function createReadFileTool(permissions: PermissionManager, getCwd: CwdSource) {
return tool({
description: 'Read the contents of a file. The path must be within an allowed scope. Files larger than 64KB are returned truncated — read specific ranges with run_command if you need more.',
inputSchema: zodSchema(z.object({
path: z.string().describe('Absolute or relative path to the file'),
})),
execute: async ({ path }) => {
- const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
+ const resolved = resolveToolPath(path, getCwd);
const check = await permissions.checkFsAccess(resolved, 'read');
if (!check.allowed) {
return readDenialMessage(resolved, check);
diff --git a/src/capabilities/filesystem/resolve-path.ts b/src/capabilities/filesystem/resolve-path.ts
new file mode 100644
index 00000000..8f6f0ebd
--- /dev/null
+++ b/src/capabilities/filesystem/resolve-path.ts
@@ -0,0 +1,22 @@
+import { isAbsolute, resolve } from 'node:path';
+
+/**
+ * Where a tool's relative paths resolve. A plain `() => cwd` works; a
+ * registry can also attach named roots so that, e.g., a bot's
+ * "_shared/report.md" always means the fleet-shared folder, whatever
+ * directory the bot is in. Without that, a bot whose cwd was a code
+ * checkout wrote its "_shared/…" files into the repo.
+ */
+export type CwdSource = (() => string) & {
+ roots?: () => ReadonlyArray<readonly [prefix: string, dir: string]>;
+};
+
+export function resolveToolPath(path: string, getCwd: CwdSource): string {
+ if (isAbsolute(path)) return resolve(path);
+ const normalized = path.replace(/\\/g, '/').replace(/^(\.\/)+/, '');
+ for (const [prefix, dir] of getCwd.roots?.() ?? []) {
+ if (normalized === prefix) return resolve(dir);
+ if (normalized.startsWith(`${prefix}/`)) return resolve(dir, normalized.slice(prefix.length + 1));
+ }
+ return resolve(getCwd(), path);
+}
diff --git a/src/capabilities/filesystem/send-file.ts b/src/capabilities/filesystem/send-file.ts
index f63c9afd..bcd48847 100644
--- a/src/capabilities/filesystem/send-file.ts
+++ b/src/capabilities/filesystem/send-file.ts
@@ -1,13 +1,14 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { existsSync, statSync } from 'node:fs';
-import { resolve, basename, isAbsolute } from 'node:path';
+import { resolve, basename } from 'node:path';
import type { PermissionManager } from '../permissions.js';
import { readDenialMessage } from './verified-read.js';
+import { resolveToolPath, type CwdSource } from './resolve-path.js';
export function createSendFileTool(
permissions: PermissionManager,
- getCwd: () => string,
+ getCwd: CwdSource,
sendFile: (filePath: string, channel?: string) => Promise<void>,
) {
return tool({
@@ -18,7 +19,7 @@ export function createSendFileTool(
channel: z.enum(['signal', 'telegram']).optional().describe('The channel to send the file via. Use this when the user explicitly requests a specific channel, e.g. "send via Signal" or "send to Telegram".'),
})),
execute: async ({ path, channel }) => {
- const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
+ const resolved = resolveToolPath(path, getCwd);
const check = await permissions.checkFsAccess(resolved, 'read');
if (!check.allowed) {
return readDenialMessage(resolved, check);
diff --git a/src/capabilities/filesystem/write-file.ts b/src/capabilities/filesystem/write-file.ts
index fd799237..ed1d2b68 100644
--- a/src/capabilities/filesystem/write-file.ts
+++ b/src/capabilities/filesystem/write-file.ts
@@ -1,11 +1,12 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { existsSync, writeFileSync, readFileSync } from 'node:fs';
-import { resolve, dirname, isAbsolute } from 'node:path';
+import { resolve, dirname } from 'node:path';
import { mkdirSync } from 'node:fs';
import type { PermissionManager } from '../permissions.js';
+import { resolveToolPath, type CwdSource } from './resolve-path.js';
-export function createWriteFileTool(permissions: PermissionManager, getCwd: () => string) {
+export function createWriteFileTool(permissions: PermissionManager, getCwd: CwdSource) {
return tool({
description: 'Write content to an existing file. The path must be within a writable scope.',
inputSchema: zodSchema(z.object({
@@ -13,7 +14,7 @@ export function createWriteFileTool(permissions: PermissionManager, getCwd: () =
content: z.string().describe('The content to write to the file'),
})),
execute: async ({ path, content }) => {
- const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
+ const resolved = resolveToolPath(path, getCwd);
const check = await permissions.checkFsAccess(resolved, 'write');
if (!check.allowed) {
const parentDir = resolve(resolved, '..');
diff --git a/src/capabilities/git/git-path.ts b/src/capabilities/git/git-path.ts
index dab69b60..e83841da 100644
--- a/src/capabilities/git/git-path.ts
+++ b/src/capabilities/git/git-path.ts
@@ -1,8 +1,9 @@
-import { resolve, isAbsolute } from 'node:path';
+import { resolve } from 'node:path';
import { execFile } from 'node:child_process';
import type { PermissionManager } from '../permissions.js';
import { readDenialMessage } from '../filesystem/verified-read.js';
import { pinnedBinary, pinnedSearchDirs, minimalEnv } from '../shell/argv-lane.js';
+import { resolveToolPath, type CwdSource } from '../filesystem/resolve-path.js';
/**
* Resolve a model-chosen path against the tool cwd and run it through the
@@ -14,10 +15,10 @@ import { pinnedBinary, pinnedSearchDirs, minimalEnv } from '../shell/argv-lane.j
*/
export async function checkGitReadPath(
permissions: PermissionManager,
- getCwd: () => string,
+ getCwd: CwdSource,
path: string,
): Promise<{ resolved: string; error?: undefined } | { resolved: string; error: string }> {
- const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
+ const resolved = resolveToolPath(path, getCwd);
const check = await permissions.checkFsAccess(resolved, 'read');
if (!check.allowed) {
return { resolved, error: readDenialMessage(resolved, check) };
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index fb53b49c..cc26aad1 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -60,6 +60,7 @@ import type { SpotifyClient } from '../spotify/client.js';
import { createDelegateTaskTool, createListAgentsTool, createStopAgentTool } from './subagents/index.js';
import { createDispatchBotTool } from '../bots/tools/dispatch-bot.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
+import type { CwdSource } from './filesystem/resolve-path.js';
import { logger } from '../utils/logger.js';
export interface ChatCommandContext {
@@ -149,8 +150,29 @@ export class CapabilityRegistry {
return this.currentCwd;
}
- setCwd(dir: string): void {
+ /** Returns false (and keeps the current directory) when the cwd guard refuses. */
+ setCwd(dir: string): boolean {
+ if (this.cwdGuard && !this.cwdGuard(dir)) return false;
this.currentCwd = dir;
+ return true;
+ }
+
+ private cwdGuard: ((dir: string) => boolean) | null = null;
+ private pathRoots: Array<readonly [string, string]> = [];
+ /** What file and git tools resolve relative paths against (cwd + named roots). */
+ private readonly cwdSource: CwdSource = Object.assign(() => this.getCwd(), { roots: () => this.pathRoots });
+
+ /** Limit where `cd` (tool or shell) may move this registry's cwd. */
+ setCwdGuard(guard: ((dir: string) => boolean) | null): void {
+ this.cwdGuard = guard;
+ }
+
+ /**
+ * Relative paths starting with one of these prefixes resolve under the
+ * given directory, regardless of cwd (e.g. a bot's "_shared/…").
+ */
+ setPathRoots(roots: Array<readonly [prefix: string, dir: string]>): void {
+ this.pathRoots = roots;
}
setSendFileHandler(handler: (filePath: string, channel?: string) => Promise<void>): void {
@@ -192,18 +214,18 @@ export class CapabilityRegistry {
const manifest = this.permissions.getManifest();
if (manifest.capabilities.filesystem.enabled) {
- this.tools.read_file = createReadFileTool(this.permissions, () => this.getCwd());
- this.tools.write_file = createWriteFileTool(this.permissions, () => this.getCwd());
- this.tools.create_file = createCreateFileTool(this.permissions, () => this.getCwd());
- this.tools.list_dir = createListDirTool(this.permissions, () => this.getCwd());
- this.tools.delete_file = createDeleteFileTool(this.permissions, () => this.getCwd());
- this.tools.edit_file = createEditFileTool(this.permissions, () => this.getCwd());
+ this.tools.read_file = createReadFileTool(this.permissions, this.cwdSource);
+ this.tools.write_file = createWriteFileTool(this.permissions, this.cwdSource);
+ this.tools.create_file = createCreateFileTool(this.permissions, this.cwdSource);
+ this.tools.list_dir = createListDirTool(this.permissions, this.cwdSource);
+ this.tools.delete_file = createDeleteFileTool(this.permissions, this.cwdSource);
+ this.tools.edit_file = createEditFileTool(this.permissions, this.cwdSource);
if (this.sendFileHandler) {
- this.tools.send_file = createSendFileTool(this.permissions, () => this.getCwd(), this.sendFileHandler);
+ this.tools.send_file = createSendFileTool(this.permissions, this.cwdSource, this.sendFileHandler);
}
- this.tools.approve_scope = createApproveScopeTool(this.permissions, () => this.getCwd());
+ this.tools.approve_scope = createApproveScopeTool(this.permissions, this.cwdSource);
logger.info('Filesystem tools registered');
}
@@ -246,12 +268,12 @@ export class CapabilityRegistry {
}
if (manifest.capabilities.git?.enabled) {
- this.tools.git_status = createGitStatusTool(this.permissions, () => this.getCwd());
- this.tools.git_diff = createGitDiffTool(this.permissions, () => this.getCwd());
- this.tools.git_log = createGitLogTool(this.permissions, () => this.getCwd());
- this.tools.git_add = createGitAddTool(this.permissions, () => this.getCwd());
- this.tools.git_commit = createGitCommitTool(this.permissions, () => this.getCwd());
- this.tools.git_push = createGitPushTool(this.permissions, () => this.getCwd());
+ this.tools.git_status = createGitStatusTool(this.permissions, this.cwdSource);
+ this.tools.git_diff = createGitDiffTool(this.permissions, this.cwdSource);
+ this.tools.git_log = createGitLogTool(this.permissions, this.cwdSource);
+ this.tools.git_add = createGitAddTool(this.permissions, this.cwdSource);
+ this.tools.git_commit = createGitCommitTool(this.permissions, this.cwdSource);
+ this.tools.git_push = createGitPushTool(this.permissions, this.cwdSource);
logger.info('Git tools registered');
}
diff --git a/src/capabilities/shell/cd.ts b/src/capabilities/shell/cd.ts
index c07cbbb8..7dee3471 100644
--- a/src/capabilities/shell/cd.ts
+++ b/src/capabilities/shell/cd.ts
@@ -3,7 +3,7 @@ import { z } from 'zod';
import { resolve, isAbsolute } from 'node:path';
import { existsSync, statSync } from 'node:fs';
-export function createCdTool(getCwd: () => string, setCwd: (dir: string) => void) {
+export function createCdTool(getCwd: () => string, setCwd: (dir: string) => boolean | void) {
return tool({
description: 'Change the current working directory. All subsequent file operations, shell commands, and git operations will use this directory. Use this before running commands in a specific project folder.',
inputSchema: zodSchema(z.object({
@@ -26,7 +26,9 @@ export function createCdTool(getCwd: () => string, setCwd: (dir: string) => void
return `Error: Cannot access: ${resolved}`;
}
- setCwd(resolved);
+ if (setCwd(resolved) === false) {
+ return `Error: you can only change directory inside your own work folders. Use absolute paths to work with ${resolved}.`;
+ }
return `Changed directory to ${resolved}`;
},
});
diff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.ts
index ddab761a..c2a729c5 100644
--- a/src/capabilities/shell/run-command.ts
+++ b/src/capabilities/shell/run-command.ts
@@ -153,7 +153,7 @@ function superviseChild(start: () => ChildProcess, timeoutMs: number, options: E
});
}
-export function createRunCommandTool(permissions: PermissionManager, getCwd: () => string, setCwd: (dir: string) => void) {
+export function createRunCommandTool(permissions: PermissionManager, getCwd: () => string, setCwd: (dir: string) => boolean | void) {
return tool({
description: `Run a shell command in the current working directory. Use the cd tool to change directories first — cd commands within this tool only affect chained commands (e.g., "cd /path && ls"), not subsequent calls.
Blocked commands (sudo, rm -rf /, etc.) are never executed.
@@ -247,7 +247,7 @@ The optional timeout parameter sets how long (in seconds) the command can run be
}
/** `cd` in the argv lane: change the tool cwd in-process (it is a shell builtin). */
-function runBuiltin(plan: Extract<ArgvPlan, { kind: 'builtin' }>, cwd: string, setCwd: (dir: string) => void): string {
+function runBuiltin(plan: Extract<ArgvPlan, { kind: 'builtin' }>, cwd: string, setCwd: (dir: string) => boolean | void): string {
const target = plan.argv[1] ?? homedir();
const resolved = isAbsolute(target) ? resolve(target) : resolve(cwd, target);
try {
@@ -255,11 +255,13 @@ function runBuiltin(plan: Extract<ArgvPlan, { kind: 'builtin' }>, cwd: string, s
} catch {
return `Error: Directory not found: ${resolved}`;
}
- setCwd(resolved);
+ if (setCwd(resolved) === false) {
+ return `Error: you can only change directory inside your own work folders. Use absolute paths to work with ${resolved}.`;
+ }
return `Changed directory to ${resolved}`;
}
-function detectCd(command: string, currentCwd: string, setCwd: (dir: string) => void): void {
+function detectCd(command: string, currentCwd: string, setCwd: (dir: string) => boolean | void): void {
const trimmed = command.trim();
const cdOnly = trimmed.match(/^cd\s+(.+)$/);