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.

feat(bots): per-bot sandbox workspace + fleet-shared folder (implicit grants)

Salman Qureshi0d39b4605baf
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.ts
index 703f9fe5..ffdaa2e7 100644
--- a/src/bots/bot-manager.test.ts
+++ b/src/bots/bot-manager.test.ts
@@ -206,6 +206,21 @@ describe('BotManager queue + turn lifecycle', () => {
expect(manager.runNow('crony').accepted).toBe(true);
});
+ it('tells the bot its sandbox paths and the shared-folder standing rule', async () => {
+ seedBot(store, 'pathfinder');
+ let systemPrompt = '';
+ mockedGenerateText.mockImplementation(async (opts: any) => {
+ systemPrompt = opts.system ?? '';
+ return { text: 'ok', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ });
+ manager.enqueue('pathfinder', { trigger: 'chat', prompt: 'hi' });
+ await vi.waitFor(() => {
+ expect(systemPrompt).toContain(store.sandboxDir('pathfinder'));
+ expect(systemPrompt).toContain('_shared');
+ expect(systemPrompt).toContain('even when not explicitly asked');
+ });
+ });
+
it('degrades to a stateless bot when the memory store cannot be built', async () => {
// Simulates a SQLite-less device: the store factory throws.
const config = getDefaultConfig() as MercuryConfig;
@@ -408,6 +423,30 @@ describe('Per-bot permission isolation (fail-closed)', () => {
expect(scopes[0].path).toBe(store.botDir('plainbot'));
});
+ it('grants the private sandbox and fleet-shared folder implicitly (rw+x)', () => {
+ const manifest = store.create({ id: 'sandboxer', name: 'Sandboxer' }) as BotManifest;
+ // create() materializes both sandbox areas
+ expect(existsSync(store.sandboxDir('sandboxer'))).toBe(true);
+ expect(existsSync(store.sharedSandboxDir())).toBe(true);
+ // and the shared dir is never mistaken for a bot
+ expect(store.list().map(m => m.id)).toEqual(['sandboxer']);
+ const registry = createBotCapabilityRegistry({
+ botId: 'sandboxer',
+ manifest,
+ botDir: store.botDir('sandboxer'),
+ permissions: store.readPermissions('sandboxer'),
+ persona: store.readPersona('sandboxer'),
+ sandbox: { workspace: store.sandboxDir('sandboxer'), shared: store.sharedSandboxDir() },
+ userMemory: null,
+ config: getDefaultConfig() as MercuryConfig,
+ });
+ const scopes = registry.permissions.getManifest().capabilities.filesystem.scopes;
+ const workspace = scopes.find(s => s.path === store.sandboxDir('sandboxer'));
+ const shared = scopes.find(s => s.path === store.sharedSandboxDir());
+ expect(workspace).toMatchObject({ read: true, write: true, execute: true });
+ expect(shared).toMatchObject({ read: true, write: true, execute: true });
+ });
+
it('fs write outside the bot scope is denied without prompting', async () => {
const manifest = store.create({ id: 'writer', name: 'Writer' }) as BotManifest;
const registry = createBotCapabilityRegistry({
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index 59dcea33..001e0bf6 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -526,6 +526,7 @@ export class BotManager {
persona: this.store.readPersona(botId),
mail,
pollMail: () => this.drainMailbox(botId),
+ sandbox: { workspace: this.store.sandboxDir(botId), shared: this.store.sharedSandboxDir() },
capabilities: registry,
tools,
userMemory,
@@ -549,6 +550,9 @@ export class BotManager {
// registry build, so a persona edit (invalidateRuntime on write) applies
// to the very next turn.
persona: this.store.readPersona(botId),
+ // Built-in work areas: private sandbox + fleet-shared folder (rw+x,
+ // implicit — no permission ask, no Access declaration).
+ sandbox: { workspace: this.store.sandboxDir(botId), shared: this.store.sharedSandboxDir() },
userMemory: this.userMemoryFor(botId, manifest),
config: this.config,
});
@@ -827,6 +831,7 @@ export class BotManager {
- \`/bots open <id>\` — open the bot's own chat; \`/bots\` — roster with live states.
- \`/bots create <id> "Name" "Description"\` — onboard; \`/bots persona <id> <text>\` — set its character.
- \`/bots journal <id>\` — recent runs; \`/bots dlq\` — failed jobs (replayable); \`/bots stop|start|enable|disable <id>\`; \`/bots run <id> [routine]\` — fire a routine now (or a bare wake).
+- Bots share data through the fleet-shared folder (\`${this.store.sharedSandboxDir()}\`); each also has a private sandbox next to its persona. Their outputs land in their own threads.
- The dispatch_bot tool lets you hand a task to a bot mid-conversation and continue talking; the result is delivered when the bot finishes.`);
return lines.join('\n');
}
diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.ts
index 4e75b1ec..34170811 100644
--- a/src/bots/bot-turn.ts
+++ b/src/bots/bot-turn.ts
@@ -23,6 +23,8 @@ export interface BotTurnInput {
mail: BotTurnMail[];
/** Callback checked between rounds for newly arrived mailbox messages. */
pollMail: () => BotTurnMail[];
+ /** Sandbox areas granted implicitly (rw+x): private workspace + fleet-shared folder. */
+ sandbox: { workspace: string; shared: string };
capabilities: CapabilityRegistry;
tools: Record<string, Tool>;
userMemory: UserMemoryStore | null;
@@ -214,6 +216,12 @@ function buildBotSystemPrompt(input: BotTurnInput): string {
- Actions you lack permission for are denied automatically (fail-closed). Do not attempt workarounds; report what you could not do.
- Stay in your specialty; say so plainly when a request falls outside it.`;
+ // Sandbox: the bot's always-granted work areas (rw+x, no permission ask).
+ prompt += `\n\nSandbox (always granted — read, write, execute; no permission needed):
+- Private workspace: ${input.sandbox.workspace} — your scratch area: drafts, intermediate work, compiled artifacts.
+- Fleet-shared folder: ${input.sandbox.shared} — one folder shared with all other bots. Publish reusable data here (clearly named files), even when not explicitly asked — other bots consume it without a handoff.
+Anything outside these two areas and your declared Access grants is denied.`;
+
const roster = manifest.comms?.canMessage ?? [];
if (roster.length > 0) {
prompt += `\n\nBots you can message via bot_send: ${roster.join(', ')}.`;
diff --git a/src/bots/persona-template.ts b/src/bots/persona-template.ts
index e0664b0a..d2a3b88a 100644
--- a/src/bots/persona-template.ts
+++ b/src/bots/persona-template.ts
@@ -98,7 +98,7 @@ Output ONLY markdown, in exactly this shape:
## Access
-<directory access the user EXPLICITLY granted — one bullet per grant, exactly like: \`- ~/some/dir — read\` or \`- ~/other/dir — read, write\` or \`- /usr/local/bin/tool — execute\`. Extract these ONLY from paths + access the user stated; if the user granted nothing beyond the bot's own profile directory, write the single line: Only the bot's own profile directory.>
+<the bot ALWAYS has its private sandbox workspace and the fleet-shared folder granted automatically — never list those here. This section holds ONLY extra directory access the user EXPLICITLY granted, one bullet per grant, exactly like: \`- ~/some/dir — read\` or \`- ~/other/dir — read, write\` or \`- /usr/local/bin/tool — execute\`. Extract these ONLY from paths + access the user stated; if the user granted nothing beyond the built-in sandboxes, write the single line: Only the bot's built-in sandbox and the fleet-shared folder.>
Rules: keep length proportional to the source material — a rich persona stays rich, never compress requirements away; never invent new capabilities, tools, or permissions; keep stated restrictions verbatim in meaning; the ## Access section may contain ONLY directory access the user stated — never invent paths, and never add write or execute where the user said read; no preamble, no code fences.`,
'You write precise bot persona files. Restructure only; never add or remove requirements.',
diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.ts
index 55eaf880..926c27e7 100644
--- a/src/bots/registry-factory.ts
+++ b/src/bots/registry-factory.ts
@@ -1,4 +1,5 @@
import { homedir } from 'node:os';
+import { mkdirSync } from 'node:fs';
import { resolve } from 'node:path';
import { CapabilityRegistry } from '../capabilities/registry.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
@@ -6,6 +7,7 @@ import type { MercuryConfig } from '../utils/config.js';
import { logger } from '../utils/logger.js';
import type { BotManifest, BotPermissionsFile, BotPathScope } from './types.js';
import { parsePersonaAccess } from './persona-access.js';
+import { BOT_SANDBOX_DIRNAME, BOT_SHARED_SANDBOX_DIRNAME } from './store.js';
/**
* Tools a bot must never see, regardless of manifest. These are the tools
@@ -42,6 +44,12 @@ export interface BotRegistryDeps {
* with permissions.yaml). Absent or empty section = no change.
*/
persona?: string;
+ /**
+ * Sandbox areas granted implicitly (read/write/execute, no ask, no
+ * persona declaration): deps.botDir/sandbox (private workspace) and the
+ * fleet-shared folder next to the bots root. Unset = not granted.
+ */
+ sandbox?: { workspace: string; shared: string };
}
/**
@@ -61,10 +69,19 @@ export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRe
// Reshape the manifest in place (never call save() — that writes the
// global ~/.mercury/permissions.yaml, and bots have no path to it).
const manifest = pm.getManifest();
- manifest.capabilities.filesystem.scopes = buildBotScopes(
- mergeScopeGrants(deps.permissions.paths, parsePersonaAccess(deps.persona ?? '')),
- deps.botDir,
- );
+ const granted = mergeScopeGrants(deps.permissions.paths, parsePersonaAccess(deps.persona ?? ''));
+ // Implicit sandbox grants come LAST and are never user-configurable away:
+ // the private workspace and the fleet-shared folder are the bot's built-in
+ // work areas (read/write/execute, no ask, no declaration).
+ if (deps.sandbox) {
+ mkdirSync(deps.sandbox.workspace, { recursive: true });
+ mkdirSync(deps.sandbox.shared, { recursive: true });
+ granted.push(
+ { scope: deps.sandbox.workspace, read: true, write: true, execute: true },
+ { scope: deps.sandbox.shared, read: true, write: true, execute: true },
+ );
+ }
+ manifest.capabilities.filesystem.scopes = buildBotScopes(granted, deps.botDir);
manifest.capabilities.shell.autoApproved = [];
manifest.capabilities.shell.blocked = [
...new Set([...manifest.capabilities.shell.blocked, ...(deps.permissions.blockedCommands ?? [])]),
diff --git a/src/bots/store.ts b/src/bots/store.ts
index 93c5da63..1189f32d 100644
--- a/src/bots/store.ts
+++ b/src/bots/store.ts
@@ -11,6 +11,11 @@ import type {
export const BOT_MANIFEST_FILENAME = 'bot.yaml';
export const BOT_PERSONA_FILENAME = 'persona.md';
export const BOT_PERMISSIONS_FILENAME = 'permissions.yaml';
+/** Fleet-shared sandbox folder (every bot gets read/write/execute). The
+ * underscore prefix keeps store.list() from ever treating it as a bot. */
+export const BOT_SHARED_SANDBOX_DIRNAME = '_shared';
+/** Per-bot private workspace inside the profile dir (auto-purged on delete). */
+export const BOT_SANDBOX_DIRNAME = 'sandbox';
export const BOT_ENV_FILENAME = '.env';
export const BOT_JOURNAL_FILENAME = 'journal.jsonl';
@@ -102,9 +107,13 @@ falls outside it.
## Access
-You can always read and write inside your own profile directory. Anything
-else is denied until it is granted here — one bullet per directory (the
-forms below are examples only; write real bullets to grant access):
+You always have three work areas — never ask permission for these, and do
+not declare them here: your private \`sandbox/\` folder (next to this
+persona file), the fleet \`_shared/\` folder (shared with all bots —
+publish reusable data there even when not asked), and your own profile
+directory. Anything else is denied until it is granted here — one bullet
+per directory (the forms below are examples only; write real bullets to
+grant access):
\`- ~/some/dir — read\` · \`- ~/other/dir — read, write\` · \`- /usr/local/bin/tool — execute\`.
A granted directory covers everything inside it. Outside these grants you
do not act — you stop and report which access you would have needed.
@@ -144,6 +153,22 @@ export class BotStore {
return dir;
}
+ /** The bot's private sandbox workspace (inside its profile dir — purged on delete). */
+ sandboxDir(id: string): string {
+ return join(this.botDir(id), BOT_SANDBOX_DIRNAME);
+ }
+
+ /** The fleet-shared sandbox folder (one physical dir; every bot gets rw+x). */
+ sharedSandboxDir(): string {
+ return resolve(this.botsRoot, BOT_SHARED_SANDBOX_DIRNAME);
+ }
+
+ /** Create both sandbox areas if missing (cheap + idempotent). */
+ ensureSandboxes(id: string): void {
+ mkdirSync(this.sandboxDir(id), { recursive: true });
+ mkdirSync(this.sharedSandboxDir(), { recursive: true });
+ }
+
list(): BotManifest[] {
if (!existsSync(this.botsRoot)) return [];
const manifests: BotManifest[] = [];
@@ -200,6 +225,7 @@ export class BotStore {
const dir = this.botDir(id);
mkdirSync(dir, { recursive: true });
+ this.ensureSandboxes(id);
this.save(manifest);
const personaFile = join(dir, manifest.persona ?? BOT_PERSONA_FILENAME);
if (!existsSync(personaFile)) {