Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(bots): per-bot TUI chats, needs-you alerts, doctor scheduler linkage

Salman Qureshi95cb7d3e9ef2
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index c78fe710..ded3fcda 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -70,12 +70,23 @@ export class BotManager {
private readonly tokenBudget: TokenBudget;
private readonly userMemoryFactory?: BotManagerDeps['userMemoryFactory'];
private notify?: BotManagerDeps['notify'];
+ private alert?: (message: string) => Promise<void>;
/** Deliver turn output to the invoking surface (wired by the Agent). */
setNotify(cb: NonNullable<BotManagerDeps['notify']>): void {
this.notify = cb;
}
+ /** Push needs-you events (permanent failure, budget pause) to the owner. */
+ setAlert(cb: (message: string) => Promise<void>): void {
+ this.alert = cb;
+ }
+
+ private async alertOwner(botId: string, message: string): Promise<void> {
+ if (!this.alert) return;
+ await this.alert(message).catch((e) => logger.warn({ e, botId }, 'Bot alert send failed'));
+ }
+
private queues: Map<string, BotJob[]> = new Map();
private mailboxes: Map<string, BotTurnMail[]> = new Map();
private running: Map<string, Set<string>> = new Map(); // botId → running job ids
@@ -257,6 +268,7 @@ export class BotManager {
if (cap && next >= cap) {
this.pausedForBudget.add(botId);
logger.warn({ botId, used: next, cap }, 'Bot daily token budget reached — pausing until next day');
+ void this.alertOwner(botId, `🟡 **${manifest.name}** paused — daily token budget reached (${next} ≥ ${cap}). Resumes tomorrow; raise the cap in bot.yaml if this is too tight.`);
}
}
@@ -318,6 +330,7 @@ export class BotManager {
this.queue.settle(job.id, 'dead', output.reasonCode);
this.needsYou.add(botId);
logger.warn({ botId, jobId: job.id, reasonCode: output.reasonCode }, 'Bot turn failed permanently — moved to DLQ (replayable via /bots dlq)');
+ await this.alertOwner(botId, `❌ **${manifest.name}** failed permanently [reason: ${output.reasonCode}] — replay with \`/bots replay ${botId} ${job.id}\``);
} else if (output.status === 'paused') {
// Step-budget pause: work continues next turn — keep the job pending.
this.queue.settle(job.id, 'done');
@@ -327,10 +340,12 @@ export class BotManager {
}
// Deliver the outcome (guaranteed delivery target: the bot's own chat
- // minimum — never silently dropped, BOTS-ARCHITECTURE §3.1.5).
+ // minimum — never silently dropped, BOTS-ARCHITECTURE §3.1.5). Jobs
+ // without a source (cron/API) deliver to the bot's own thread, which
+ // the CLI channel routes via the `bot:<id>` targetId.
if (this.notify && output.status !== 'halted' && job.trigger !== 'mailbox') {
- const channelType = job.source?.channelType ?? (job.trigger === 'telegram' ? 'telegram' : 'bot');
- const channelId = job.source?.channelId ?? botId;
+ const channelType = job.source?.channelType ?? 'cli';
+ const channelId = job.source?.channelId ?? `bot:${botId}`;
const icon = output.status === 'completed' ? '🤖' : output.status === 'failed' ? '❌' : '⏸';
const text = `${icon} **${manifest.name}** (${job.trigger}): ${output.output.slice(0, 800)}`;
await this.notify(channelType, channelId, text).catch((e) =>
diff --git a/src/bots/cli.ts b/src/bots/cli.ts
index 736575ab..d8f39aef 100644
--- a/src/bots/cli.ts
+++ b/src/bots/cli.ts
@@ -1,6 +1,7 @@
import type { Command } from 'commander';
import { loadConfig } from '../utils/config.js';
import { logger } from '../utils/logger.js';
+import { loadSchedules } from '../core/scheduler.js';
import { BotStore } from './store.js';
import { BotQueue } from './queue.js';
import { BotJournal } from './journal.js';
@@ -38,10 +39,15 @@ export function registerBotsCommand(program: Command): void {
const store = new BotStore();
const queue = new BotQueue(store.botsRoot, config.bots?.retention?.dlqCap);
const getJournal = journalFor(store, config);
+ // Registered routine ids come from the persisted schedules manifest so
+ // the doctor can flag bot routines that exist in bot.yaml but never
+ // got registered (the "silently not firing" failure mode).
+ const scheduledRoutineIds = loadSchedules().map(t => t.id);
const report = runBotDoctor({
store,
queue,
journalFor: getJournal,
+ scheduledRoutineIds,
});
console.log(formatDoctorReport(report));
if (!report.healthy) {
diff --git a/src/channels/cli-bot-chat.test.ts b/src/channels/cli-bot-chat.test.ts
new file mode 100644
index 00000000..a3926da2
--- /dev/null
+++ b/src/channels/cli-bot-chat.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { CLIChannel } from './cli.js';
+
+describe('CLIChannel bot chat (transcript swap + target routing)', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ function makeChannel(): CLIChannel {
+ vi.spyOn(process.stdout, 'write').mockImplementation((() => true) as typeof process.stdout.write);
+ return new CLIChannel();
+ }
+
+ it('enterBotChat swaps the transcript and parks the main one', async () => {
+ const channel = new CLIChannel();
+ await channel.send('main message one');
+ expect(channel.getTuiState().chatMessages.some(m => m.content.includes('main message one'))).toBe(true);
+
+ channel.enterBotChat('researcher', 'Research');
+ const state = channel.getTuiState();
+ expect(state.botChat).toEqual({ botId: 'researcher', botName: 'Research' });
+ // Transcript swapped to the bot's seeded thread
+ expect(state.chatMessages.some(m => m.content.includes('bot chat'))).toBe(true);
+ expect(state.chatMessages.some(m => m.content.includes('main message one'))).toBe(false);
+
+ // Main-agent traffic while in the bot chat parks in the main transcript
+ await channel.send('main agent completion');
+ expect(channel.getTuiState().chatMessages.some(m => m.content.includes('main agent completion'))).toBe(false);
+
+ channel.exitBotChat();
+ const restored = channel.getTuiState();
+ expect(restored.botChat).toBeNull();
+ expect(restored.chatMessages.some(m => m.content.includes('main message one'))).toBe(true);
+ expect(restored.chatMessages.some(m => m.content.includes('main agent completion'))).toBe(true);
+ });
+
+ it('routes bot:<id> sends live when that bot chat is open', async () => {
+ const channel = new CLIChannel();
+ channel.enterBotChat('researcher', 'Research');
+ await channel.send('bot reply', 'bot:researcher');
+ expect(channel.getTuiState().chatMessages.some(m => m.content.includes('bot reply'))).toBe(true);
+ });
+
+ it('stores sends for an inactive bot transcript without disturbing the screen', async () => {
+ const channel = new CLIChannel();
+ channel.enterBotChat('researcher', 'Research');
+ await channel.send('publisher reply', 'bot:publisher');
+ expect(channel.getTuiState().chatMessages.some(m => m.content.includes('publisher reply'))).toBe(false);
+ // Switching to the publisher chat reveals the stored message
+ channel.exitBotChat();
+ channel.enterBotChat('publisher', 'Publisher');
+ expect(channel.getTuiState().chatMessages.some(m => m.content.includes('publisher reply'))).toBe(true);
+ });
+
+ it('persists a bot transcript across exit and re-entry', async () => {
+ const channel = new CLIChannel();
+ channel.enterBotChat('researcher', 'Research');
+ await channel.send('first bot run result', 'bot:researcher');
+ channel.exitBotChat();
+ channel.enterBotChat('researcher', 'Research');
+ expect(channel.getTuiState().chatMessages.some(m => m.content.includes('first bot run result'))).toBe(true);
+ });
+
+ it('seeded bot chat shows the /chat hint exactly once', async () => {
+ const channel = new CLIChannel();
+ channel.enterBotChat('researcher', 'Research');
+ channel.exitBotChat();
+ channel.enterBotChat('researcher', 'Research');
+ const hints = channel.getTuiState().chatMessages.filter(m => m.content.includes('bot chat — everything you type'));
+ expect(hints).toHaveLength(1);
+ });
+});
\ No newline at end of file
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index 0ee30d09..957c61b5 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -324,6 +324,8 @@ export interface TuiState {
/** A newer Mercury version the background check found — shown as a tiny
* bottom-bar indicator (⬆ vX) in Mercury Code until ignored. */
updateAvailable: string | null;
+ /** Active Mercury Bot chat — transcript is swapped to the bot's thread. */
+ botChat: { botId: string; botName: string } | null;
}
const defaultState: TuiState = {
@@ -358,6 +360,7 @@ const defaultState: TuiState = {
statusVerbs: null,
tuiFrozen: false,
updateAvailable: null,
+ botChat: null,
};
function shallowEqualSubAgents(a: SubAgentInfo[], b: SubAgentInfo[]): boolean {
@@ -386,6 +389,14 @@ export class CLIChannel extends BaseChannel {
private menuDepth = 0;
private menuAbortController: AbortController | null = null;
private heartbeatMsgId: string | null = null;
+ // Mercury Bot chat (mode-scoped transcript swap, §3.3): the bot's thread
+ // replaces the transcript on screen; main-agent traffic parks in
+ // mainTranscript until /chat restores it.
+ private activeBotId: string | null = null;
+ private mainTranscript: ChatMessage[] | null = null;
+ private botTranscripts = new Map<string, ChatMessage[]>();
+ /** Set while the input handler dispatches a bot-chat message downstream. */
+ private pendingBotChatTarget: string | null = null;
// Per-turn file-change attribution: file-tool calls (write/create/edit/
// delete) with their args path. Committed entries surface in the completion
@@ -588,6 +599,57 @@ export class CLIChannel extends BaseChannel {
}
/** useSyncExternalStore contract: read the latest immutable state snapshot. */
+ // ---- Mercury Bot chat (per-bot transcripts) ------------------------------
+
+ /** Open a bot's chat: swap the on-screen transcript to the bot's thread. */
+ enterBotChat(botId: string, botName: string): void {
+ if (this.activeBotId === botId) return;
+ if (this.activeBotId) {
+ this.botTranscripts.set(this.activeBotId, [...this.state.chatMessages]);
+ } else {
+ this.mainTranscript = [...this.state.chatMessages];
+ }
+ this.activeBotId = botId;
+ const seed: ChatMessage[] = this.botTranscripts.get(botId) ?? [{
+ id: `bot-open-${Date.now().toString(36)}`,
+ role: 'system',
+ content: `🤖 **${botName}** bot chat — everything you type here goes to the bot (runs outside the main conversation). \`/chat\` returns to the main transcript.`,
+ timestamp: Date.now(),
+ }];
+ this.botTranscripts.set(botId, seed);
+ this.trimAndSetMessages(seed, { botChat: { botId, botName }, isThinking: false, liveActivity: null });
+ }
+
+ /** Leave the bot chat and restore the main transcript. */
+ exitBotChat(): void {
+ if (!this.activeBotId) return;
+ this.botTranscripts.set(this.activeBotId, [...this.state.chatMessages]);
+ const main = this.mainTranscript ?? [];
+ this.activeBotId = null;
+ this.mainTranscript = null;
+ this.trimAndSetMessages(main, { botChat: null, isThinking: false, liveActivity: null });
+ }
+
+ getActiveBotChat(): { botId: string; botName: string } | null {
+ return this.activeBotId ? this.state.botChat : null;
+ }
+
+ /** Agent-side marker: the in-flight input was dispatched from a bot chat. */
+ consumePendingBotChatTarget(): string | null {
+ const target = this.pendingBotChatTarget;
+ this.pendingBotChatTarget = null;
+ return target;
+ }
+
+ private appendBotMessage(botId: string, msg: ChatMessage): void {
+ const existing = this.botTranscripts.get(botId) ?? [];
+ const updated = [...existing, msg];
+ this.botTranscripts.set(botId, updated);
+ if (this.activeBotId === botId) {
+ this.trimAndSetMessages(updated, { isThinking: false, liveActivity: null });
+ }
+ }
+
getTuiStateSnapshot = (): TuiState => {
return this.state;
};
@@ -664,6 +726,25 @@ export class CLIChannel extends BaseChannel {
this.inputHandler = (text: string) => {
const trimmed = text.trim();
+ // Bot chat: /chat exits back to the main transcript; plain text goes
+ // to the bot as `/bot <id> <text>` (durable enqueue, reply lands here).
+ if (this.activeBotId) {
+ if (trimmed === '/chat' || trimmed === '/c') {
+ this.exitBotChat();
+ this.update({ mode: 'chat' });
+ return;
+ }
+ if (trimmed && !trimmed.startsWith('/')) {
+ const wrapped = `/bot ${this.activeBotId} ${trimmed}`;
+ this.pendingBotChatTarget = this.activeBotId;
+ try {
+ onInput(wrapped);
+ } finally {
+ this.pendingBotChatTarget = null;
+ }
+ return;
+ }
+ }
if (trimmed === '/chat' || trimmed === '/c') {
// Returning from Mercury Code must tear down its state (mouse mode,
// scroll offset, programming mode) — not just flip the view. A bare
@@ -988,19 +1069,31 @@ export class CLIChannel extends BaseChannel {
this.trimAndSetMessages([...this.state.chatMessages, msg]);
}
- async send(content: string, _targetId?: string, _elapsedMs?: number): Promise<void> {
+ async send(content: string, targetId?: string, _elapsedMs?: number): Promise<void> {
const msg: ChatMessage = {
id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
role: 'agent',
content,
timestamp: Date.now(),
};
+ // Bot transcripts (targetId `bot:<id>`, BOTS-ARCHITECTURE §3.3): route to
+ // the bot's own thread — live if it is the one on screen, else stored.
+ if (targetId?.startsWith('bot:')) {
+ this.appendBotMessage(targetId.slice(4), msg);
+ return;
+ }
// Clear any lingering heartbeat message when we send a real response.
let chat = this.state.chatMessages;
if (this.heartbeatMsgId) {
chat = chat.filter((m) => m.id !== this.heartbeatMsgId);
this.heartbeatMsgId = null;
}
+ // While a bot chat is open, main-agent traffic must not leak into the
+ // bot's thread: non-bot sends land in the parked main transcript.
+ if (this.activeBotId) {
+ this.mainTranscript = [...(this.mainTranscript ?? []), msg];
+ return;
+ }
this.trimAndSetMessages([...chat, msg], { isThinking: false, liveActivity: null });
}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index bf49e095..b69b457c 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -562,12 +562,16 @@ export class Agent {
/** Wire the Mercury Bots runtime (see bots/bot-manager.ts, BOTS-ARCHITECTURE.md). */
setBotManager(botManager: import('../bots/bot-manager.js').BotManager): void {
this.botManager = botManager;
- botManager['notify'] = async (channelType, channelId, message) => {
+ botManager.setNotify(async (channelType, channelId, message) => {
const channel = this.channels.get(channelType as any);
if (channel) {
await channel.send(message, channelId).catch((e) => logger.warn({ e }, 'bot notify channel send failed'));
}
- };
+ });
+ botManager.setAlert(async (message) => {
+ const channel = this.channels.getNotificationChannel();
+ await channel?.send(message).catch((e) => logger.warn({ e }, 'bot alert send failed'));
+ });
}
getBotManager(): import('../bots/bot-manager.js').BotManager | undefined {
@@ -655,16 +659,21 @@ export class Agent {
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: msg.channelId },
+ 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.`, msg.channelId)
+ 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}]`, msg.channelId)
+ void channel.send(`Could not message **${botId}**: [reason: ${result.reasonCode}]`, replyTarget)
.catch((err) => logger.warn({ err }, '/bot ack send failed'));
}
return;
@@ -1118,6 +1127,21 @@ export class Agent {
return;
}
+ if (action === 'open') {
+ const target = parts[1]?.toLowerCase();
+ const manifest = target ? bm.store.get(target) : null;
+ if (!target || !manifest) {
+ await channel.send(`No bot "${target ?? ''}". See \`/bots\` for the roster.`, channelId);
+ return;
+ }
+ if (typeof (channel as any).enterBotChat === 'function') {
+ (channel as any).enterBotChat(target, manifest.name);
+ return;
+ }
+ await channel.send(`Opening a bot chat is only supported in the TUI — use \`/bots send ${target} <message>\` here.`, channelId);
+ return;
+ }
+
if (action === 'create' || action === 'onboard') {
// /bots create <id> "Name" "Description"
const id = (parts[1] ?? '').toLowerCase();
@@ -1274,7 +1298,9 @@ export class Agent {
await channel.send(
'**Bots commands**\n' +
'`/bots` — roster with live states\n' +
+ '`/bots open <id>` — open a bot chat (transcript swaps to the bot thread)\n' +
'`/bots create <id> "Name" "Description"` — onboard a bot\n' +
+ '`/bot <id> <message>` — message a bot from any channel\n' +
'`/bots send <id> <message>` — message a bot\n' +
'`/bots journal <id>` — recent runs\n' +
'`/bots inbox <id>` — pending bot-to-bot mail\n' +
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index d28f4d21..375c0461 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -129,6 +129,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
'/session delete ',
'/bots',
'/bots list',
+ '/bots open ',
'/bots create ',
'/bots send ',
'/bots journal ',
@@ -1021,6 +1022,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
mode={state.mode}
programmingMode={state.programmingMode}
projectContext={state.projectContext}
+ botChat={state.botChat}
/>
)}
{showInput && state.mode !== 'mercury-code' && slashSuggestions.length > 0 && (
@@ -2168,17 +2170,19 @@ function InputBox({
mode,
programmingMode,
projectContext,
+ botChat,
}: {
input: string;
cursorPos: number;
mode: AppMode;
programmingMode: ProgrammingModeState;
projectContext: string | null;
+ botChat?: { botId: string; botName: string } | null;
}) {
const inWorkspace = mode === 'workspace';
const inCoding = mode === 'coding' || inWorkspace;
- const promptColor = inWorkspace ? 'cyan' : inCoding ? 'green' : 'yellow';
- const label = inWorkspace ? '[IDE CHAT]' : inCoding ? '[CODING]' : '[CHAT]';
+ const promptColor = botChat ? 'magenta' : inWorkspace ? 'cyan' : inCoding ? 'green' : 'yellow';
+ const label = botChat ? `[BOT ${botChat.botId}]` : inWorkspace ? '[IDE CHAT]' : inCoding ? '[CODING]' : '[CHAT]';
const contextLabel = projectContext && projectContext.length > 52
? `...${projectContext.slice(-49)}`
: (projectContext || 'No project context');