Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): onboard a bot from Telegram with the full TUI flow — persona, tier, fleet, budget as native choices
Salman Qureshie733a46abe9f
diff --git a/.lint-baseline.json b/.lint-baseline.jsonindex efdf5e2c..73b00afe 100644--- a/.lint-baseline.json+++ b/.lint-baseline.json@@ -1,7 +1,7 @@{"$comment": "ESLint ratchet baseline. Per-rule counts (errors + warnings) may only go down. Refresh with `npm run lint:ratchet -- --update` after a clean-up.","provisional": false,- "generatedAt": "2026-10-10T16:18:00.110Z",+ "generatedAt": "2026-10-10T16:59:09.838Z","target": "src","rules": {"(unknown)": 1,diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d4cf47b7..73cc6924 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased — bots in your pocket (ADR-023)+- **Onboarding from Telegram.** `/bots create <id> "Name" "Description"` in Telegram (or the web chat) now runs the same flow as the TUI: your next message is the persona (keep as-is or convert to the template), then permissions tier, solo vs fleet, and the daily budget — each a tap on Telegram's native buttons that settle in place. Every reply lands in the chat that asked; nothing is lost to the TUI-only bot thread any more.- **Telegram controls.** `/bots` and `/bot` are in Telegram's command menu; the roster arrives with buttons — Stop/Start, Run and Runs per bot, plus Cost, Outputs, Doctor and Stop all for the fleet. A tap runs the slash command behind it as if you had typed it (same permissions, same reply). `/bots outputs` carries a 📎 button per delivered file.- **Files, not paths.** A task asked for from Telegram (or any remote chat) comes back with its delivered files attached. `/bots fetch <id> [name|latest]` sends one on demand.- **`/bots doctor`** runs the fleet health check from any chat; **`/bots help`** lists the commands. The TUI's slash completion, the busy-mode `/help`, and the docs now list every `/bots` subcommand.diff --git a/src/core/agent.ts b/src/core/agent.tsindex 46485d9f..d65fb2cc 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -545,6 +545,8 @@ export class Agent {botManager?: import('../bots/bot-manager.js').BotManager;/** Bot awaiting a persona from the next message (post-create setup flow). */pendingPersonaFor: string | null = null;+ /** The chat whose next message is the persona (Telegram/web/Discord — channels without a bot thread). */+ pendingPersonaChannelId: string | null = null;/** True while the pending persona capture belongs to a JUST-created bot —* gates the fleet (solo vs lead) onboarding step in finalizePersona. */pendingPersonaNewlyCreated = false;@@ -704,6 +706,31 @@ export class Agent {const trimmed = msg.content.trim();+ // Onboarding from a chat without a bot thread (Telegram, web, Discord):+ // the next plain message in THAT chat is the new bot's persona — same+ // state machine as the TUI, same choices, just addressed to the chat+ // that asked. A slash command means the owner moved on.+ if (this.pendingPersonaFor && this.pendingPersonaChannelId === msg.channelId && this.botManager) {+ const botId = this.pendingPersonaFor;+ const channel = this.channels.getChannelForMessage(msg);+ if (trimmed.toLowerCase() === '/skip') {+ this.pendingPersonaFor = null;+ this.pendingPersonaChannelId = null;+ channel?.send(`⏭ Keeping the starter persona — change it anytime with \`/bots persona ${botId} <text>\`.`, msg.channelId).catch(() => {});+ return;+ }+ if (trimmed.startsWith('/')) {+ this.pendingPersonaFor = null;+ this.pendingPersonaChannelId = null;+ } else if (channel) {+ this.pendingPersonaChannelId = null;+ this.finalizePersona(this.botManager, botId, trimmed, msg, this.pendingPersonaNewlyCreated).catch((err) => {+ logger.warn({ err, botId }, 'Persona onboarding failed');+ });+ return;+ }+ }+// Mercury Bots never touch the main message queue — /bots is always// fast-path, whether the main loop is busy or idle.if (trimmed.startsWith('/bots')) {@@ -1096,6 +1123,7 @@ export class Agent {const manifest = bm.store.get(botId);if (!channel || !manifest) return;const channelType = msg.channelType as any;+ const target = this.onboardingTarget(botId, msg, channel);let choice = 'template';try {@@ -1122,7 +1150,7 @@ export class Agent {if (choice.startsWith('Convert')) {// The builder is an LLM call (10-60s on slower providers) — the user// must see it is working, or onboarding reads as a hang.- await channel.send('⏳ Running the persona builder — structuring your text (typically 10–60s)…', `bot:${botId}`).catch(() => {});+ await channel.send('⏳ Running the persona builder — structuring your text (typically 10–60s)…', target).catch(() => {});(channel as any).sendHeartbeat?.('⏳ Persona builder running…');const refined = await refinePersona(raw, manifest.name, this.providers.getDefault());(channel as any).clearHeartbeat?.();@@ -1137,7 +1165,7 @@ export class Agent {bm.invalidateRuntime(botId);this.pendingPersonaFor = null;const mode = finalPersona === raw ? 'as-is' : 'as a structured template';- await channel.send(`✍️ Persona saved ${mode}.`, `bot:${botId}`).catch(() => {});+ await channel.send(`✍️ Persona saved ${mode}.`, target).catch(() => {});// New-bot onboarding: permission tier, then solo vs fleet (edits later never ask).if (newlyCreated) {@@ -1148,6 +1176,10 @@ export class Agent {// Final onboarding step: the daily token budget. Every bot has one// (ADR-020) — the presets are sizes, not a yes/no.const standard = this.config.bots?.suggestedDailyTokenBudget ?? 5_000_000;+ if (channel.type !== 'cli') {+ await this.offerBudgetChoice(bm, botId, manifest.name, msg, channel, standard);+ return;+ }this.pendingBudgetFor = botId;const home = homedir();const folder = bm.store.deliverablesDir(botId);@@ -1159,21 +1191,59 @@ export class Agent {`• a number, or \`none\` for no cap\n` +`When the cap is hit the bot pauses until tomorrow; you are warned at 80%. Change anytime: \`/bots budget ${botId} <tokens|suggest|none>\`.\n` +`📁 Its results will appear in \`${folder.startsWith(home) ? '~' + folder.slice(home.length) : folder}\` (\`/bots folder ${botId}\` opens it).`,- `bot:${botId}`,+ target,).catch(() => {});}+ /**+ * Where onboarding talks: the bot's own thread in the TUI, the chat that+ * asked everywhere else (Telegram cannot resolve `bot:<id>`).+ */+ private onboardingTarget(botId: string, msg: ChannelMessage, channel: { type?: string }): string {+ return channel.type === 'cli' ? `bot:${botId}` : msg.channelId;+ }++ /** Budget step as buttons (Telegram/web): sizes, not a typed keyword. */+ private async offerBudgetChoice(bm: import('../bots/bot-manager.js').BotManager, botId: string, botName: string, msg: ChannelMessage, channel: { send: (text: string, target?: string) => Promise<void> }, standard: number): Promise<void> {+ const home = homedir();+ const folder = bm.store.deliverablesDir(botId);+ const options = [+ `Standard — ${standard.toLocaleString()}/day (recommended)`,+ 'Light — 1M/day',+ 'Heavy — 20M/day',+ 'No cap',+ ];+ let choice = options[0];+ try {+ choice = await this.presentChoice(+ `Last step — how much may **${botName}** spend per day? When the cap is hit it pauses until tomorrow (warned at 80%). Change anytime: \`/bots budget ${botId} <tokens|suggest|none>\`.\n📁 Results will appear in \`${folder.startsWith(home) ? '~' + folder.slice(home.length) : folder}\`.`,+ options,+ msg.channelId,+ msg.channelType,+ );+ } catch {+ choice = options[0];+ }+ const keyword = choice.startsWith('Light') ? 'light' : choice.startsWith('Heavy') ? 'heavy' : choice.startsWith('No cap') ? 'none' : 'standard';+ this.pendingBudgetFor = botId;+ await this.applyBudgetAnswer(bm, botId, keyword, msg);+ await channel.send(`✅ **${botName}** is ready. Give it work with \`/bot ${botId} <task>\` or \`@${botId} <task>\` — results come back here, with the files.`, msg.channelId).catch(() => {});+ }+/*** Permission-tier onboarding step (new bots only): one clear question* instead of silent fail-closed defaults + manual file editing. Change* anytime with `/bots permissions <id> <tier>`.*/private async offerPermissionTier(bm: import('../bots/bot-manager.js').BotManager, botId: string, botName: string, msg: ChannelMessage, channel: any): Promise<void> {+ const target = this.onboardingTarget(botId, msg, channel);let choice = 'Read-only (recommended default)';try {choice = await this.presentChoice(- `What should **${botName}** be allowed to do? (Path scopes always stay fail-closed — a tool only reaches what its Access grants cover.)`,- Object.values(PERMISSION_TIERS).map(t => `${t.label} — ${t.description}`),+ `What should **${botName}** be allowed to do?\n` ++ Object.values(PERMISSION_TIERS).map(t => `• **${t.label}** — ${t.description}`).join('\n') ++ '\n(Path scopes always stay fail-closed — a tool only reaches what its Access grants cover.)',+ Object.values(PERMISSION_TIERS).map(t => t.label),msg.channelId,msg.channelType as any,);@@ -1188,7 +1258,7 @@ export class Agent {bm.store.writePermissions(botId, tierPermissionsFile(tier));bm.store.update(botId, m => { delete (m as any).tools; });bm.invalidateRuntime(botId);- await channel.send(`🔐 Permissions for **${botName}**: **${PERMISSION_TIERS[tier].label}**. Change anytime with \`/bots permissions ${botId} <readonly|builder|operator|full>\`.`, `bot:${botId}`).catch(() => {});+ await channel.send(`🔐 Permissions for **${botName}**: **${PERMISSION_TIERS[tier].label}**. Change anytime with \`/bots permissions ${botId} <readonly|builder|operator|full>\`.`, target).catch(() => {});}/**@@ -1197,6 +1267,7 @@ export class Agent {* budget step follows either way.*/async offerFleetStep(bm: import('../bots/bot-manager.js').BotManager, botId: string, botName: string, msg: ChannelMessage, channel: any): Promise<void> {+ const target = this.onboardingTarget(botId, msg, channel);let choice = 'Solo bot';try {choice = await this.presentChoice(@@ -1219,7 +1290,7 @@ export class Agent {`👑 **${botName}** is now a fleet lead. Add specialists anytime:\n` +`\`/bots add-crew ${botId} <id> "Name" "Description" "persona (optional)"\`\n` +`Review the fleet with \`/bots crew ${botId}\` — or just tell **${botName}** to hire its own crew (it has bot_spawn).`,- `bot:${botId}`,+ target,).catch(() => {});return;}@@ -1227,7 +1298,7 @@ export class Agent {// Auto-build: one LLM proposal, created through the standard path. This// is an LLM call (30-90s) — it must NOT hold onboarding hostage: run it// detached with visible progress, and deliver the roster when ready.- await channel.send(`👑 **${botName}** is now a fleet lead — building the crew in the background…`, `bot:${botId}`).catch(() => {});+ await channel.send(`👑 **${botName}** is now a fleet lead — building the crew in the background…`, target).catch(() => {});(channel as any).sendHeartbeat?.('⏳ Proposing fleet crew (up to ~90s)…');const persona = bm.store.readPersona(botId);const leadDescription = bm.store.get(botId)?.description ?? '';@@ -1236,7 +1307,7 @@ export class Agent {const proposals = await proposeCrew(botName, leadDescription, persona, this.providers.getDefault(), bm.maxCrew());(channel as any).clearHeartbeat?.();if (proposals.length === 0) {- await channel.send(`⚠ Crew proposal unavailable (provider) — **${botName}** is a lead with an empty crew. Add members with \`/bots add-crew ${botId} <id> "Name" "Description" "persona"\` or tell the lead to hire its own.`, `bot:${botId}`).catch(() => {});+ await channel.send(`⚠ Crew proposal unavailable (provider) — **${botName}** is a lead with an empty crew. Add members with \`/bots add-crew ${botId} <id> "Name" "Description" "persona"\` or tell the lead to hire its own.`, target).catch(() => {});return;}const lines: string[] = [`👑 **${botName}** fleet ready — ${proposals.length} crew member(s) created:`, ''];@@ -1251,10 +1322,10 @@ export class Agent {}}lines.push('', 'Dispatch tasks with `/bot <crewId> <task>` or tell the lead to delegate — it can also spawn more crew itself.');- await channel.send(lines.join('\n'), `bot:${botId}`).catch(() => {});+ await channel.send(lines.join('\n'), target).catch(() => {});} catch (err: any) {(channel as any).clearHeartbeat?.();- await channel.send(`⚠ Fleet auto-build failed: ${err?.message ?? err} — **${botName}** is a lead with an empty crew; add members with \`/bots add-crew ${botId} <id> "Name" "Description" "persona"\`.`, `bot:${botId}`).catch(() => {});+ await channel.send(`⚠ Fleet auto-build failed: ${err?.message ?? err} — **${botName}** is a lead with an empty crew; add members with \`/bots add-crew ${botId} <id> "Name" "Description" "persona"\`.`, target).catch(() => {});}})();}@@ -1290,7 +1361,7 @@ export class Agent {}bm.invalidateRuntime(botId);const channel = this.channels.getChannelForMessage(msg);- await channel?.send(`💰 Budget for **${manifest?.name ?? botId}**: ${applied}. When the cap is hit the bot pauses until the next day — never killed.`, `bot:${botId}`)+ await channel?.send(`💰 Budget for **${manifest?.name ?? botId}**: ${applied}. When the cap is hit the bot pauses until the next day — never killed.`, channel ? this.onboardingTarget(botId, msg, channel) : msg.channelId).catch(() => {});return true;}diff --git a/src/core/bots-onboarding-anywhere.test.ts b/src/core/bots-onboarding-anywhere.test.tsnew file mode 100644index 00000000..098d8c6c--- /dev/null+++ b/src/core/bots-onboarding-anywhere.test.ts@@ -0,0 +1,129 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++vi.mock('ai', async (importOriginal) => {+ const actual = await importOriginal<typeof import('ai')>();+ return { ...actual, generateText: vi.fn(), streamText: vi.fn() };+});++import { Agent } from './agent.js';+import { handleBotsCommand } from './commands/bots-command.js';+import { BotManager } from '../bots/bot-manager.js';+import { BotStore } from '../bots/store.js';+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';+import type { ChannelMessage } from '../types/channel.js';+import { tierPermissionsFile } from '../bots/permission-tiers.js';++/**+ * Bot onboarding from a chat that has no bot thread (Telegram, web, Discord):+ * the same persona → permissions → fleet → budget flow as the TUI, with every+ * reply addressed to the chat that asked and every choice offered as a+ * channel-native prompt (buttons on Telegram). Before this, `/bots create`+ * on Telegram sent the whole flow to `bot:<id>`, which Telegram cannot+ * resolve — the owner saw nothing after "onboarded".+ */++const CHAT = 'telegram:4242';++function telegramMessage(content: string): ChannelMessage {+ return { id: `m-${Math.random().toString(36).slice(2)}`, channelId: CHAT, channelType: 'telegram', senderId: '7', senderRole: 'admin', content, timestamp: Date.now() } as ChannelMessage;+}++describe('bot onboarding from Telegram (no bot thread)', () => {+ let root: string;+ let manager: BotManager;+ let agent: Agent;+ let sent: Array<{ target: string | undefined; text: string }>;+ let choices: Array<{ question: string; options: string[] }>;+ let answers: string[];+ let channel: { type: string; send: (text: string, target?: string) => Promise<void> };++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-onboard-'));+ const config = getDefaultConfig() as MercuryConfig;+ const providers = { get: () => undefined, getDefault: () => ({ name: 'stub', getModelInstance: () => ({}), getModel: () => 'stub' }) } as never;+ manager = new BotManager({ config, providers, tokenBudget: { recordUsage: () => {}, getRemaining: () => 1e6, getStatusText: () => '', getUsagePercentage: () => 0 } as never, store: new BotStore(join(root, 'bots')), userMemoryFactory: () => null });+ sent = [];+ choices = [];+ answers = [];+ channel = { type: 'telegram', send: async (text, target) => { sent.push({ target, text }); } };+ // A bare Agent: only the onboarding state machine, nothing else constructed.+ agent = Object.create(Agent.prototype) as Agent;+ Object.assign(agent, {+ botManager: manager,+ config,+ providers,+ channels: { getChannelForMessage: () => channel, get: () => channel },+ pendingPersonaFor: null,+ pendingPersonaChannelId: null,+ pendingPersonaNewlyCreated: false,+ pendingBudgetFor: null,+ presentChoice: vi.fn(async (question: string, options: string[]) => {+ choices.push({ question, options });+ const pick = answers.shift();+ return options.find(o => pick && o.startsWith(pick)) ?? options[0];+ }),+ });+ });++ afterEach(() => {+ manager.dispose();+ rmSync(root, { recursive: true, force: true });+ });++ it('create → persona → permissions → fleet → budget, every reply in the asking chat, every choice a prompt', async () => {+ await handleBotsCommand(agent, '/bots create scout "Scout" "Finds leads"', telegramMessage('/bots create scout "Scout" "Finds leads"'), channel);+ expect(agent.pendingPersonaFor).toBe('scout');+ expect(agent.pendingPersonaChannelId).toBe(CHAT);+ expect(sent.at(-1)?.target).toBe(CHAT);+ expect(sent.at(-1)?.text).toMatch(/next message here/);++ // The owner answers: as-is persona, Operator tier, solo, light budget.+ answers = ['Save as-is', 'Operator', 'Solo', 'Light'];+ agent.enqueueMessage(telegramMessage('You are Scout. You find B2B leads and report them as a table.'));+ await vi.waitFor(() => expect(choices).toHaveLength(4));+ await vi.waitFor(() => expect(sent.some(s => /is ready/.test(s.text))).toBe(true));++ expect(choices.map(c => c.options[0])).toEqual([+ expect.stringMatching(/^Convert to template/),+ 'Read-only (recommended default)',+ 'Solo bot',+ expect.stringMatching(/^Standard/),+ ]);+ // Buttons are short: the tier descriptions live in the question, not the labels.+ expect(choices[1].options.every(o => o.length <= 60)).toBe(true);+ expect(choices[1].question).toContain('Builder');++ expect(manager.store.readPersona('scout')).toContain('You are Scout');+ expect(manager.store.readPermissions('scout')).toEqual(tierPermissionsFile('operator'));+ expect(manager.store.get('scout')?.fleetRole ?? 'solo').not.toBe('lead');+ expect(manager.store.get('scout')?.autonomy?.dailyTokenBudget).toBe(1_000_000);++ // Nothing went to a TUI-only thread.+ expect(sent.every(s => s.target === CHAT)).toBe(true);+ expect(agent.pendingPersonaFor).toBeNull();+ expect(agent.pendingBudgetFor).toBeNull();+ });++ it('a lead choice promotes the bot; /skip keeps the starter persona; a slash command cancels capture', async () => {+ await handleBotsCommand(agent, '/bots create lead "Lead" "Runs a crew"', telegramMessage('/bots create lead "Lead" "Runs a crew"'), channel);+ answers = ['Save as-is', 'Read-only', "Lead a fleet — I'll", 'No cap'];+ agent.enqueueMessage(telegramMessage('You lead a research crew.'));+ await vi.waitFor(() => expect(sent.some(s => /is ready/.test(s.text))).toBe(true));+ expect(manager.store.get('lead')?.fleetRole).toBe('lead');+ expect(manager.store.get('lead')?.autonomy?.dailyTokenBudget).toBe(0);++ await handleBotsCommand(agent, '/bots create quiet "Quiet" "x"', telegramMessage('/bots create quiet "Quiet" "x"'), channel);+ agent.enqueueMessage(telegramMessage('/skip'));+ expect(agent.pendingPersonaFor).toBeNull();+ expect(sent.at(-1)?.text).toMatch(/Keeping the starter persona/);++ await handleBotsCommand(agent, '/bots create moved "Moved" "x"', telegramMessage('/bots create moved "Moved" "x"'), channel);+ expect(agent.pendingPersonaFor).toBe('moved');+ agent.enqueueMessage(telegramMessage('/bots cost'));+ expect(agent.pendingPersonaFor).toBeNull();+ expect(agent.pendingPersonaChannelId).toBeNull();+ });+});diff --git a/src/core/commands/bots-command.ts b/src/core/commands/bots-command.tsindex c1f12e7f..a42730c1 100644--- a/src/core/commands/bots-command.ts+++ b/src/core/commands/bots-command.ts@@ -215,7 +215,16 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan`bot:${id}`,);} else {- await channel.send(`🤖 Bot **${manifest.name}** (\`${id}\`) onboarded — enabled, fail-closed defaults.\n📁 Results will appear in \`${tildify(bm.store.deliverablesDir(id))}\`.\nPersona: \`${bm.store.botDir(id)}/persona.md\` — set it now with \`/bots persona ${id} <text>\`.`, channelId);+ // No bot thread here (Telegram, web, Discord): the next message in+ // this chat is the persona; the tier, fleet and budget steps follow+ // as tappable choices — the same onboarding as the TUI.+ agent.pendingPersonaFor = id;+ agent.pendingPersonaChannelId = channelId;+ await channel.send(+ `🤖 **${manifest.name}** (\`${id}\`) created — enabled, fail-closed defaults. 📁 Results: \`${tildify(bm.store.deliverablesDir(id))}\`\n\n` ++ `Now give it its character — your **next message here** becomes its persona (who it is, how it works, how it reports). I will offer to structure it into a template. Send \`/skip\` to keep the starter persona.`,+ channelId,+ );}} catch (err: any) {await channel.send(`Could not create bot "${id}": ${err?.message}`, channelId);diff --git a/website/docs/integrations/mercury-bots.mdx b/website/docs/integrations/mercury-bots.mdxindex 175137c3..7866409d 100644--- a/website/docs/integrations/mercury-bots.mdx+++ b/website/docs/integrations/mercury-bots.mdx@@ -111,7 +111,7 @@ Every unattended run is governed:## From Telegram-Everything above works from your phone: `/bots` and `/bot` are in Telegram's command menu, and the roster comes with buttons — **Stop / Start**, **Run** and **Runs** per bot, and a fleet row with **Cost**, **Outputs**, **Doctor** and **Stop all**. A tap runs the same slash command you would have typed (same permissions, same reply). When a bot finishes a task you asked for from Telegram, the reply comes back to that chat **with the delivered files attached**, not a path on your Mac; `/bots outputs <id>` lists what a bot has delivered with a 📎 button per file, and `/bots fetch <id> [name|latest]` sends one.+Everything above works from your phone: `/bots` and `/bot` are in Telegram's command menu, and the roster comes with buttons — **Stop / Start**, **Run** and **Runs** per bot, and a fleet row with **Cost**, **Outputs**, **Doctor** and **Stop all**. A tap runs the same slash command you would have typed (same permissions, same reply). Creating a bot works there too: `/bots create <id> "Name" "Description"`, then your next message is its persona, and the template, permissions, fleet and budget steps arrive as buttons. When a bot finishes a task you asked for from Telegram, the reply comes back to that chat **with the delivered files attached**, not a path on your Mac; `/bots outputs <id>` lists what a bot has delivered with a 📎 button per file, and `/bots fetch <id> [name|latest]` sends one.## Bundles