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): P2 — @mention routing, webhooks, auto-skill synthesis, web UI

Salman Qureshie222286c51f9
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index ded3fcda..048d5cc1 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -13,6 +13,7 @@ import { BotQueue, idempotencyKeyFor, LEASE_SECONDS, type DurableBotJob } from '
import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';
import { createBotSendTool } from './tools/bot-send.js';
import { runBotTurn, isTransientFailure, type BotTurnMail } from './bot-turn.js';
+import { synthesizeSkill, MIN_TOOLS_FOR_SYNTHESIS } from './skill-synthesis.js';
import { logger } from '../utils/logger.js';
import type {
BotLiveState,
@@ -317,6 +318,23 @@ export class BotManager {
this.needsYou.delete(botId);
this.recordBotTokens(botId, manifest, output.tokensIn + output.tokensOut);
+ // Auto-skill synthesis (P2-3): a completed multi-step run is a
+ // procedure worth keeping. Fire-and-forget, gated by config.
+ if (
+ output.status === 'completed'
+ && output.toolsUsed.length >= MIN_TOOLS_FOR_SYNTHESIS
+ && (this.config.bots as any)?.autoSkill?.enabled
+ ) {
+ void synthesizeSkill({
+ botId,
+ botName: manifest.name,
+ prompt: job.prompt,
+ output: output.output,
+ toolsUsed: output.toolsUsed,
+ provider: resolveProvider(this.providers, manifest),
+ }).catch((err) => logger.warn({ err, botId }, 'Skill synthesis failed'));
+ }
+
// Transient provider failures retry with backoff, bounded; permanent
// failures go to the capped DLQ and stop (never silently re-queued — §2.6).
if (output.status === 'failed' && output.reasonCode && isTransientFailure(output.reasonCode) && job.attempts + 1 < MAX_TRANSIENT_ATTEMPTS) {
@@ -560,6 +578,15 @@ export class BotManager {
getQueuedCount(botId: string): number {
return (this.queues.get(botId) ?? []).length;
}
+
+ /** Resolve a bot by id or case-insensitive name (for @mention routing). */
+ resolveBotId(nameOrId: string): string | null {
+ const needle = nameOrId.toLowerCase();
+ for (const m of this.store.list()) {
+ if (m.id === needle || m.name.toLowerCase() === needle) return m.id;
+ }
+ return null;
+ }
}
function resolveProvider(providers: ProviderRegistry, manifest: BotManifest) {
diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.ts
index b94666da..4e75b1ec 100644
--- a/src/bots/bot-turn.ts
+++ b/src/bots/bot-turn.ts
@@ -36,6 +36,8 @@ export interface BotTurnOutput {
output: string;
tokensIn: number;
tokensOut: number;
+ /** Distinct tool names the turn used (drives auto-skill synthesis). */
+ toolsUsed: string[];
error?: string;
reasonCode?: string;
}
@@ -69,6 +71,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
let tokensOut = 0;
let lastResult: any = null;
let stepsRemaining = maxSteps;
+ const toolsUsed = new Set<string>();
try {
while (stepsRemaining > 0 && !abortSignal.aborted) {
@@ -80,13 +83,16 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
stopWhen: stepCountIs(stepsRemaining),
abortSignal,
experimental_include: { requestBody: false, responseBody: false },
- onStepFinish: ({ usage }) => {
+ onStepFinish: ({ usage, toolCalls }) => {
if (abortSignal.aborted) return;
stepsRemaining--;
if (usage) {
tokensIn += usage.inputTokens ?? 0;
tokensOut += usage.outputTokens ?? 0;
}
+ for (const tc of toolCalls ?? []) {
+ if (tc?.toolName) toolsUsed.add(String(tc.toolName));
+ }
},
});
lastResult = result;
@@ -119,7 +125,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
}
if (abortSignal.aborted) {
- return { status: 'halted', output: 'Turn was halted.', tokensIn, tokensOut };
+ return { status: 'halted', output: 'Turn was halted.', tokensIn, tokensOut, toolsUsed: [...toolsUsed] };
}
// Step budget exhausted with tool calls still pending — pause, never
@@ -130,6 +136,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
output: 'Step budget reached before the turn completed — remaining work continues next turn.',
tokensIn,
tokensOut,
+ toolsUsed: [...toolsUsed],
reasonCode: 'step_budget',
};
}
@@ -145,16 +152,17 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
channelType: 'bot',
});
- return { status: 'completed', output, tokensIn, tokensOut };
+ return { status: 'completed', output, tokensIn, tokensOut, toolsUsed: [...toolsUsed] };
} catch (err: any) {
if (abortSignal.aborted) {
- return { status: 'halted', output: 'Turn was halted.', tokensIn, tokensOut };
+ return { status: 'halted', output: 'Turn was halted.', tokensIn, tokensOut, toolsUsed: [...toolsUsed] };
}
return {
status: 'failed',
output: `Turn failed: ${err?.message ?? String(err)}`,
tokensIn,
tokensOut,
+ toolsUsed: [...toolsUsed],
error: err?.message ?? String(err),
reasonCode: classifyFailure(err),
};
diff --git a/src/bots/skill-synthesis.test.ts b/src/bots/skill-synthesis.test.ts
new file mode 100644
index 00000000..30087b57
--- /dev/null
+++ b/src/bots/skill-synthesis.test.ts
@@ -0,0 +1,112 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { synthesizeSkill, MIN_TOOLS_FOR_SYNTHESIS } from './skill-synthesis.js';
+
+// Synthesis calls the provider object directly (BaseProvider.generateText),
+// so the stub is scriptable rather than an ai-module mock.
+const scriptedResponses: string[] = [];
+
+function stubProvider() {
+ return {
+ name: 'stub',
+ model: 'stub-model',
+ generateText: async () => ({
+ text: scriptedResponses.shift() ?? '',
+ inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub', provider: 'stub',
+ }),
+ streamText: async function* () { yield { text: '', done: true }; },
+ isAvailable: () => true,
+ getModelInstance: () => ({}),
+ getModel: () => 'stub-model',
+ } as any;
+}
+
+describe('auto-skill synthesis', () => {
+ let root: string;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-skill-synthesis-'));
+ scriptedResponses.length = 0;
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ const validModelOutput = `---
+name: RSS Market Scan
+description: Scan RSS sources and summarize market findings for the publishing pipeline
+allowed-tools: fetch_url, read_file, bot_send
+draft: true
+---
+
+1. Fetch each configured RSS source with fetch_url.
+2. Extract items published since the last run.
+3. Summarize findings and hand off to the publisher bot.
+`;
+
+ it('writes a draft SKILL.md under the bots skill category', async () => {
+ scriptedResponses.push(validModelOutput);
+ const result = await synthesizeSkill({
+ botId: 'researcher',
+ botName: 'Research',
+ prompt: 'Scan RSS sources',
+ output: 'Found 12 items',
+ toolsUsed: ['fetch_url', 'read_file', 'bot_send'],
+ provider: stubProvider(),
+ skillsRoot: root,
+ });
+ expect(result?.name).toBe('RSS Market Scan');
+ const path = result!.path;
+ expect(existsSync(path)).toBe(true);
+ const content = readFileSync(path, 'utf-8');
+ expect(content).toContain('draft: true');
+ expect(content).toContain('RSS source');
+ // Nested layout the loader already understands: <root>/bots/<slug>/SKILL.md
+ expect(path).toContain(join('bots', 'researcher-rss-market-scan', 'SKILL.md'));
+ });
+
+ it('never overwrites an existing skill draft', async () => {
+ scriptedResponses.push(validModelOutput);
+ const first = await synthesizeSkill({
+ botId: 'researcher', botName: 'Research', prompt: 'p', output: 'o',
+ toolsUsed: ['a', 'b', 'c'], provider: stubProvider(), skillsRoot: root,
+ });
+ expect(first).not.toBeNull();
+ // Second run with the same procedure → existing draft is kept as-is
+ const second = await synthesizeSkill({
+ botId: 'researcher', botName: 'Research', prompt: 'p2', output: 'o2',
+ toolsUsed: ['a', 'b', 'c'], provider: stubProvider(), skillsRoot: root,
+ });
+ expect(second).toBeNull();
+ const content = readFileSync(first!.path, 'utf-8');
+ expect(content).toContain('RSS Market Scan');
+ });
+
+ it('returns null for unusable model output (no frontmatter, too short)', async () => {
+ scriptedResponses.push('I wrote a thing but not a skill file');
+ const result = await synthesizeSkill({
+ botId: 'researcher', botName: 'Research', prompt: 'p', output: 'o',
+ toolsUsed: ['a', 'b', 'c'], provider: stubProvider(), skillsRoot: root,
+ });
+ expect(result).toBeNull();
+ });
+
+ it('is non-fatal when the provider throws', async () => {
+ const throwingProvider = {
+ ...stubProvider(),
+ generateText: async () => { throw new Error('HTTP 500'); },
+ } as any;
+ const result = await synthesizeSkill({
+ botId: 'researcher', botName: 'Research', prompt: 'p', output: 'o',
+ toolsUsed: ['a', 'b', 'c'], provider: throwingProvider, skillsRoot: root,
+ });
+ expect(result).toBeNull();
+ });
+
+ it('threshold: a run must use at least 3 distinct tools to be worth synthesizing', () => {
+ expect(MIN_TOOLS_FOR_SYNTHESIS).toBe(3);
+ });
+});
\ No newline at end of file
diff --git a/src/bots/skill-synthesis.ts b/src/bots/skill-synthesis.ts
new file mode 100644
index 00000000..450a6047
--- /dev/null
+++ b/src/bots/skill-synthesis.ts
@@ -0,0 +1,81 @@
+import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { getMercuryHome } from '../utils/config.js';
+import { logger } from '../utils/logger.js';
+import type { BaseProvider } from '../providers/base.js';
+
+export interface SkillSynthesisInput {
+ botId: string;
+ botName: string;
+ /** The task the bot performed. */
+ prompt: string;
+ /** The bot's final summary. */
+ output: string;
+ /** Distinct tools used during the run (≥3 distinct = a procedure worth keeping). */
+ toolsUsed: string[];
+ provider: BaseProvider;
+ skillsRoot?: string;
+}
+
+export interface SynthesizedSkill {
+ name: string;
+ path: string;
+}
+
+export const MIN_TOOLS_FOR_SYNTHESIS = 3;
+
+function slugify(name: string): string {
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'skill';
+}
+
+/**
+ * Auto-skill synthesis (competitive-roadmap "self-improvement" wedge):
+ * after a bot completes a genuinely multi-step run, draft a reusable
+ * SKILL.md from the transcript — written with `draft: true` so it is
+ * reviewable, and never allowed to break or block the run that produced it.
+ */
+export async function synthesizeSkill(input: SkillSynthesisInput): Promise<SynthesizedSkill | null> {
+ const skillsRoot = resolve(input.skillsRoot ?? join(getMercuryHome(), 'skills'));
+ try {
+ const result = await input.provider.generateText(
+ `You distill a completed bot run into a reusable skill for the Mercury agent.
+
+Bot: ${input.botName} (${input.botId})
+Task: ${input.prompt.slice(0, 800)}
+Tools used: ${input.toolsUsed.join(', ')}
+Outcome summary:
+${input.output.slice(0, 2000)}
+
+Write the skill that captures the REUSABLE procedure (not this one instance). Rules:
+- Start with YAML frontmatter: name, description (one line, when to use), allowed-tools (comma-separated tool names actually needed), draft: true
+- Then markdown instructions: numbered steps, decision points, and failure handling.
+- The skill must generalize beyond this specific task instance.
+- 150-350 words. No preamble, no code fences around the whole file.`,
+ 'You write concise, procedural agent skills. Return ONLY the file content.',
+ );
+
+ const content = (result.text ?? '').trim();
+ if (!content || content.length < 80 || !content.startsWith('---')) {
+ logger.debug({ botId: input.botId }, 'Skill synthesis skipped: unusable model output');
+ return null;
+ }
+ // Pull the skill name out of the frontmatter for the directory slug.
+ const nameMatch = /^name:\s*(.+)$/m.exec(content);
+ const name = (nameMatch?.[1] ?? `${input.botId}-skill`).trim().slice(0, 60);
+ const slug = slugify(`${input.botId}-${name}`);
+ const dir = join(skillsRoot, 'bots', slug);
+ if (!dir.startsWith(resolve(skillsRoot) + '/')) return null; // traversal guard
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, 'SKILL.md');
+ if (!existsSync(path)) {
+ writeFileSync(path, content.endsWith('\n') ? content : content + '\n', 'utf-8');
+ logger.info({ botId: input.botId, path }, 'Auto-skill draft synthesized from bot run');
+ return { name, path };
+ }
+ logger.debug({ botId: input.botId, path }, 'Skill draft already exists — not overwritten');
+ return null;
+ } catch (err: any) {
+ logger.warn({ botId: input.botId, err: err?.message }, 'Auto-skill synthesis failed (non-fatal)');
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/src/core/agent.ts b/src/core/agent.ts
index b69b457c..49cd481b 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -650,35 +650,28 @@ export class Agent {
// Telegram, web). Durable enqueue; the run's output is delivered back
// to the requesting chat via the job's source (Telegram first).
if (trimmed.startsWith('/bot ')) {
- const bm = this.botManager;
- if (!bm) return; // bots not wired — fall through as a normal message
+ if (!this.botManager) return; // bots not wired — fall through as a normal message
const rest = trimmed.slice('/bot '.length).trim();
const spaceIndex = rest.indexOf(' ');
const botId = (spaceIndex === -1 ? rest : rest.slice(0, spaceIndex)).toLowerCase();
const message = spaceIndex === -1 ? '' : rest.slice(spaceIndex + 1).trim();
- if (!botId || !message) return;
- const channel = this.channels.getChannelForMessage(msg);
- if (!channel) 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;
- const inBotChat = pendingBot === botId;
- const replyTarget = inBotChat ? `bot:${botId}` : msg.channelId;
- const result = bm.enqueue(botId, {
- trigger: 'chat',
- prompt: message,
- source: { channelType: msg.channelType, channelId: replyTarget },
- });
- if (result.accepted) {
- void channel.send(`🤖 Queued for **${botId}** (job ${result.jobId}) — the reply will arrive in this chat.`, replyTarget)
- .catch((err) => logger.warn({ err }, '/bot ack send failed'));
- } else {
- void channel.send(`Could not message **${botId}**: [reason: ${result.reasonCode}]`, replyTarget)
- .catch((err) => logger.warn({ err }, '/bot ack send failed'));
+ if (botId && message) {
+ void this.dispatchToBot(botId, message, msg);
}
return;
}
+ // @<botId|name> <message> — mention-style routing (Telegram groups, etc.).
+ // Only intercepts when the first token resolves to a configured bot, so
+ // ordinary @-messages are never hijacked.
+ if (trimmed.startsWith('@') && this.botManager) {
+ const mention = this.parseBotMention(trimmed);
+ if (mention) {
+ void this.dispatchToBot(mention.botId, mention.message, msg);
+ return;
+ }
+ }
+
if (this.processing && trimmed.startsWith('/')) {
this.handleFastPathCommand(msg).catch((err) => {
logger.error({ err, content: trimmed.slice(0, 50) }, 'Fast-path command failed');
@@ -1088,6 +1081,46 @@ export class Agent {
await channel.send('Agent is busy. Programming mode changes will be available after current task completes.', msg.channelId);
}
+ /** Enqueue a bot turn from any channel, with ack + reply-back routing. */
+ private async dispatchToBot(botId: string, message: string, msg: ChannelMessage): Promise<void> {
+ const bm = this.botManager;
+ if (!bm) return;
+ const channel = this.channels.getChannelForMessage(msg);
+ if (!channel) 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;
+ const inBotChat = pendingBot === botId;
+ const replyTarget = inBotChat ? `bot:${botId}` : msg.channelId;
+ const result = bm.enqueue(botId, {
+ trigger: 'chat',
+ prompt: message,
+ source: { channelType: msg.channelType, channelId: replyTarget },
+ });
+ if (result.accepted) {
+ await channel.send(`🤖 Queued for **${botId}** (job ${result.jobId}) — the reply will arrive in this chat.`, replyTarget)
+ .catch((err) => logger.warn({ err }, '/bot ack send failed'));
+ } else {
+ await channel.send(`Could not message **${botId}**: [reason: ${result.reasonCode}]`, replyTarget)
+ .catch((err) => logger.warn({ err }, '/bot ack send failed'));
+ }
+ }
+
+ /**
+ * Parse `@<botId|Name> <message>` into a bot routing when the first token
+ * resolves to a configured bot; null for any other @-message.
+ */
+ private parseBotMention(content: string): { botId: string; message: string } | null {
+ const bm = this.botManager;
+ if (!bm) return null;
+ const firstSpace = content.indexOf(' ');
+ const token = (firstSpace === -1 ? content : content.slice(0, firstSpace)).replace(/^@/, '').trim();
+ const message = firstSpace === -1 ? '' : content.slice(firstSpace + 1).trim();
+ if (!token || !message) return null;
+ const botId = bm.resolveBotId(token);
+ return botId ? { botId, message } : null;
+ }
+
/**
* /bots — Mercury Bots control surface (BOTS-ARCHITECTURE.md §2.7).
* Always fast-path: bots live outside the main message queue, so bot
diff --git a/src/index.ts b/src/index.ts
index 80edbee9..f1cea8d5 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -81,7 +81,7 @@ import { selectWithArrowKeys } from './utils/arrow-select.js';
import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/provider-models.js';
import { initCloudTokenStore } from './cloud/token-store.js';
import { clearCloudRuntimeOnline, markCloudRuntimeOnline } from './cloud/runtime-status.js';
-import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager } from './web/server.js';
+import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret } from './web/server.js';
import { isWebAuthInitialized, setWebPassword, writeAttachToken } from './web/auth.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -2489,6 +2489,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
botManager.registerRoutines(scheduler);
agent.setBotManager(botManager);
setWebBotManager(botManager);
+ if (config.bots?.webhookSecret) {
+ setBotsWebhookSecret(config.bots.webhookSecret);
+ }
}
let spotifyClient: SpotifyClient | undefined;
diff --git a/src/utils/config.ts b/src/utils/config.ts
index 2795f7bb..ba020b6e 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -200,6 +200,12 @@ export interface MercuryConfig {
enabled: boolean;
/** 0 = auto (clamp(2, cpus-1)). Fleet-wide cap on concurrent bot turns. */
maxConcurrent: number;
+ /** Shared secret for POST /api/bots/:id/hooks/* (unset = session auth only). */
+ webhookSecret?: string;
+ /** Auto-skill synthesis: draft SKILL.md from completed multi-step bot runs. */
+ autoSkill?: {
+ enabled?: boolean;
+ };
retention: {
transcriptRuns: number;
journalRotateBytes: number;
@@ -458,6 +464,10 @@ export function getDefaultConfig(): MercuryConfig {
bots: {
enabled: getEnvBool('BOTS_ENABLED', true),
maxConcurrent: getEnvNum('BOTS_MAX_CONCURRENT', 0),
+ webhookSecret: getEnv('BOTS_WEBHOOK_SECRET') || undefined,
+ autoSkill: {
+ enabled: getEnvBool('BOTS_AUTO_SKILL', false),
+ },
retention: {
transcriptRuns: getEnvNum('BOTS_RETENTION_TRANSCRIPT_RUNS', 50),
journalRotateBytes: getEnvNum('BOTS_JOURNAL_ROTATE_BYTES', 5 * 1024 * 1024),
diff --git a/src/web/api/bots.ts b/src/web/api/bots.ts
index 14910d88..c4179f9f 100644
--- a/src/web/api/bots.ts
+++ b/src/web/api/bots.ts
@@ -5,11 +5,17 @@ import type { BotManifest } from '../../bots/types.js';
const app = new Hono();
let botManager: BotManager | undefined;
+let webhookSecret: string | undefined;
export function setBotManager(bm: BotManager | undefined): void {
botManager = bm;
}
+/** Shared secret for bot webhook ingress; unset = auth via the web session only. */
+export function setBotsWebhookSecret(secret: string | undefined): void {
+ webhookSecret = secret;
+}
+
// Fleet roster with live states
app.get('/api/bots', (c: any) => {
if (!botManager) {
@@ -175,4 +181,42 @@ app.delete('/api/bots/:id', (c: any) => {
}
});
+// Generic webhook ingress: validate → dedupe → durable enqueue, ack fast
+// (BOTS-ARCHITECTURE §2.3). Callers: external systems pushing events into a
+// bot (e.g. an RSS monitor or CI pipeline waking the researcher bot).
+app.post('/api/bots/:id/hooks/:hook', async (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ // Auth: shared secret header when configured (webhook callers have no
+ // browser session); otherwise the normal authGuard already applied.
+ if (webhookSecret) {
+ const provided = c.req.header('x-mercury-hook-secret');
+ if (provided !== webhookSecret) {
+ return c.json({ error: 'Invalid hook secret' }, 401);
+ }
+ }
+ let text: string;
+ if (contentTypeIsJson(c.req.header('content-type'))) {
+ const body = await c.req.json().catch(() => null);
+ if (!body) return c.json({ error: 'Invalid JSON body' }, 400);
+ text = typeof body.text === 'string' ? body.text : JSON.stringify(body);
+ } else {
+ text = await c.req.text();
+ }
+ if (!text.trim()) return c.json({ error: 'Empty payload' }, 400);
+ // Idempotency: an explicit event id joins the prompt, so the queue's
+ // idempotency key dedupes redeliveries of the same event.
+ const eventId = c.req.header('x-event-id');
+ const prompt = eventId ? `[hook:${c.req.param('hook')}:${eventId}] ${text}` : `[hook:${c.req.param('hook')}] ${text}`;
+ const result = botManager.enqueue(id, { trigger: 'api', prompt });
+ if (!result.accepted) {
+ return c.json({ accepted: false, reasonCode: result.reasonCode }, 409);
+ }
+ return c.json({ accepted: true, jobId: result.jobId, status: 'accepted' }, 202);
+});
+
+function contentTypeIsJson(value: string | undefined): boolean {
+ return (value ?? '').split(';')[0].trim().toLowerCase() === 'application/json';
+}
+
export default app;
\ No newline at end of file
diff --git a/src/web/server.ts b/src/web/server.ts
index f06a48f1..3d88b031 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -14,7 +14,7 @@ import systemRoutes, { setScheduler } from './api/system.js';
import brainRoutes, { setUserMemory } from './api/brain.js';
import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setSessionRepository, setSessionSyncEnabledCallback } from './api/chat.js';
import agentRoutes, { setAgentSupervisor, setBackgroundTaskManager } from './api/agents.js';
-import botsRoutes, { setBotManager } from './api/bots.js';
+import botsRoutes, { setBotManager, setBotsWebhookSecret } from './api/bots.js';
import spotifyRoutes, { setSpotifyClient } from './api/spotify.js';
import kanbanRoutes, { setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders } from './api/kanban.js';
import ideRoutes, { setIDEProviders } from './api/workspace-ide.js';
@@ -193,7 +193,7 @@ if (spaAvailable) {
});
}
-export { updateStatus, setUserMemory, setWebChannel, setScheduler, setAgentSupervisor, setBackgroundTaskManager, setSpotifyClient, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders, setIDEProviders, setBotManager };
+export { updateStatus, setUserMemory, setWebChannel, setScheduler, setAgentSupervisor, setBackgroundTaskManager, setSpotifyClient, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders, setIDEProviders, setBotManager, setBotsWebhookSecret };
let webServer: ReturnType<typeof createAdaptorServer> | null = null;
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index c1655289..29f5b5f9 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -18,6 +18,7 @@ const ProvidersPage = lazy(() => import("./pages/Providers").then((m) => ({ defa
const SkillsPage = lazy(() => import("./pages/Skills").then((m) => ({ default: m.SkillsPage })));
const PermissionsPage = lazy(() => import("./pages/Permissions").then((m) => ({ default: m.PermissionsPage })));
const SchedulesPage = lazy(() => import("./pages/Schedules").then((m) => ({ default: m.SchedulesPage })));
+const BotsPage = lazy(() => import("./pages/Bots").then((m) => ({ default: m.BotsPage })));
const UsagePage = lazy(() => import("./pages/Usage").then((m) => ({ default: m.UsagePage })));
const SettingsPage = lazy(() => import("./pages/Settings").then((m) => ({ default: m.SettingsPage })));
const WorkspacePage = lazy(() => import("./pages/Workspace").then((m) => ({ default: m.WorkspacePage })));
@@ -79,6 +80,7 @@ function AnimatedRoutes() {
<Route path="skills" element={<AnimatedPage><SkillsPage /></AnimatedPage>} />
<Route path="permissions" element={<AnimatedPage><PermissionsPage /></AnimatedPage>} />
<Route path="schedules" element={<AnimatedPage><SchedulesPage /></AnimatedPage>} />
+ <Route path="bots" element={<AnimatedPage><BotsPage /></AnimatedPage>} />
<Route path="usage" element={<AnimatedPage><UsagePage /></AnimatedPage>} />
<Route path="settings" element={<AnimatedPage><SettingsPage /></AnimatedPage>} />
diff --git a/ui/src/components/layout/Sidebar.tsx b/ui/src/components/layout/Sidebar.tsx
index 9baba9f0..a072e146 100644
--- a/ui/src/components/layout/Sidebar.tsx
+++ b/ui/src/components/layout/Sidebar.tsx
@@ -14,6 +14,7 @@ import {
Share2,
Cpu,
+ Bot,
Puzzle,
Shield,
Clock,
@@ -63,6 +64,7 @@ const NAV_SECTIONS = [
{ to: "/skills", icon: Puzzle, label: "Skills" },
{ to: "/permissions", icon: Shield, label: "Permissions" },
{ to: "/schedules", icon: Clock, label: "Schedules" },
+ { to: "/bots", icon: Bot, label: "Bots" },
{ to: "/usage", icon: BarChart3, label: "Usage" },
],
},
diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts
index e91db3fa..198fcbf5 100644
--- a/ui/src/lib/api.ts
+++ b/ui/src/lib/api.ts
@@ -642,6 +642,52 @@ export interface BgTask {
completedAt?: string;
}
+// ── Mercury Bots ──
+export interface BotStatus {
+ id: string;
+ name: string;
+ enabled: boolean;
+ state: "disabled" | "idle" | "queued" | "running" | "paused";
+ activity?: string;
+ lastRunAt?: number;
+ lastRunState?: string;
+ needsYou: boolean;
+}
+
+export interface BotManifest {
+ id: string;
+ name: string;
+ description?: string;
+ enabled: boolean;
+ model?: { provider?: string; model?: string };
+ memory?: { scope: string };
+ comms?: { canMessage?: string[] };
+ schedules?: Array<{ name: string; cron: string; prompt: string }>;
+ autonomy?: { maxSteps?: number; dailyTokenBudget?: number };
+}
+
+export interface BotRunRecord {
+ runId: string;
+ botId: string;
+ trigger: string;
+ state: string;
+ startedAt: number;
+ durationMs: number;
+ tokensIn: number;
+ tokensOut: number;
+ summary?: string;
+ reasonCode?: string;
+}
+
+export interface BotDlqEntry {
+ id: string;
+ botId: string;
+ trigger: string;
+ prompt: string;
+ attempts: number;
+ reasonCode?: string;
+}
+
export interface Skill {
name: string;
path: string;
@@ -795,6 +841,23 @@ const api = {
schedules,
spotify,
boards,
+ bots: {
+ list: () => get<{ bots: BotStatus[]; available: boolean }>("/api/bots"),
+ get: (id: string) =>
+ get<{ bot: BotManifest; state: BotStatus | null; journal: BotRunRecord[]; inbox: unknown[] }>(`/api/bots/${id}`),
+ create: (body: { id: string; name: string; description?: string }) =>
+ post<{ bot: BotManifest }>("/api/bots", body),
+ message: (id: string, message: string) =>
+ post<{ accepted: boolean; jobId?: string; reasonCode?: string }>(`/api/bots/${id}/message`, { message }),
+ patch: (id: string, body: Partial<BotManifest>) => patch<unknown>(`/api/bots/${id}`, body),
+ enable: (id: string) => post<{ ok: boolean }>(`/api/bots/${id}/enable`),
+ disable: (id: string) => post<{ ok: boolean }>(`/api/bots/${id}/disable`),
+ stop: (id: string) => post<{ ok: boolean }>(`/api/bots/${id}/stop`),
+ dlq: (id: string) => get<{ dlq: BotDlqEntry[] }>(`/api/bots/${id}/dlq`),
+ replay: (id: string, jobId: string) => post<{ accepted: boolean }>(`/api/bots/${id}/replay/${jobId}`),
+ storage: () =>
+ get<{ usage: Array<{ id: string; bytes: number; journalBytes: number }>; queue: { pending: number; claimed: number; dlq: number } }>("/api/bots-storage"),
+ },
};
export default api;
diff --git a/ui/src/pages/Bots.tsx b/ui/src/pages/Bots.tsx
new file mode 100644
index 00000000..56809b97
--- /dev/null
+++ b/ui/src/pages/Bots.tsx
@@ -0,0 +1,301 @@
+import { useEffect, useState, useCallback } from "react";
+import { motion } from "framer-motion";
+import { Bot, Plus, Send, RefreshCw, Trash2, Play, Pause, RotateCcw, RotateCw, AlertTriangle } from "lucide-react";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import {
+ Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
+} from "@/components/ui/dialog";
+import { cn, formatDate } from "@/lib/utils";
+import api, { type BotStatus, type BotManifest, type BotRunRecord, type BotDlqEntry } from "@/lib/api";
+
+const fadeUp = {
+ hidden: { opacity: 0, y: 12 },
+ visible: (i: number) => ({
+ opacity: 1, y: 0,
+ transition: { delay: i * 0.07, duration: 0.35, ease: "easeOut" as const },
+ }),
+};
+
+const STATE_STYLES: Record<string, { label: string; className: string }> = {
+ running: { label: "🟢 Running", className: "bg-emerald-500/15 text-emerald-500" },
+ queued: { label: "🔵 Queued", className: "bg-blue-500/15 text-blue-500" },
+ paused: { label: "🟡 Paused", className: "bg-yellow-500/15 text-yellow-500" },
+ disabled: { label: "⛔ Disabled", className: "bg-muted text-muted-foreground" },
+ idle: { label: "⚪ Idle", className: "bg-muted text-muted-foreground" },
+};
+
+function Skeleton({ className }: { className?: string }) {
+ return <div className={cn("animate-pulse rounded-lg bg-muted", className)} />;
+}
+
+export function BotsPage() {
+ const [botsList, setBotsList] = useState<BotStatus[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [available, setAvailable] = useState(true);
+ const [selected, setSelected] = useState<string | null>(null);
+ const [detail, setDetail] = useState<{ bot: BotManifest; journal: BotRunRecord[]; inbox: unknown[] } | null>(null);
+ const [dlq, setDlq] = useState<BotDlqEntry[]>([]);
+ const [message, setMessage] = useState("");
+ const [creating, setCreating] = useState(false);
+ const [newId, setNewId] = useState("");
+ const [newName, setNewName] = useState("");
+ const [newDescription, setNewDescription] = useState("");
+ const [error, setError] = useState<string | null>(null);
+
+ const refresh = useCallback(async () => {
+ try {
+ const data = await api.bots.list();
+ setBotsList(data.bots);
+ setAvailable(data.available);
+ } catch {
+ setAvailable(false);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ const openDetail = useCallback(async (id: string) => {
+ setSelected(id);
+ try {
+ const [detail, dlqData] = await Promise.all([api.bots.get(id), api.bots.dlq(id)]);
+ setDetail(detail);
+ setDlq(dlqData.dlq);
+ } catch (err) {
+ setError(String(err));
+ }
+ }, []);
+
+ useEffect(() => {
+ void refresh();
+ const t = setInterval(() => void refresh(), 4000); // live roster states
+ return () => clearInterval(t);
+ }, [refresh]);
+
+ const sendMessage = async () => {
+ if (!selected || !message.trim()) return;
+ try {
+ const result = await api.bots.message(selected, message.trim());
+ if (result.accepted) {
+ setMessage("");
+ setTimeout(() => void openDetail(selected), 400);
+ } else {
+ setError(`Rejected: ${result.reasonCode}`);
+ }
+ } catch (err) {
+ setError(String(err));
+ }
+ };
+
+ const createBot = async () => {
+ try {
+ await api.bots.create({ id: newId.toLowerCase(), name: newName, description: newDescription || undefined });
+ setCreating(false);
+ setNewId(""); setNewName(""); setNewDescription("");
+ void refresh();
+ } catch (err) {
+ setError(String(err));
+ }
+ };
+
+ const toggleEnabled = async (bot: BotStatus) => {
+ await (bot.enabled ? api.bots.disable(bot.id) : api.bots.enable(bot.id));
+ void refresh();
+ };
+
+ const replay = async (entry: BotDlqEntry) => {
+ try {
+ await api.bots.replay(entry.botId, entry.id);
+ if (selected) void openDetail(selected);
+ } catch (err) {
+ setError(String(err));
+ }
+ };
+
+ return (
+ <div className="space-y-6 p-6">
+ <div className="flex items-center justify-between">
+ <div>
+ <h1 className="text-2xl font-semibold flex items-center gap-2"><Bot className="h-6 w-6" /> Bots</h1>
+ <p className="text-sm text-muted-foreground">
+ Persistent persona-scoped agents — own model, memory, and permissions; run outside the main conversation.
+ </p>
+ </div>
+ <div className="flex gap-2">
+ <Button variant="outline" size="sm" onClick={() => void refresh()}><RefreshCw className="h-4 w-4" /> Refresh</Button>
+ <Button size="sm" onClick={() => setCreating(true)}><Plus className="h-4 w-4" /> Onboard bot</Button>
+ </div>
+ </div>
+
+ {error && (
+ <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-2 text-sm text-destructive">{error}</div>
+ )}
+
+ {!available && (
+ <Card><CardContent className="py-8 text-center text-muted-foreground">
+ Bots are not available on this instance (config.bots.enabled is off).
+ </CardContent></Card>
+ )}
+
+ {loading ? (
+ <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
+ {[0, 1, 2].map(i => <Skeleton key={i} className="h-28" />)}
+ </div>
+ ) : botsList.length === 0 ? (
+ <Card><CardContent className="py-8 text-center text-muted-foreground">
+ No bots configured yet. Onboard one to get started.
+ </CardContent></Card>
+ ) : (
+ <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
+ {botsList.map((bot, i) => (
+ <motion.div key={bot.id} custom={i} variants={fadeUp} initial="hidden" animate="visible">
+ <Card
+ className="cursor-pointer transition-colors hover:border-primary/50"
+ onClick={() => void openDetail(bot.id)}
+ >
+ <CardHeader className="pb-2">
+ <div className="flex items-center justify-between">
+ <CardTitle className="flex items-center gap-2 text-base">
+ <Bot className="h-4 w-4" /> {bot.name}
+ </CardTitle>
+ <Badge variant="secondary" className={STATE_STYLES[bot.state]?.className}>
+ {STATE_STYLES[bot.state]?.label ?? bot.state}
+ </Badge>
+ </div>
+ </CardHeader>
+ <CardContent className="space-y-2 text-sm">
+ {bot.activity && <p className="text-muted-foreground truncate">↳ {bot.activity}</p>}
+ {bot.needsYou && (
+ <p className="flex items-center gap-1 text-yellow-500"><AlertTriangle className="h-3.5 w-3.5" /> Needs you — see DLQ</p>
+ )}
+ {bot.lastRunAt && (
+ <p className="text-muted-foreground">Last run {formatDate(bot.lastRunAt)} · {bot.lastRunState}</p>
+ )}
+ </CardContent>
+ </Card>
+ </motion.div>
+ ))}
+ </div>
+ )}
+
+ {/* Detail dialog: config, send, journal, DLQ */}
+ <Dialog open={!!selected} onOpenChange={(o) => { if (!o) { setSelected(null); setDetail(null); } }}>
+ <DialogContent className="max-h-[80vh] max-w-2xl overflow-y-auto">
+ {detail && (
+ <>
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Bot className="h-5 w-5" /> {detail.bot.name} <span className="text-muted-foreground text-sm">({detail.bot.id})</span>
+ </DialogTitle>
+ <DialogDescription>{detail.bot.description ?? "Mercury bot"}</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div className="flex flex-wrap gap-2 text-sm">
+ <Badge variant="secondary">model: {detail.bot.model?.provider ?? "inherit"}{detail.bot.model?.model ? `:${detail.bot.model.model}` : ""}</Badge>
+ <Badge variant="secondary">memory: {detail.bot.memory?.scope ?? "own"}</Badge>
+ {detail.bot.autonomy?.dailyTokenBudget && <Badge variant="secondary">budget: {detail.bot.autonomy.dailyTokenBudget}/day</Badge>}
+ {(detail.bot.comms?.canMessage?.length ?? 0) > 0 && <Badge variant="secondary">→ {detail.bot.comms!.canMessage!.join(", ")}</Badge>}
+ </div>
+
+ {(detail.bot.schedules?.length ?? 0) > 0 && (
+ <div className="text-sm">
+ <p className="font-medium mb-1">Routines</p>
+ {detail.bot.schedules!.map(s => (
+ <p key={s.name} className="text-muted-foreground">⏰ {s.name} — <code>{s.cron}</code></p>
+ ))}
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <Textarea
+ placeholder={`Message ${detail.bot.name}… (runs outside the main conversation)`}
+ value={message}
+ onChange={(e) => setMessage(e.target.value)}
+ rows={3}
+ />
+ <div className="flex gap-2">
+ <Button size="sm" onClick={() => void sendMessage()} disabled={!message.trim()}>
+ <Send className="h-3.5 w-3.5" /> Send
+ </Button>
+ <Button
+ size="sm" variant="outline"
+ onClick={async () => { await (detail.bot.enabled ? api.bots.disable(detail.bot.id) : api.bots.enable(detail.bot.id)); void openDetail(detail.bot.id); void refresh(); }}
+ >
+ {detail.bot.enabled ? <><Pause className="h-3.5 w-3.5" /> Disable</> : <><Play className="h-3.5 w-3.5" /> Enable</>}
+ </Button>
+ <Button size="sm" variant="outline" onClick={async () => { await api.bots.stop(detail.bot.id); void openDetail(detail.bot.id); }}>
+ Stop
+ </Button>
+ </div>
+ </div>
+
+ <div>
+ <p className="font-medium text-sm mb-2">Recent runs</p>
+ {detail.journal.length === 0 ? (
+ <p className="text-sm text-muted-foreground">No runs yet.</p>
+ ) : (
+ <div className="space-y-1.5">
+ {[...detail.journal].reverse().map(r => (
+ <div key={r.runId} className="flex items-center gap-2 text-sm">
+ <Badge variant="secondary" className={
+ r.state === "completed" ? "bg-emerald-500/15 text-emerald-500"
+ : r.state === "failed" ? "bg-red-500/15 text-red-500"
+ : "bg-yellow-500/15 text-yellow-500"
+ }>{r.state}</Badge>
+ <span className="text-muted-foreground">{r.trigger}</span>
+ <span>{(r.durationMs / 1000).toFixed(1)}s</span>
+ <span className="text-muted-foreground">{r.tokensIn + r.tokensOut} tok</span>
+ {r.reasonCode && <span className="text-red-500">[{r.reasonCode}]</span>}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {dlq.length > 0 && (
+ <div>
+ <p className="font-medium text-sm mb-2 flex items-center gap-1"><AlertTriangle className="h-4 w-4 text-yellow-500" /> Dead-lettered jobs</p>
+ <div className="space-y-1.5">
+ {dlq.map(e => (
+ <div key={e.id} className="flex items-center gap-2 text-sm">
+ <span className="text-muted-foreground font-mono">{e.id}</span>
+ <span className="text-red-500">[{e.reasonCode ?? "unknown"}]</span>
+ <span className="text-muted-foreground truncate flex-1">{e.prompt.slice(0, 60)}</span>
+ <Button size="sm" variant="ghost" onClick={() => void replay(e)}><RotateCw className="h-3.5 w-3.5" /> Replay</Button>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+
+ {/* Onboard dialog */}
+ <Dialog open={creating} onOpenChange={setCreating}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>Onboard a bot</DialogTitle>
+ <DialogDescription>
+ Fail-closed defaults: dangerous tools denied, memory scope own, only its own directory writable. Refine in the profile files afterwards.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-3">
+ <Input placeholder="id (lowercase, e.g. researcher)" value={newId} onChange={e => setNewId(e.target.value)} />
+ <Input placeholder="Name (e.g. Research)" value={newName} onChange={e => setNewName(e.target.value)} />
+ <Input placeholder="Description (optional)" value={newDescription} onChange={e => setNewDescription(e.target.value)} />
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setCreating(false)}>Cancel</Button>
+ <Button onClick={() => void createBot()} disabled={!newId || !newName}><Trash2 className="hidden" /> Create</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
\ No newline at end of file