Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): skill access for bots — native library + per-bot skill libraries
Salman Qureshif07868b4646d
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex ff515032..7d056688 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import { mkdtempSync, rmSync, existsSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, existsSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -17,6 +17,7 @@ import { generateText } from 'ai';import { BotManager } from './bot-manager.js';import { BotStore } from './store.js';import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';+import { SkillLoader } from '../skills/loader.js';import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';import type { BotManifest } from './types.js';@@ -472,6 +473,28 @@ describe('Per-bot permission isolation (fail-closed)', () => {expect(shared).toMatchObject({ read: true, write: true, execute: true });});+ it('bot toolset gains list_skills + use_skill; install_skill stays stripped', () => {+ const manifest = store.create({ id: 'skillful', name: 'Skillful' }) as BotManifest;+ const loader = new SkillLoader(join(root, 'skills'), { seedDefaults: false });+ loader.discover();+ const registry = createBotCapabilityRegistry({+ botId: 'skillful',+ manifest,+ botDir: store.botDir('skillful'),+ permissions: store.readPermissions('skillful'),+ skillLoader: loader,+ userMemory: null,+ config: getDefaultConfig() as MercuryConfig,+ });+ const tools = registry.getTools();+ expect(tools.list_skills).toBeDefined();+ expect(tools.use_skill).toBeDefined();+ const filtered = filterBotTools({ ...tools }, manifest);+ expect(filtered.list_skills).toBeDefined();+ expect(filtered.use_skill).toBeDefined();+ expect(filtered.install_skill).toBeUndefined();+ });+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({@@ -582,4 +605,43 @@ describe('bot_send tool scoping', () => {const firstCall = mockedGenerateText.mock.calls[0][0] as any;expect(JSON.stringify(firstCall.messages)).toContain('Message from 🤖 researcher');});-});\ No newline at end of file+});+describe('Bot skill access (native + own library)', () => {+ let root: string;+ let store: BotStore;+ let manager: BotManager;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-skills-'));+ store = new BotStore(join(root, 'bots'));+ manager = makeManager(root);+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ function writeSkill(dir: string, name: string, body: string) {+ const skillDir = join(dir, name);+ mkdirSync(skillDir, { recursive: true });+ writeFileSync(join(skillDir, 'SKILL.md'), `---\nname: ${name}\ndescription: ${name} skill\nallowed-tools: []\n---\n\n${body}\n`);+ }++ it('turn prompts list native skills AND the bot\'s own library', async () => {+ // Default skills root = <botsRoot>/../skills — the native library.+ writeSkill(join(root, 'skills'), 'shared-procedure', 'Native procedure steps.');+ // The bot's OWN library: synthesized or hand-authored, bot-private.+ writeSkill(store.skillsDir('skilled'), 'own-procedure', 'The bot learned this itself.');+ seedBot(store, 'skilled');+ let systemPrompt = '';+ mockedGenerateText.mockImplementation(async (opts: any) => {+ systemPrompt = opts.system ?? '';+ return { text: 'ok', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;+ });+ manager.enqueue('skilled', { trigger: 'chat', prompt: 'hi' });+ await vi.waitFor(() => {+ expect(systemPrompt).toContain('own-procedure');+ expect(systemPrompt).toContain('shared-procedure');+ });+ });+});diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 001e0bf6..ba7b603e 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -1,5 +1,6 @@import { cpus } from 'node:os';import { randomUUID } from 'node:crypto';+import { resolve } from 'node:path';import type { Tool } from 'ai';import type { MercuryConfig } from '../utils/config.js';import type { ProviderRegistry } from '../providers/registry.js';@@ -15,6 +16,7 @@ import { createBotSendTool } from './tools/bot-send.js';import { createBotScheduleTool, type BotScheduler } from './tools/bot-schedule.js';import { runBotTurn, isTransientFailure, type BotTurnMail } from './bot-turn.js';import { synthesizeSkill, MIN_TOOLS_FOR_SYNTHESIS } from './skill-synthesis.js';+import { SkillLoader } from '../skills/loader.js';import { logger } from '../utils/logger.js';import type {BotLiveState,@@ -52,6 +54,8 @@ export interface BotManagerDeps {queue?: BotQueue;/** Per-bot memory factory (P0-5 wires the default: UserMemoryStore with bot:<id> key). */userMemoryFactory?: (botId: string, manifest: BotManifest) => UserMemoryStore | null;+ /** Global (native) skills root; default resolves to <botsRoot>/../skills (~/.mercury/skills). */+ skillsRoot?: string;/** Deliver turn output to the invoking surface (chat/telegram/api). */notify?: (channelType: string, channelId: string, message: string) => Promise<void>;}@@ -84,6 +88,7 @@ export class BotManager {private readonly providers: ProviderRegistry;private readonly tokenBudget: TokenBudget;private readonly userMemoryFactory?: BotManagerDeps['userMemoryFactory'];+ private readonly skillsRoot?: BotManagerDeps['skillsRoot'];private notify?: BotManagerDeps['notify'];private alert?: (message: string) => Promise<void>;@@ -125,7 +130,7 @@ export class BotManager {private mailboxes: Map<string, BotTurnMail[]> = new Map();private running: Map<string, Set<string>> = new Map(); // botId → running job idsprivate aborts: Map<string, AbortController> = new Map(); // job key → controller- private registries: Map<string, { registry: CapabilityRegistry; tools: Record<string, Tool> }> = new Map();+ private registries: Map<string, { registry: CapabilityRegistry; tools: Record<string, Tool>; skillsPrompt: string }> = new Map();private activity: Map<string, string> = new Map(); // botId → current activityprivate lastRun: Map<string, { at: number; state: BotRunRecord['state'] }> = new Map();private needsYou: Set<string> = new Set();@@ -158,6 +163,7 @@ export class BotManager {});this.notify = deps.notify;this.store = deps.store ?? new BotStore();+ this.skillsRoot = deps.skillsRoot;this.queue = deps.queue ?? new BotQueue(this.store.botsRoot, this.config.bots?.retention?.dlqCap);// Resume work a crashed predecessor left behind: pending jobs (and// expired-lease claimed jobs) re-enter the in-memory queues. Durable@@ -400,7 +406,12 @@ export class BotManager {output: output.output,toolsUsed: output.toolsUsed,provider: resolveProvider(this.providers, manifest),- }).catch((err) => logger.warn({ err, botId }, 'Skill synthesis failed'));+ // The synthesized skill lands in the BOT'S OWN library (draft:true),+ // not the global root — it is that bot's learned procedure, usable+ // by it on the next run (runtime invalidated on success).+ skillsRoot: this.store.skillsDir(botId),+ }).then((synth) => { if (synth) this.invalidateRuntime(botId); })+ .catch((err) => logger.warn({ err, botId }, 'Skill synthesis failed'));}// Transient provider failures retry with backoff, bounded; permanent@@ -510,7 +521,7 @@ export class BotManager {}private buildTurn(botId: string, manifest: BotManifest, job: BotJob, signal: AbortSignal): { input: Parameters<typeof runBotTurn>[0]; cleanup: () => void } {- const { registry, tools } = this.getOrCreateRuntime(botId, manifest);+ const { registry, tools, skillsPrompt } = this.getOrCreateRuntime(botId, manifest);const userMemory = this.userMemoryFor(botId, manifest);const mail: BotTurnMail[] = [];@@ -527,6 +538,7 @@ export class BotManager {mail,pollMail: () => this.drainMailbox(botId),sandbox: { workspace: this.store.sandboxDir(botId), shared: this.store.sharedSandboxDir() },+ skillsPrompt,capabilities: registry,tools,userMemory,@@ -538,9 +550,25 @@ export class BotManager {};}- private getOrCreateRuntime(botId: string, manifest: BotManifest): { registry: CapabilityRegistry; tools: Record<string, Tool> } {+ private getOrCreateRuntime(botId: string, manifest: BotManifest): { registry: CapabilityRegistry; tools: Record<string, Tool>; skillsPrompt: string } {const cached = this.registries.get(botId);- if (cached) return cached;+ if (cached) return cached as { registry: CapabilityRegistry; tools: Record<string, Tool>; skillsPrompt: string };+ // Skill access: global (native) library + the bot's own skills dir+ // (auto-synthesized + hand-authored; own-dir names win on collision).+ // Default root = <botsRoot>/../skills — ~/.mercury/skills in production,+ // tmp-local in tests.+ let skillLoader: SkillLoader | undefined;+ let skillsPrompt = '';+ try {+ skillLoader = new SkillLoader(this.skillsRoot ?? resolve(this.store.botsRoot, '..', 'skills'), {+ extraDirs: [this.store.skillsDir(botId)],+ seedDefaults: false,+ });+ skillLoader.discover();+ skillsPrompt = skillLoader.getSkillSummariesText();+ } catch (err: any) {+ logger.warn({ botId, err: err?.message }, 'Bot skill loader unavailable — continuing without skills');+ }const registry = createBotCapabilityRegistry({botId,manifest,@@ -550,6 +578,7 @@ export class BotManager {// registry build, so a persona edit (invalidateRuntime on write) applies// to the very next turn.persona: this.store.readPersona(botId),+ skillLoader,// 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() },@@ -568,8 +597,8 @@ export class BotManager {if (this.scheduler) {filtered.bot_schedule = createBotScheduleTool(this.scheduler, botId);}- this.registries.set(botId, { registry, tools: filtered });- return { registry, tools: filtered };+ this.registries.set(botId, { registry, tools: filtered, skillsPrompt });+ return { registry, tools: filtered, skillsPrompt };}invalidateRuntime(botId: string): void {diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.tsindex 34170811..2015f539 100644--- a/src/bots/bot-turn.ts+++ b/src/bots/bot-turn.ts@@ -25,6 +25,8 @@ export interface BotTurnInput {pollMail: () => BotTurnMail[];/** Sandbox areas granted implicitly (rw+x): private workspace + fleet-shared folder. */sandbox: { workspace: string; shared: string };+ /** Skill roster text (native + the bot's own library); empty when none. */+ skillsPrompt?: string;capabilities: CapabilityRegistry;tools: Record<string, Tool>;userMemory: UserMemoryStore | null;@@ -232,6 +234,11 @@ Anything outside these two areas and your declared Access grants is denied.`;prompt += `\n\nAvailable tools: ${toolNames.join(', ')}`;}+ if (input.skillsPrompt) {+ prompt += `\n\n${input.skillsPrompt}`;+ prompt += `\nSkill scripts are subject to your access grants: a skill whose scripts you cannot run from its own directory can be copied into your sandbox workspace and run from there.`;+ }+const remaining = input.tokenBudget.getRemaining();prompt += `\n\nToken budget remaining: ${remaining}`;diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.tsindex 0cf2a5fb..3b97851e 100644--- a/src/bots/registry-factory.ts+++ b/src/bots/registry-factory.ts@@ -2,6 +2,7 @@ import { homedir } from 'node:os';import { mkdirSync } from 'node:fs';import { 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';import type { MercuryConfig } from '../utils/config.js';import { logger } from '../utils/logger.js';@@ -44,6 +45,11 @@ export interface BotRegistryDeps {* with permissions.yaml). Absent or empty section = no change.*/persona?: string;+ /**+ * Skill access: when set, the bot gets list_skills + use_skill over the+ * global library AND its own skills dir (install_skill stays stripped).+ */+ skillLoader?: SkillLoader;/*** Sandbox areas granted implicitly (read/write/execute, no ask, no* persona declaration): deps.botDir/sandbox (private workspace) and the@@ -63,7 +69,7 @@ export interface BotRegistryDeps {* - no persistent-manifest writes: interactive mutation tools are stripped*/export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRegistry {- const registry = new CapabilityRegistry();+ const registry = new CapabilityRegistry(deps.skillLoader);const pm = registry.permissions;// Reshape the manifest in place (never call save() — that writes thediff --git a/src/bots/store.ts b/src/bots/store.tsindex 4f458b6e..22bd0390 100644--- a/src/bots/store.ts+++ b/src/bots/store.ts@@ -160,6 +160,11 @@ export class BotStore {return join(this.botDir(id), BOT_SANDBOX_DIRNAME);}+ /** The bot's own skill library (auto-synthesized + hand-authored; bot-private). */+ skillsDir(id: string): string {+ return join(this.botDir(id), 'skills');+ }+/** The fleet-shared sandbox folder (one physical dir; every bot gets rw+x). */sharedSandboxDir(): string {return resolve(this.botsRoot, BOT_SHARED_SANDBOX_DIRNAME);diff --git a/src/capabilities/permissions.test.ts b/src/capabilities/permissions.test.tsindex 438269b0..f80af97d 100644--- a/src/capabilities/permissions.test.ts+++ b/src/capabilities/permissions.test.ts@@ -93,6 +93,19 @@ describe('fail-closed execute scopes (bots)', () => {});});+describe('fail-closed skill elevation', () => {+ it('elevateForSkill is a no-op in fail-closed mode (skills never re-permission a bot)', async () => {+ const permissions = new PermissionManager();+ permissions.getManifest().capabilities.shell.enabled = true;+ permissions.setFailClosed(true);+ permissions.setCurrentContext('bot', 'worker');+ permissions.elevateForSkill(['fs_write', 'run_command', 'read_file']);+ // Without the guard, elevation would bypass the fail-closed gates.+ await expect(permissions.checkFsAccess('/etc/hosts', 'write')).resolves.toMatchObject({ allowed: false });+ await expect(permissions.checkShellCommand('npm install')).resolves.toMatchObject({ allowed: false });+ });+});+describe('PermissionManager remote safety', () => {it('enforces hard command blocks before Local allow-all', async () => {const permissions = new PermissionManager();diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.tsindex b8585b26..bab6e8b4 100644--- a/src/capabilities/permissions.ts+++ b/src/capabilities/permissions.ts@@ -358,6 +358,15 @@ export class PermissionManager {}elevateForSkill(allowedTools: string[]): void {+ // Fail-closed mode (bots): skill elevation must never widen the granted+ // scopes — elevation is checked BEFORE the fail-closed gates in+ // checkFsAccess/checkShellCommand, so honoring it here would hand any+ // skill with allowed-tools an unrestricted bypass. Skills guide; they do+ // not re-permission.+ if (this.failClosed) {+ logger.info({ allowedTools }, 'Skill elevation ignored in fail-closed mode (granted scopes rule)');+ return;+ }if (allowedTools.includes('run_command')) {this.elevatedCommands.add('run_command');}diff --git a/src/skills/loader.test.ts b/src/skills/loader.test.tsindex c6bb2530..54144c75 100644--- a/src/skills/loader.test.ts+++ b/src/skills/loader.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, beforeEach, afterEach } from 'vitest';-import { mkdtempSync, rmSync, existsSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, existsSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';import { SkillLoader } from './loader.js';@@ -35,3 +35,51 @@ describe('SkillLoader skill-name confinement', () => {expect(() => loader.installFromContent(content)).toThrow(/outside the skills root/);});});++describe('SkillLoader extra skill roots (per-bot libraries)', () => {+ let root: string;+ let botSkills: string;++ beforeEach(() => {+ // Both roots are NOT-yet-existing children so the seedDefaults test can+ // prove the loader never touches the primary root.+ root = join(mkdtempSync(join(tmpdir(), 'mercury-skills-extra-')), 'skills');+ botSkills = join(mkdtempSync(join(tmpdir(), 'mercury-skills-bot-')), 'skills');+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ function writeSkill(dir: string, slug: string, name: string, description: string) {+ const skillDir = join(dir, slug);+ mkdirSync(skillDir, { recursive: true });+ writeFileSync(join(skillDir, 'SKILL.md'), `---\nname: ${name}\ndescription: ${name} skill\n---\n\nDo the ${name} thing.\n`);+ return skillDir;+ }++ it('discovers skills from extraDirs alongside the primary root', () => {+ writeSkill(join(root, 'shared'), 'shared-skill', 'shared-skill', 'x');+ writeSkill(botSkills, 'own-skill', 'own-skill', 'x');+ const loader = new SkillLoader(root, { extraDirs: [botSkills], seedDefaults: false });+ const names = loader.discover().map(s => s.name).sort();+ expect(names).toContain('shared-skill');+ expect(names).toContain('own-skill');+ });++ it('own-dir skills win on name collision with the primary root', () => {+ writeSkill(join(root, 'digest'), 'digest', 'digest', 'x');+ writeSkill(botSkills, 'digest', 'digest', 'x');+ const loader = new SkillLoader(root, { extraDirs: [botSkills], seedDefaults: false });+ loader.discover();+ const skill = loader.load('digest');+ // The bot's own version loads (extraDirs walk last, and load prefers the deepest/last match)+ expect(skill).not.toBeNull();+ expect(skill?.instructions).toContain('Do the digest thing');+ });++ it('seedDefaults:false never writes into the primary root (bots are read-only guests there)', () => {+ new SkillLoader(root, { extraDirs: [botSkills], seedDefaults: false }).discover();+ expect(existsSync(root)).toBe(false); // no mkdir, no default-seed writes+ });+});diff --git a/src/skills/loader.ts b/src/skills/loader.tsindex e369d87c..fa57cca9 100644--- a/src/skills/loader.ts+++ b/src/skills/loader.ts@@ -30,12 +30,17 @@ function parseSkillMd(content: string): { meta: SkillMeta; instructions: stringexport class SkillLoader {private skillsDir: string;+ /** Additional read-only skill roots (e.g. a bot's own skills dir). Own-dir entries load after the primary dir, so they win on name collision. */+ private extraDirs: string[];+ private seedDefaults: boolean;private discovered: Map<string, SkillDiscovery> = new Map();private loaded: Map<string, Skill> = new Map();readonly intentRouter: IntentRouter;- constructor(skillsDir?: string) {+ constructor(skillsDir?: string, options?: { extraDirs?: string[]; seedDefaults?: boolean }) {this.skillsDir = skillsDir || join(getMercuryHome(), 'skills');+ this.extraDirs = options?.extraDirs ?? [];+ this.seedDefaults = options?.seedDefaults !== false;this.intentRouter = new IntentRouter();}@@ -43,11 +48,14 @@ export class SkillLoader {this.discovered.clear();this.loaded.clear();if (!existsSync(this.skillsDir)) {+ if (!this.seedDefaults) return [];mkdirSync(this.skillsDir, { recursive: true });this.seedTemplate();}- this.ensureDefaultSkills();+ if (this.seedDefaults) {+ this.ensureDefaultSkills();+ }// Walk both layouts:// - flat: <skillsDir>/<name>/SKILL.md (legacy + user-authored)@@ -116,11 +124,19 @@ export class SkillLoader {*/private findSkillFiles(): string[] {const out: string[] = [];- if (!existsSync(this.skillsDir)) return out;+ for (const dir of [this.skillsDir, ...this.extraDirs]) {+ this.findSkillFilesIn(dir, out);+ }+ return out;+ }- for (const entry of readdirSync(this.skillsDir, { withFileTypes: true })) {+ /** Walk one skills root (flat + one nested category level), appending SKILL.md paths. */+ private findSkillFilesIn(skillsDir: string, out: string[]): string[] {+ if (!existsSync(skillsDir)) return out;++ for (const entry of readdirSync(skillsDir, { withFileTypes: true })) {if (!entry.isDirectory() || entry.name.startsWith('_') || entry.name.startsWith('.')) continue;- const dir = join(this.skillsDir, entry.name);+ const dir = join(skillsDir, entry.name);if (existsSync(join(dir, DISABLED_FILE))) continue;const flat = join(dir, SKILL_FILE);