Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): main-agent awareness + persona setup flow
Salman Qureshi53ce676fbbda
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex b77d7e6c..6ed900fc 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -159,6 +159,62 @@ describe('BotManager queue + turn lifecycle', () => {});});+describe('Main-agent bots awareness (system prompt section)', () => {+ let root: string;+ let store: BotStore;+ let manager: BotManager;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-aware-'));+ store = new BotStore(join(root, 'bots'));+ manager = makeManager(root);+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('lists bots with descriptions and live states so the main chat can answer precisely', () => {+ store.create({ id: 'researcher', name: 'Research', description: 'Deep research specialist' });+ store.create({ id: 'publisher', name: 'Publisher', manifest: { enabled: false } });+ const section = manager.getSystemPromptSection();+ expect(section).toContain('**Research** (`researcher`) — Deep research specialist');+ expect(section).toContain('idle');+ expect(section).toContain('disabled');+ });++ it('documents the control commands and the dispatch tool', () => {+ seedBot(store, 'researcher');+ const section = manager.getSystemPromptSection();+ expect(section).toContain('/bot <id> <message>');+ expect(section).toContain('dispatch_bot');+ expect(section).toContain('/bots open <id>');+ });++ it('empty fleet section still tells the agent how to onboard', () => {+ const section = manager.getSystemPromptSection();+ expect(section).toContain('no bots configured');+ expect(section).toContain('/bots create');+ });++ it('dispatch_bot tool routes through the handler with name resolution', async () => {+ const { createDispatchBotTool } = await import('./tools/dispatch-bot.js');+ store.create({ id: 'researcher', name: 'Research' });+ const calls: Array<{ bot: string; message: string }> = [];+ const tool = createDispatchBotTool((botId, message) => {+ const resolved = manager.resolveBotId(botId);+ calls.push({ bot: resolved ?? '', message });+ if (!resolved) return { accepted: false, reasonCode: 'target_unknown' };+ return { accepted: true, jobId: 'j1' };+ }, () => ({ channelType: 'cli', channelId: 'current' })) as any;+ const ok = await tool.execute({ bot: 'Research', message: 'do the thing' });+ expect(ok).toContain('Dispatched');+ expect(calls[0].bot).toBe('researcher');+ const unknown = await tool.execute({ bot: 'ghost', message: 'x' });+ expect(unknown).toContain('target_unknown');+ });+});+describe('BotManager mailboxes (bot-to-bot comms)', () => {let root: string;let store: BotStore;diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 048d5cc1..771fd90f 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -587,6 +587,34 @@ export class BotManager {}return null;}++ /**+ * Compact bots section for the MAIN agent's system prompt: without it the+ * conversational agent is blind to the bot fleet — it cannot answer "what+ * do my bots do" or hand a task to the right specialist. Kept to a few+ * lines per bot so the token cost stays trivial.+ */+ getSystemPromptSection(): string {+ const summaries = this.store.list();+ if (summaries.length === 0) {+ return '\n\nMercury Bots: no bots configured. The user can create one with `/bots create <id> "Name" "Description"`.';+ }+ const lines: string[] = [+ '\n\nMercury Bots — the user maintains these persistent specialist agents (each has its own persona, model, memory, and permissions; they run OUTSIDE this conversation):',+ ];+ for (const m of summaries) {+ const state = this.running.get(m.id)?.size ? 'running' : ((this.queues.get(m.id)?.length ?? 0) > 0 ? 'queued' : (m.enabled ? 'idle' : 'disabled'));+ const desc = m.description ? ` — ${m.description}` : '';+ lines.push(`- **${m.name}** (\`${m.id}\`)${desc} [${state}]`);+ }+ lines.push(`Bot control (never route bot work through this main conversation):+- \`/bot <id> <message>\` or \`@<id> <message>\` — dispatch a task to a bot; its reply arrives in this chat when done.+- \`/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|enable|disable <id>\`.+- 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');+ }}function resolveProvider(providers: ProviderRegistry, manifest: BotManifest) {diff --git a/src/bots/tools/dispatch-bot.ts b/src/bots/tools/dispatch-bot.tsnew file mode 100644index 00000000..4ee9694e--- /dev/null+++ b/src/bots/tools/dispatch-bot.ts@@ -0,0 +1,36 @@+import { tool, zodSchema } from 'ai';+import { z } from 'zod';++export interface BotDispatchResult {+ accepted: boolean;+ jobId?: string;+ reasonCode?: string;+}++/**+ * dispatch_bot — lets the MAIN agent hand a task to a Mercury bot+ * mid-conversation. The bot runs outside the main loop; its output is+ * delivered to the invoking channel when it finishes.+ */+export function createDispatchBotTool(handler: (botId: string, message: string, ctx: { channelType: string; channelId: string }) => BotDispatchResult | null, channelCtx: () => { channelType: string; channelId: string }) {+ return tool({+ description:+ 'Hand a task to one of the user\'s Mercury bots (persistent specialist agents with their own persona and tools). ' ++ 'Use this when a request matches a bot\'s specialty and the work is delegable (research, publishing, monitoring) — ' ++ 'the bot runs outside this conversation and its result is delivered here when done.',+ inputSchema: zodSchema(z.object({+ bot: z.string().describe('Bot id or name'),+ message: z.string().min(1).max(20000).describe('The task for the bot — self-contained and concrete'),+ })),+ execute: async ({ bot, message }: { bot: string; message: string }) => {+ const result = handler(bot, message, channelCtx());+ if (!result) {+ return 'Bots are not available on this instance.';+ }+ if (!result.accepted) {+ return `Dispatch rejected: [reason: ${result.reasonCode}] — check /bots for the roster and states.`;+ }+ return `Dispatched to ${bot} (job ${result.jobId}). The bot runs outside this conversation; its reply will be delivered to this chat when it finishes. Continue helping the user in the meantime.`;+ },+ });+}\ No newline at end of filediff --git a/src/capabilities/registry.ts b/src/capabilities/registry.tsindex a74cdbcb..3c763b53 100644--- a/src/capabilities/registry.ts+++ b/src/capabilities/registry.ts@@ -57,6 +57,7 @@ import type { TokenBudget } from '../utils/tokens.js';import type { SubAgentSupervisor } from '../core/supervisor.js';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 { logger } from '../utils/logger.js';@@ -93,6 +94,17 @@ export class CapabilityRegistry {private currentCwd = process.cwd();private researchModeGetter: (() => boolean) | null = null;+ /**+ * Mercury Bots dispatch handler — set once the BotManager exists+ * (src/index.ts). Registers the dispatch_bot tool so the main agent can+ * hand tasks to the bot fleet (the bots section in the system prompt comes+ * from BotManager.getSystemPromptSection via the Agent).+ */+ setBotDispatchHandler(handler: (botId: string, message: string, ctx: { channelType: string; channelId: string }) => import('../bots/tools/dispatch-bot.js').BotDispatchResult | null, channelCtx: () => { channelType: string; channelId: string }): void {+ this.tools.dispatch_bot = createDispatchBotTool(handler, channelCtx);+ logger.info('Bot dispatch tool registered (dispatch_bot)');+ }+constructor(skillLoader?: SkillLoader, scheduler?: Scheduler, tokenBudget?: TokenBudget, supervisor?: SubAgentSupervisor, userMemory?: UserMemoryStore) {this.permissions = new PermissionManager();this.skillLoader = skillLoader;diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 957c61b5..be0bd335 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -744,6 +744,17 @@ export class CLIChannel extends BaseChannel {}return;}+ // /persona <text> inside a bot chat rewrites to the explicit setter+ // so the persona flow works without leaving the bot thread.+ if (trimmed.startsWith('/persona')) {+ const personaText = trimmed.slice('/persona'.length).trim();+ if (personaText) {+ onInput(`/bots persona ${this.activeBotId} ${personaText}`);+ } else {+ onInput('/bots');+ }+ return;+ }}if (trimmed === '/chat' || trimmed === '/c') {// Returning from Mercury Code must tear down its state (mouse mode,diff --git a/src/core/agent.ts b/src/core/agent.tsindex 49cd481b..6a2f27ab 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -490,6 +490,8 @@ export class Agent {private stepNarrative: import('../utils/tool-label.js').NarrativeStep[] = [];private supervisor?: import('../core/supervisor.js').SubAgentSupervisor;private botManager?: import('../bots/bot-manager.js').BotManager;+ /** Bot awaiting a persona from the next message (post-create setup flow). */+ private pendingPersonaFor: string | null = null;readonly programmingMode: ProgrammingMode;readonly researchMode: ResearchMode;readonly saverMode: SaverMode;@@ -1087,6 +1089,29 @@ export class Agent {if (!bm) return;const channel = this.channels.getChannelForMessage(msg);if (!channel) return;++ // Post-create persona setup: the first message typed into the new bot's+ // chat becomes its persona instead of a task (send /skip to keep the+ // template). Any dispatch to a different bot cancels the pending setup.+ if (this.pendingPersonaFor) {+ if (this.pendingPersonaFor !== botId) {+ this.pendingPersonaFor = null;+ } else if (message.trim().toLowerCase() === '/skip') {+ this.pendingPersonaFor = null;+ await channel.send('⏭ Keeping the starter persona — edit it anytime with `/persona` here or `/bots persona <id> <text>`.', `bot:${botId}`)+ .catch(() => {});+ return;+ } else {+ bm.store.writePersona(botId, message.trim() + '\n');+ bm.invalidateRuntime(botId);+ this.pendingPersonaFor = null;+ await channel.send(+ `✍️ Persona set — **${bm.store.get(botId)?.name ?? botId}** is ready.\nTry: \`/bot ${botId} <task>\`, or just type here and it runs as a bot task.`,+ `bot:${botId}`,+ ).catch(() => {});+ return;+ }+ }// Dispatched from inside that bot's TUI chat → ack and reply land in// the bot's own transcript (targetId `bot:<id>`; cli.ts routes it).const pendingBot = (channel as any).consumePendingBotChatTarget?.() ?? null;@@ -1176,26 +1201,56 @@ export class Agent {}if (action === 'create' || action === 'onboard') {- // /bots create <id> "Name" "Description"+ // /bots create <id> "Name" "Description" ["persona text"]const id = (parts[1] ?? '').toLowerCase();if (!id) {- await channel.send('Usage: `/bots create <id> "Name" "Description"` — the bot starts with a fail-closed default profile you can refine via its profile files.', channelId);+ await channel.send('Usage: `/bots create <id> "Name" "Description" "persona (optional)"` — the bot starts with a fail-closed default profile you can refine via its profile files.', channelId);return;}const rest = trimmed.slice(trimmed.indexOf(id) + id.length).trim();const quoted = [...rest.matchAll(/"([^"]*)"/g)].map(m => m[1]);const name = quoted[0] ?? id.toUpperCase();const description = quoted[1];+ const personaText = quoted[2];try {const manifest = bm.store.create({ id, name, description });- bm.invalidateRuntime(id);- await channel.send(`🤖 Bot **${manifest.name}** (\`${id}\`) onboarded — enabled, fail-closed defaults (dangerous tools denied, memory scope own, only its own directory writable).\nPersona: \`${bm.store.botDir(id)}/persona.md\` — edit it to shape the bot's character.`, channelId);+ if (personaText) {+ bm.store.writePersona(id, personaText + '\n');+ bm.invalidateRuntime(id);+ await channel.send(`🤖 Bot **${manifest.name}** (\`${id}\`) onboarded with your persona — enabled, fail-closed defaults.\nStart using it: \`/bot ${id} <task>\`, \`/bots open ${id}\`, or just \`@${id} <task>\`.`, channelId);+ return;+ }+ // No persona given — open its chat and prompt for one now (TUI only).+ if (typeof (channel as any).enterBotChat === 'function') {+ (channel as any).enterBotChat(id, manifest.name);+ this.pendingPersonaFor = id;+ await channel.send(+ `🤖 **${manifest.name}** onboarded (fail-closed defaults).\n\nNow give it its character — your next message here becomes its **persona** (who it is, how it works, how it reports). Send \`/skip\` to keep the starter template, or \`/persona\` later to change it.`,+ `bot:${id}`,+ );+ } else {+ await channel.send(`🤖 Bot **${manifest.name}** (\`${id}\`) onboarded — enabled, fail-closed defaults.\nPersona: \`${bm.store.botDir(id)}/persona.md\` — set it now with \`/bots persona ${id} <text>\`.`, channelId);+ }} catch (err: any) {await channel.send(`Could not create bot "${id}": ${err?.message}`, channelId);}return;}+ if (action === 'persona') {+ const target = parts[1]?.toLowerCase();+ const personaText = trimmed.slice(trimmed.indexOf(target ?? '') + (target?.length ?? 0)).trim();+ if (!target || !personaText || !bm.store.exists(target)) {+ await channel.send('Usage: `/bots persona <id> <full persona text in one message>` — or open the bot chat (`/bots open <id>`) and type `/persona <text>`.', channelId);+ return;+ }+ bm.store.writePersona(target, personaText + '\n');+ bm.invalidateRuntime(target);+ this.pendingPersonaFor = null;+ await channel.send(`✍️ Persona updated for **${target}** — the next run uses it.`, channelId);+ return;+ }+if (action === 'send') {const target = parts[1]?.toLowerCase();const message = trimmed.slice(trimmed.indexOf(parts[1] ?? '') + (parts[1]?.length ?? 0)).trim();@@ -4467,6 +4522,12 @@ export class Agent {if (skillContext) {prompt += '\n\n' + skillContext;}+ // Mercury Bots: the main agent must know the fleet exists — what each+ // bot does, its live state, and how to dispatch to it. Without this the+ // conversational agent answers bot questions blindly.+ if (this.botManager) {+ prompt += this.botManager.getSystemPromptSection();+ }const programmingSuffix = this.programmingMode.getSystemPromptSuffix();if (programmingSuffix) {prompt += programmingSuffix;diff --git a/src/index.ts b/src/index.tsindex f1cea8d5..ddb3ce30 100644--- a/src/index.ts+++ b/src/index.ts@@ -2492,6 +2492,19 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {if (config.bots?.webhookSecret) {setBotsWebhookSecret(config.bots.webhookSecret);}+ // Main-agent awareness: bots section in the system prompt + dispatch tool.+ capabilities.setBotDispatchHandler((botIdOrName, message, ctx) => {+ const botId = botManager.resolveBotId(botIdOrName);+ if (!botId) return { accepted: false, reasonCode: 'target_unknown' };+ const result = botManager.enqueue(botId, {+ trigger: 'chat',+ prompt: message,+ source: { channelType: ctx.channelType, channelId: ctx.channelId },+ });+ return result.accepted+ ? { accepted: true, jobId: result.jobId }+ : { accepted: false, reasonCode: result.reasonCode };+ }, () => capabilities.getChannelContext());}let spotifyClient: SpotifyClient | undefined;