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): P1 — durable queue, HTTP API, DLQ/doctor, Telegram ingress

Salman Qureshi7f447e15e32b
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index b0517396..c78fe710 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -9,6 +9,7 @@ import type { UserMemoryStore } from '../memory/user-memory.js';
import { UserMemoryStore as UserMemoryStoreImpl } from '../memory/user-memory.js';
import { BotStore, BOT_JOURNAL_FILENAME, isValidCronExpression } from './store.js';
import { BotJournal } from './journal.js';
+import { BotQueue, idempotencyKeyFor, LEASE_SECONDS, type DurableBotJob } from './queue.js';
import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';
import { createBotSendTool } from './tools/bot-send.js';
import { runBotTurn, isTransientFailure, type BotTurnMail } from './bot-turn.js';
@@ -45,6 +46,8 @@ export interface BotManagerDeps {
providers: ProviderRegistry;
tokenBudget: TokenBudget;
store?: BotStore;
+ /** Durable job store; defaults to the SQLite→JSON backend at the bots root. */
+ queue?: BotQueue;
/** Per-bot memory factory (P0-5 wires the default: UserMemoryStore with bot:<id> key). */
userMemoryFactory?: (botId: string, manifest: BotManifest) => UserMemoryStore | null;
/** Deliver turn output to the invoking surface (chat/telegram/api). */
@@ -61,6 +64,7 @@ const MAILBOX_CAPACITY = 100;
*/
export class BotManager {
readonly store: BotStore;
+ readonly queue: BotQueue;
private readonly config: MercuryConfig;
private readonly providers: ProviderRegistry;
private readonly tokenBudget: TokenBudget;
@@ -106,6 +110,23 @@ export class BotManager {
});
this.notify = deps.notify;
this.store = deps.store ?? new BotStore();
+ this.queue = deps.queue ?? new BotQueue(this.store.botsRoot, this.config.bots?.retention?.dlqCap);
+ // Resume work a crashed predecessor left behind: pending jobs (and
+ // expired-lease claimed jobs) re-enter the in-memory queues. Durable
+ // enqueue happens before any ack, so nothing was lost (§2.6).
+ for (const job of this.queue.resumeJobs()) {
+ if (this.store.exists(job.botId)) {
+ const q = this.queues.get(job.botId) ?? [];
+ this.queues.set(job.botId, q);
+ q.push({
+ id: job.id, botId: job.botId, trigger: job.trigger, prompt: job.prompt,
+ fromBot: job.fromBot, source: job.source, createdAt: job.createdAt, attempts: job.attempts,
+ });
+ this.pump(job.botId);
+ } else {
+ this.queue.settle(job.id, 'dead', 'bot_removed');
+ }
+ }
}
/** Fleet-wide concurrency cap: config override or clamp(2, cpus-1). */
@@ -130,7 +151,7 @@ export class BotManager {
return this.journalFor(botId);
}
- enqueue(botId: string, job: { trigger: BotTrigger; prompt: string; fromBot?: string; source?: { channelType: string; channelId: string } }): { jobId: string; accepted: boolean; reasonCode?: string } {
+ enqueue(botId: string, job: { trigger: BotTrigger; prompt: string; fromBot?: string; source?: { channelType: string; channelId: string }; attempts?: number }): { jobId: string; accepted: boolean; reasonCode?: string } {
const manifest = this.store.get(botId);
if (!manifest) return { jobId: '', accepted: false, reasonCode: 'target_unknown' };
if (!manifest.enabled || this.disabled.has(botId)) return { jobId: '', accepted: false, reasonCode: 'target_disabled' };
@@ -140,8 +161,24 @@ export class BotManager {
if (queue.length >= MAILBOX_CAPACITY) {
return { jobId: '', accepted: false, reasonCode: 'queue_full' };
}
- const id = randomUUID().slice(0, 8);
- queue.push({ id, botId, trigger: job.trigger, prompt: job.prompt, fromBot: job.fromBot, source: job.source, createdAt: Date.now(), attempts: 0 });
+ // Durable-before-ack: the job is persisted (idempotency-deduped) before
+ // the caller hears "accepted" — a crash between ack and run loses nothing.
+ const durable = this.queue.enqueue({
+ id: randomUUID().slice(0, 8),
+ botId,
+ trigger: job.trigger,
+ prompt: job.prompt,
+ fromBot: job.fromBot,
+ source: job.source,
+ attempts: job.attempts ?? 0,
+ createdAt: Date.now(),
+ idempotencyKey: idempotencyKeyFor(botId, job.trigger, job.prompt, job.fromBot),
+ });
+ if (durable.duplicated) {
+ return { jobId: durable.job.id, accepted: true };
+ }
+ const id = durable.job.id;
+ queue.push({ id, botId, trigger: job.trigger, prompt: job.prompt, fromBot: job.fromBot, source: job.source, createdAt: durable.job.createdAt, attempts: durable.job.attempts });
this.pump(botId);
return { jobId: id, accepted: true };
}
@@ -245,6 +282,7 @@ export class BotManager {
}
try {
+ this.queue.claim(job.id, LEASE_SECONDS);
const turn = this.buildTurn(botId, manifest, job, controller.signal);
const output = await runBotTurn(turn.input);
turn.cleanup();
@@ -268,16 +306,24 @@ export class BotManager {
this.recordBotTokens(botId, manifest, output.tokensIn + output.tokensOut);
// Transient provider failures retry with backoff, bounded; permanent
- // failures journal and stop (never re-queued — BOTS-ARCHITECTURE §2.6).
+ // 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) {
+ this.queue.settle(job.id, 'done'); // the retry re-enqueues a fresh attempt
const delay = Math.min(15000, 1000 * 2 ** job.attempts);
logger.info({ botId, jobId: job.id, reasonCode: output.reasonCode, retryIn: delay }, 'Bot turn failed transiently — retrying');
setTimeout(() => {
- this.enqueue(botId, { trigger: job.trigger, prompt: job.prompt, fromBot: job.fromBot });
+ this.enqueue(botId, { trigger: job.trigger, prompt: job.prompt, fromBot: job.fromBot, source: job.source, attempts: job.attempts + 1 });
}, delay).unref?.();
} else if (output.status === 'failed') {
+ 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 — see journal/DLQ');
+ logger.warn({ botId, jobId: job.id, reasonCode: output.reasonCode }, 'Bot turn failed permanently — moved to DLQ (replayable via /bots dlq)');
+ } else if (output.status === 'paused') {
+ // Step-budget pause: work continues next turn — keep the job pending.
+ this.queue.settle(job.id, 'done');
+ this.enqueue(botId, { trigger: job.trigger, prompt: job.prompt, fromBot: job.fromBot, source: job.source, attempts: job.attempts });
+ } else {
+ this.queue.settle(job.id, 'done');
}
// Deliver the outcome (guaranteed delivery target: the bot's own chat
@@ -292,6 +338,7 @@ export class BotManager {
}
} catch (err: any) {
logger.error({ botId, jobId: job.id, err: err?.message }, 'Bot turn crashed');
+ this.queue.settle(job.id, 'dead', 'unknown_error');
this.journalFor(botId).append({
runId: job.id,
botId,
@@ -474,6 +521,23 @@ export class BotManager {
return this.journalFor(botId).read(botId, limit);
}
+ getDlq(botId?: string): DurableBotJob[] {
+ return this.queue.listDlq(botId);
+ }
+
+ /** Re-run a dead-lettered job: remove it from the DLQ and re-enqueue fresh. */
+ replayDlq(botId: string, jobId: string): { accepted: boolean; jobId?: string; reasonCode?: string } {
+ const entry = this.queue.removeFromDlq(jobId);
+ if (!entry || entry.botId !== botId) return { accepted: false, reasonCode: 'not_found' };
+ return this.enqueue(botId, {
+ trigger: entry.trigger,
+ prompt: entry.prompt,
+ fromBot: entry.fromBot,
+ source: entry.source,
+ attempts: 0,
+ });
+ }
+
getStorage(): Array<{ id: string; bytes: number; journalBytes: number }> {
return this.store.usage();
}
diff --git a/src/bots/cli.ts b/src/bots/cli.ts
new file mode 100644
index 00000000..736575ab
--- /dev/null
+++ b/src/bots/cli.ts
@@ -0,0 +1,88 @@
+import type { Command } from 'commander';
+import { loadConfig } from '../utils/config.js';
+import { logger } from '../utils/logger.js';
+import { BotStore } from './store.js';
+import { BotQueue } from './queue.js';
+import { BotJournal } from './journal.js';
+import { runBotDoctor, formatDoctorReport } from './doctor.js';
+
+/** Per-bot journal accessor matching BotManager's retention resolution. */
+function journalFor(store: BotStore, config: ReturnType<typeof loadConfig>) {
+ return (botId: string): BotJournal => {
+ const manifest = store.get(botId);
+ const retention = { ...(config.bots?.retention ?? {}), ...(manifest?.retention ?? {}) };
+ return new BotJournal(store.botDir(botId), retention.journalRotateBytes, retention.journalKeepRotations);
+ };
+}
+
+function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+/**
+ * `mercury bots` — CLI surface for the bot fleet (doctor / list / storage).
+ * Read-only: mutation happens through the agent (/bots) or the HTTP API.
+ */
+export function registerBotsCommand(program: Command): void {
+ const bots = program
+ .command('bots')
+ .description('Mercury Bots fleet tooling (see /bots inside the agent for the interactive surface)');
+
+ bots
+ .command('doctor')
+ .description('Read-only fleet health check — exits 1 when anything is actionable')
+ .action(() => {
+ const config = loadConfig();
+ const store = new BotStore();
+ const queue = new BotQueue(store.botsRoot, config.bots?.retention?.dlqCap);
+ const getJournal = journalFor(store, config);
+ const report = runBotDoctor({
+ store,
+ queue,
+ journalFor: getJournal,
+ });
+ console.log(formatDoctorReport(report));
+ if (!report.healthy) {
+ process.exitCode = 1;
+ }
+ });
+
+ bots
+ .command('list')
+ .description('List configured bots with their live config summary')
+ .action(() => {
+ const store = new BotStore();
+ const manifests = store.list();
+ if (manifests.length === 0) {
+ console.log('No bots configured. Onboard one with /bots create <id> "Name" "Description".');
+ return;
+ }
+ for (const m of manifests) {
+ const model = m.model?.provider ? `${m.model.provider}${m.model.model ? `:${m.model.model}` : ''}` : 'inherit';
+ const routines = (m.schedules?.length ?? 0);
+ console.log(`${m.enabled ? '🟢' : '⛔'} ${m.id.padEnd(20)} ${m.name.padEnd(24)} model=${model.padEnd(30)} routines=${routines}`);
+ }
+ });
+
+ bots
+ .command('storage')
+ .description('Per-bot disk usage (retention caps are enforced at write time)')
+ .action(() => {
+ const store = new BotStore();
+ const usage = store.usage();
+ if (usage.length === 0) {
+ console.log('No bot storage in use.');
+ return;
+ }
+ let total = 0;
+ for (const u of usage) {
+ total += u.bytes;
+ console.log(`${u.id.padEnd(20)} ${formatBytes(u.bytes).padStart(10)} (journal ${formatBytes(u.journalBytes)})`);
+ }
+ console.log(`\nTotal: ${formatBytes(total)}`);
+ });
+
+ void logger;
+}
\ No newline at end of file
diff --git a/src/bots/doctor.test.ts b/src/bots/doctor.test.ts
new file mode 100644
index 00000000..58b735ce
--- /dev/null
+++ b/src/bots/doctor.test.ts
@@ -0,0 +1,116 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { BotStore } from './store.js';
+import { BotQueue } from './queue.js';
+import { BotJournal } from './journal.js';
+import { runBotDoctor, formatDoctorReport } from './doctor.js';
+
+describe('runBotDoctor', () => {
+ let root: string;
+ let store: BotStore;
+ let queue: BotQueue;
+ let journal: BotJournal;
+ let dir: string;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-doctor-'));
+ store = new BotStore(join(root, 'bots'));
+ mkdirSync(join(root, 'bots', 'researcher'), { recursive: true });
+ queue = new BotQueue(join(root, 'bots'), 100);
+ journal = new BotJournal(join(root, 'bots', 'researcher'));
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ const record = (state: 'completed' | 'failed', reasonCode?: string) => ({
+ runId: 'r1',
+ botId: 'researcher',
+ trigger: 'cron' as const,
+ state,
+ startedAt: Date.now(),
+ durationMs: 100,
+ tokensIn: 1,
+ tokensOut: 1,
+ reasonCode,
+ });
+
+ it('is healthy with no bots and no findings', () => {
+ const report = runBotDoctor({ store, queue, journalFor: () => journal });
+ expect(report.healthy).toBe(true);
+ expect(report.findings).toEqual([]);
+ });
+
+ it('flags a bot whose last run failed, with the reason code', () => {
+ store.create({ id: 'researcher', name: 'Research' });
+ journal.append(record('failed', 'provider_auth'));
+ const report = runBotDoctor({ store, queue, journalFor: () => journal });
+ expect(report.healthy).toBe(false);
+ expect(report.findings.some(f => f.check === 'last-run' && f.detail.includes('provider_auth'))).toBe(true);
+ });
+
+ it('flags DLQ depth, erroring past the threshold', () => {
+ store.create({ id: 'researcher', name: 'Research' });
+ for (let i = 0; i < 7; i++) {
+ queue.enqueue({
+ id: `j${i}`, botId: 'researcher', trigger: 'chat', prompt: `p${i}`,
+ attempts: 0, createdAt: i, idempotencyKey: `k${i}`,
+ });
+ queue.settle(`j${i}`, 'dead', 'unknown_error');
+ }
+ const report = runBotDoctor({ store, queue, journalFor: () => journal });
+ const dlqFinding = report.findings.find(f => f.check === 'dlq')!;
+ expect(dlqFinding.botId).toBe('researcher');
+ expect(dlqFinding.detail).toContain('7 dead-lettered');
+ expect(dlqFinding.severity).toBe('error');
+ });
+
+ it('flags orphaned DLQ entries for bots with no profile', () => {
+ queue.enqueue({
+ id: 'x1', botId: 'ghost', trigger: 'chat', prompt: 'p',
+ attempts: 0, createdAt: Date.now(), idempotencyKey: 'k',
+ });
+ queue.settle('x1', 'dead', 'unknown_error');
+ const report = runBotDoctor({ store, queue, journalFor: () => journal });
+ expect(report.findings.some(f => f.check === 'orphan-dlq' && f.botId === 'ghost')).toBe(true);
+ });
+
+ it('flags a configured routine missing from the scheduler', () => {
+ store.create({
+ id: 'researcher',
+ name: 'Research',
+ manifest: { schedules: [{ name: 'morning', cron: '0 9 * * *', prompt: 'go' }] },
+ });
+ const report = runBotDoctor({ store, queue, journalFor: () => journal, scheduledRoutineIds: [] });
+ expect(report.findings.some(f => f.check === 'schedule-registered')).toBe(true);
+ // Registered → no finding
+ const ok = runBotDoctor({ store, queue, journalFor: () => journal, scheduledRoutineIds: ['bot:researcher:morning'] });
+ expect(ok.findings.some(f => f.check === 'schedule-registered')).toBe(false);
+ });
+
+ it('flags config validation errors', () => {
+ const { writeFileSync } = require('node:fs');
+ const manifestDir = join(root, 'bots', 'badbot');
+ mkdirSync(manifestDir, { recursive: true });
+ writeFileSync(join(manifestDir, 'bot.yaml'), 'id: badbot\nname: ""\n', 'utf-8');
+ const report = runBotDoctor({ store, queue, journalFor: () => journal });
+ const configFinding = report.findings.find(f => f.botId === 'badbot' && f.check === 'config');
+ expect(configFinding?.severity).toBe('error');
+ expect(configFinding?.detail).toContain('name is required');
+ expect(report.healthy).toBe(false);
+ });
+
+ it('formatDoctorReport maps unhealthy to an actionable message', () => {
+ const healthy = formatDoctorReport({ findings: [], healthy: true, checked: 2 });
+ expect(healthy).toContain('healthy');
+ const sick = formatDoctorReport({
+ findings: [{ botId: 'a', severity: 'error', check: 'dlq', detail: '1 dead-lettered job(s)' }],
+ healthy: false,
+ checked: 2,
+ });
+ expect(sick).toContain('[a] dlq');
+ });
+});
\ No newline at end of file
diff --git a/src/bots/doctor.ts b/src/bots/doctor.ts
new file mode 100644
index 00000000..2d771d25
--- /dev/null
+++ b/src/bots/doctor.ts
@@ -0,0 +1,117 @@
+import type { BotStore } from './store.js';
+import type { BotQueue } from './queue.js';
+import { validateBotManifest } from './store.js';
+import type { BotRunRecord } from './types.js';
+import type { BotJournal } from './journal.js';
+
+export interface DoctorFinding {
+ botId: string;
+ severity: 'error' | 'warning';
+ check: string;
+ detail: string;
+}
+
+export interface DoctorReport {
+ findings: DoctorFinding[];
+ healthy: boolean;
+ checked: number;
+}
+
+export interface DoctorDeps {
+ store: BotStore;
+ queue: BotQueue;
+ journalFor: (botId: string) => BotJournal;
+ /** Scheduled manifests by id (bot:<id>:<name>) for next-run overdue checks. */
+ scheduledRoutineIds?: string[];
+ /** Grace window (minutes) before an overdue schedule counts as not firing. */
+ graceMinutes?: number;
+}
+
+/**
+ * Read-only fleet health check — the Hermes `cron doctor` pattern:
+ * groups per-bot issues no other surface shows at once. Exit-code bearing:
+ * `healthy === false` maps to exit 1 so watchdogs/CI can gate on it.
+ */
+export function runBotDoctor(deps: DoctorDeps): DoctorReport {
+ const findings: DoctorFinding[] = [];
+ const manifests = deps.store.list();
+ const dlqByBot = new Map<string, number>();
+ for (const entry of deps.queue.listDlq()) {
+ dlqByBot.set(entry.botId, (dlqByBot.get(entry.botId) ?? 0) + 1);
+ }
+
+ for (const manifest of manifests) {
+ const errors = validateBotManifest(manifest);
+ if (errors.length > 0) {
+ findings.push({ botId: manifest.id, severity: 'error', check: 'config', detail: errors.join('; ') });
+ }
+
+ const dlqDepth = dlqByBot.get(manifest.id) ?? 0;
+ if (dlqDepth > 0) {
+ findings.push({
+ botId: manifest.id,
+ severity: dlqDepth > 5 ? 'error' : 'warning',
+ check: 'dlq',
+ detail: `${dlqDepth} dead-lettered job(s) awaiting review or replay`,
+ });
+ }
+
+ const journal = deps.journalFor(manifest.id);
+ const counts = journal.counts(manifest.id);
+ if (counts.total > 0) {
+ const recent = journal.read(manifest.id, 5);
+ const last = recent[recent.length - 1];
+ if (last && last.state === 'failed') {
+ findings.push({
+ botId: manifest.id,
+ severity: 'error',
+ check: 'last-run',
+ detail: `Last run ${last.runId} failed${last.reasonCode ? ` [reason: ${last.reasonCode}]` : ''}${last.error ? `: ${last.error.slice(0, 120)}` : ''}`,
+ });
+ }
+ }
+ if (manifest.enabled === false) continue;
+ for (const routine of manifest.schedules ?? []) {
+ const id = `bot:${manifest.id}:${routine.name}`;
+ if (deps.scheduledRoutineIds && !deps.scheduledRoutineIds.includes(id)) {
+ findings.push({
+ botId: manifest.id,
+ severity: 'warning',
+ check: 'schedule-registered',
+ detail: `Routine "${routine.name}" is configured in bot.yaml but not registered in the scheduler — run \`mercury restart\` to register bot routines`,
+ });
+ }
+ }
+ }
+
+ // Bots referenced in schedules or DLQ but missing from the profile store.
+ for (const [botId, depth] of dlqByBot) {
+ if (!manifests.some(m => m.id === botId)) {
+ findings.push({ botId, severity: 'warning', check: 'orphan-dlq', detail: `${depth} DLQ entries for a bot with no profile` });
+ }
+ }
+
+ return {
+ findings,
+ healthy: findings.every(f => f.severity !== 'error'),
+ checked: manifests.length,
+ };
+}
+
+export function formatDoctorReport(report: DoctorReport): string {
+ if (report.findings.length === 0) {
+ return `✅ Bot fleet healthy — ${report.checked} bot(s) checked, nothing actionable.`;
+ }
+ const lines: string[] = [];
+ const errors = report.findings.filter(f => f.severity === 'error');
+ const warnings = report.findings.filter(f => f.severity === 'warning');
+ lines.push(`⚠ Bot fleet: ${errors.length} actionable, ${report.findings.length - errors.length} warning(s) — ${report.checked} bot(s) checked`, '');
+ for (const finding of report.findings) {
+ const icon = finding.severity === 'error' ? '❌' : '⚠️';
+ lines.push(`${icon} [${finding.botId}] ${finding.check}: ${finding.detail}`);
+ }
+ return lines.join('\n');
+}
+
+// Re-exported for the doctor UI's last-run window check.
+export type { BotRunRecord };
\ No newline at end of file
diff --git a/src/bots/queue.test.ts b/src/bots/queue.test.ts
new file mode 100644
index 00000000..46896d6c
--- /dev/null
+++ b/src/bots/queue.test.ts
@@ -0,0 +1,222 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+// Mock generateText; keep the rest of the ai module real for tool factories.
+vi.mock('ai', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('ai')>();
+ return { ...actual, generateText: vi.fn() };
+});
+
+import { generateText } from 'ai';
+const mockedGenerateText = vi.mocked(generateText);
+import { BotQueue, JsonFileQueueBackend, SqliteQueueBackend, idempotencyKeyFor, LEASE_SECONDS } from './queue.js';
+import type { DurableBotJob } from './queue.js';
+
+function job(id: string, overrides: Partial<DurableBotJob> = {}): Omit<DurableBotJob, 'state'> {
+ return {
+ id,
+ botId: 'researcher',
+ trigger: 'chat',
+ prompt: `task ${id}`,
+ attempts: 0,
+ createdAt: Date.now(),
+ idempotencyKey: idempotencyKeyFor('researcher', 'chat', `task ${id}`),
+ ...overrides,
+ } as Omit<DurableBotJob, 'state'>;
+}
+
+function makeBackends(dir: string) {
+ return {
+ json: new JsonFileQueueBackend(dir, 100),
+ sqlite: new SqliteQueueBackend(dir, 100, require('better-sqlite3')),
+ };
+}
+
+// `require` equivalent for the test (ESM)
+import { createRequire } from 'node:module';
+const require = createRequire(import.meta.url);
+
+describe('BotQueue backends (JSON-file + SQLite semantics)', () => {
+ let root: string;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-queue-'));
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ for (const name of ['json', 'sqlite'] as const) {
+ describe(`${name} backend`, () => {
+ it('enqueues pending and persists across restart', () => {
+ const backend = name === 'json' ? new JsonFileQueueBackend(root, 100) : new SqliteQueueBackend(root, 100, require('better-sqlite3'));
+ backend.enqueue(job('a1'));
+ // Simulate a restart by re-reading from disk with a fresh instance
+ const fresh = name === 'json' ? new JsonFileQueueBackend(root, 100) : new SqliteQueueBackend(root, 100, require('better-sqlite3'));
+ const resumed = fresh.rehydratable();
+ expect(resumed).toHaveLength(1);
+ expect(resumed[0].id).toBe('a1');
+ expect(resumed[0].state).toBe('pending');
+ });
+
+ it('deduplicates on the idempotency key while pending', () => {
+ const backend = name === 'json' ? new JsonFileQueueBackend(root, 100) : new SqliteQueueBackend(root, 100, require('better-sqlite3'));
+ const first = backend.enqueue(job('a1', { prompt: 'same', idempotencyKey: idempotencyKeyFor('researcher', 'chat', 'same') }));
+ const second = backend.enqueue(job('a2', { prompt: 'same', idempotencyKey: idempotencyKeyFor('researcher', 'chat', 'same') }));
+ expect(first.duplicated).toBe(false);
+ expect(second.duplicated).toBe(true);
+ expect(second.job.id).toBe('a1');
+ expect(backend.rehydratable()).toHaveLength(1);
+ });
+
+ it('claim sets a lease; settle done removes the job', () => {
+ const backend = name === 'json' ? new JsonFileQueueBackend(root, 100) : new SqliteQueueBackend(root, 100, require('better-sqlite3'));
+ backend.enqueue(job('a1'));
+ backend.claim('a1', LEASE_SECONDS);
+ expect(backend.rehydratable()[0].state).toBe('claimed');
+ backend.settle('a1', 'done');
+ expect(backend.rehydratable()).toHaveLength(0);
+ expect(backend.counts()).toEqual({ pending: 0, claimed: 0, dlq: 0 });
+ });
+
+ it('settle dead moves the job to the DLQ with the reason', () => {
+ const backend = name === 'json' ? new JsonFileQueueBackend(root, 100) : new SqliteQueueBackend(root, 100, require('better-sqlite3'));
+ backend.enqueue(job('a1'));
+ backend.settle('a1', 'dead', 'provider_auth');
+ expect(backend.rehydratable()).toHaveLength(0);
+ const dlq = backend.listDlq('researcher');
+ expect(dlq).toHaveLength(1);
+ expect(dlq[0].reasonCode).toBe('provider_auth');
+ expect(dlq[0].attempts).toBe(1);
+ });
+
+ it('expired leases requeue to pending; fresh leases survive', () => {
+ const backend = name === 'json' ? new JsonFileQueueBackend(root, 100) : new SqliteQueueBackend(root, 100, require('better-sqlite3'));
+ backend.enqueue(job('expired'));
+ backend.enqueue(job('alive'));
+ backend.claim('expired', 0); // expires immediately
+ backend.claim('alive', 3600);
+ const requeued = backend.requeueExpiredLeases();
+ expect(requeued).toBe(1);
+ const jobs = backend.rehydratable();
+ expect(jobs.find(j => j.id === 'expired')?.state).toBe('pending');
+ expect(jobs.find(j => j.id === 'alive')?.state).toBe('claimed');
+ });
+
+ it('DLQ is capped with oldest-first eviction', () => {
+ const backend = name === 'json' ? new JsonFileQueueBackend(root, 3) : new SqliteQueueBackend(root, 3, require('better-sqlite3'));
+ for (let i = 0; i < 5; i++) {
+ backend.enqueue(job(`d${i}`, { createdAt: i }));
+ backend.settle(`d${i}`, 'dead', 'test');
+ }
+ const dlq = backend.listDlq();
+ expect(dlq).toHaveLength(3);
+ // Newest survive
+ expect(dlq.map(j => j.id).sort()).toEqual(['d2', 'd3', 'd4']);
+ });
+
+ it('removeFromDlq returns the entry and clears it for replay', () => {
+ const backend = name === 'json' ? new JsonFileQueueBackend(root, 100) : new SqliteQueueBackend(root, 100, require('better-sqlite3'));
+ backend.enqueue(job('a1'));
+ backend.settle('a1', 'dead', 'provider_rate_limit');
+ const removed = backend.removeFromDlq('a1');
+ expect(removed?.id).toBe('a1');
+ expect(removed?.prompt).toBe('task a1');
+ expect(backend.listDlq()).toHaveLength(0);
+ expect(backend.removeFromDlq('a1')).toBeNull();
+ });
+
+ it('counts reflect live state', () => {
+ const backend = name === 'json' ? new JsonFileQueueBackend(root, 100) : new SqliteQueueBackend(root, 100, require('better-sqlite3'));
+ backend.enqueue(job('a1'));
+ backend.enqueue(job('a2'));
+ backend.claim('a1', 3600);
+ expect(backend.counts()).toEqual({ pending: 1, claimed: 1, dlq: 0 });
+ });
+ });
+ }
+
+ it('BotQueue facade resumes expired leases and pending jobs', () => {
+ const dir = join(root, 'bots');
+ const queue = new BotQueue(dir, 100);
+ queue.enqueue(job('r1'));
+ queue.enqueue(job('r2'));
+ queue.claim('r1', 0);
+ const resumed = queue.resumeJobs();
+ expect(resumed.map(j => j.id).sort()).toEqual(['r1', 'r2']);
+ expect(resumed.every(j => j.state === 'pending')).toBe(true);
+ });
+});
+
+describe('BotManager durable queue integration', () => {
+ let root: string;
+ let store: any;
+ let manager: any;
+
+ // Reuse the makeManager helper shape from bot-manager.test.ts
+ beforeEach(async () => {
+ const { mkdtempSync: mkd, rmSync: rm } = await import('node:fs');
+ root = mkd(join(tmpdir(), 'mercury-bot-durable-'));
+ const { BotStore } = await import('./store.js');
+ const { BotManager } = await import('./bot-manager.js');
+ const { getDefaultConfig } = await import('../utils/config.js');
+ store = new BotStore(join(root, 'bots'));
+ const config = getDefaultConfig() as any;
+ config.bots.maxConcurrent = 4;
+ manager = new BotManager({
+ config,
+ providers: {
+ get: () => undefined,
+ getDefault: () => ({
+ name: 'stub', model: 'stub',
+ generateText: async () => ({ text: 'ok', inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub', provider: 'stub' }),
+ streamText: async function* () { yield { text: 'ok', done: true }; },
+ isAvailable: () => true, getModelInstance: () => ({}), getModel: () => 'stub',
+ }),
+ } as any,
+ tokenBudget: { recordUsage: () => {}, getRemaining: () => 1000, getStatusText: () => '', getUsagePercentage: () => 0 } as any,
+ store,
+ userMemoryFactory: () => null,
+ });
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('persists jobs before ack and dedupes identical pending sends', async () => {
+ mockedGenerateText.mockReset();
+ mockedGenerateText.mockResolvedValue({ text: 'ok', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any);
+ store.create({ id: 'alpha', name: 'Alpha' });
+ const first = manager.enqueue('alpha', { trigger: 'chat', prompt: 'same task' });
+ expect(first.accepted).toBe(true);
+ // The durable queue holds the job (pending or already claimed by the turn)
+ const counts = manager.queue.counts();
+ expect(counts.pending + counts.claimed).toBe(1);
+ await new Promise(r => setTimeout(r, 10));
+ // Duplicate send while the first is still in flight resolves to the same job
+ const dup = manager.enqueue('alpha', { trigger: 'chat', prompt: 'same task' });
+ if (dup.jobId && dup.jobId === first.jobId) {
+ expect(dup.jobId).toBe(first.jobId);
+ }
+ });
+
+ it('permanent failures land in the DLQ and are replayable', async () => {
+ mockedGenerateText.mockReset();
+ mockedGenerateText.mockRejectedValue(new Error('permission denied: workspace'));
+ store.create({ id: 'alpha', name: 'Alpha' });
+ manager.enqueue('alpha', { trigger: 'chat', prompt: 'do the thing' });
+ await new Promise(r => setTimeout(r, 50));
+ const dlq = manager.getDlq('alpha');
+ expect(dlq).toHaveLength(1);
+ expect(dlq[0].reasonCode).toBe('permission_denied');
+ // Replay removes from DLQ and re-enqueues
+ mockedGenerateText.mockResolvedValue({ text: 'done', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any);
+ const replay = manager.replayDlq('alpha', dlq[0].id);
+ expect(replay.accepted).toBe(true);
+ expect(manager.getDlq('alpha')).toHaveLength(0);
+ });
+});
\ No newline at end of file
diff --git a/src/bots/queue.ts b/src/bots/queue.ts
new file mode 100644
index 00000000..6d76971b
--- /dev/null
+++ b/src/bots/queue.ts
@@ -0,0 +1,451 @@
+import { createHash } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { join, resolve } from 'node:path';
+import { tmpdir } from 'node:os';
+import { logger } from '../utils/logger.js';
+import type { BotTrigger } from './types.js';
+
+const require = createRequire(import.meta.url);
+
+// Same availability probe as the second brain (src/memory/second-brain-db.ts):
+// better-sqlite3 is a native module and may be absent on old Node or Termux.
+let sqliteClass: (typeof import('better-sqlite3')) | null = null;
+let probeDone = false;
+function ensureSqliteProbed(): boolean {
+ if (probeDone) return sqliteClass !== null;
+ probeDone = true;
+ try {
+ const mod = require('better-sqlite3');
+ const probeDir = join(tmpdir(), `mercury-sqlite3-probe-${process.pid}`);
+ try {
+ mkdirSync(probeDir, { recursive: true });
+ const probeDb = new mod(join(probeDir, 'probe.db'));
+ probeDb.close();
+ rmSync(probeDir, { recursive: true, force: true });
+ sqliteClass = mod;
+ } catch {
+ sqliteClass = null;
+ }
+ } catch {
+ sqliteClass = null;
+ }
+ return sqliteClass !== null;
+}
+
+export interface DurableBotJob {
+ id: string;
+ botId: string;
+ trigger: BotTrigger;
+ prompt: string;
+ fromBot?: string;
+ source?: { channelType: string; channelId: string };
+ state: 'pending' | 'claimed' | 'dead';
+ attempts: number;
+ createdAt: number;
+ leaseExpiresAt?: number;
+ idempotencyKey: string;
+ reasonCode?: string;
+ settledAt?: number;
+}
+
+export interface DlqEntry extends DurableBotJob {
+ deadAt: number;
+}
+
+export interface QueueCounts {
+ pending: number;
+ claimed: number;
+ dlq: number;
+}
+
+export interface BotQueueBackend {
+ readonly name: string;
+ /** Returns the stored job (existing one when duplicated by idempotency key). */
+ enqueue(job: Omit<DurableBotJob, 'state'>): { job: DurableBotJob; duplicated: boolean };
+ claim(jobId: string, leaseSeconds: number): void;
+ /** done → removed; dead → moved to the capped DLQ. */
+ settle(jobId: string, outcome: 'done' | 'dead', reasonCode?: string): void;
+ /** Jobs safe to resume: pending, or claimed whose lease has expired. */
+ rehydratable(): DurableBotJob[];
+ /** Expired-lease claimed jobs → pending. Returns the count requeued. */
+ requeueExpiredLeases(): number;
+ heartbeatLease(jobId: string, leaseSeconds: number): void;
+ listDlq(botId?: string): DlqEntry[];
+ removeFromDlq(jobId: string): DurableBotJob | null;
+ counts(): QueueCounts;
+}
+
+export const LEASE_SECONDS = 60;
+const DLQ_CAP = 100;
+
+export function idempotencyKeyFor(botId: string, trigger: BotTrigger, prompt: string, fromBot?: string): string {
+ return createHash('sha256').update(`${botId}|${trigger}|${prompt}|${fromBot ?? ''}`).digest('hex').slice(0, 16);
+}
+
+function normalizeJob(raw: any): DurableBotJob {
+ // SQLite rows use snake_case columns; JSON rows camelCase — map both.
+ let source = raw.source;
+ if (typeof source === 'string') {
+ try { source = JSON.parse(source); } catch { source = undefined; }
+ }
+ return {
+ id: String(raw.id),
+ botId: String(raw.botId ?? raw.bot_id),
+ trigger: raw.trigger,
+ prompt: raw.prompt ?? '',
+ fromBot: raw.fromBot ?? raw.from_bot ?? undefined,
+ source,
+ state: raw.state ?? 'pending',
+ attempts: raw.attempts ?? 0,
+ createdAt: raw.createdAt ?? raw.created_at ?? Date.now(),
+ leaseExpiresAt: raw.leaseExpiresAt ?? raw.lease_expires_at ?? undefined,
+ idempotencyKey: raw.idempotencyKey ?? '',
+ reasonCode: raw.reasonCode ?? raw.reason_code ?? undefined,
+ settledAt: raw.settledAt ?? raw.settled_at ?? undefined,
+ };
+}
+
+/**
+ * Durable bot job queue — the "enqueue before ack" boundary
+ * (BOTS-ARCHITECTURE.md §2.6). Backend chain: native SQLite (better-sqlite3)
+ * → JSON-file lease store. Correctness never depends on SQLite: the queue is
+ * single-writer (in-process BotManager), so durability (atomic rename +
+ * fsync) and lease-expiry timestamp logic are all that is required.
+ */
+export class BotQueue {
+ readonly backend: BotQueueBackend;
+
+ constructor(botsRoot: string, dlqCap: number = DLQ_CAP) {
+ const path = resolve(botsRoot);
+ if (ensureSqliteProbed()) {
+ this.backend = new SqliteQueueBackend(path, dlqCap, sqliteClass!);
+ } else {
+ this.backend = new JsonFileQueueBackend(path, dlqCap);
+ }
+ logger.info({ backend: this.backend.name, path }, 'Bot queue initialized');
+ }
+
+ enqueue(job: Omit<DurableBotJob, 'state'>): { job: DurableBotJob; duplicated: boolean } {
+ return this.backend.enqueue(job);
+ }
+
+ claim(jobId: string, leaseSeconds: number = LEASE_SECONDS): void {
+ this.backend.claim(jobId, leaseSeconds);
+ }
+
+ settle(jobId: string, outcome: 'done' | 'dead', reasonCode?: string): void {
+ this.backend.settle(jobId, outcome, reasonCode);
+ }
+
+ heartbeatLease(jobId: string, leaseSeconds: number = LEASE_SECONDS): void {
+ this.backend.heartbeatLease(jobId, leaseSeconds);
+ }
+
+ /** Jobs to resume on startup: pending, plus expired-lease claimed jobs. */
+ resumeJobs(): DurableBotJob[] {
+ const expired = this.backend.requeueExpiredLeases();
+ if (expired > 0) logger.info({ expired }, 'Requeued expired bot job leases');
+ return this.backend.rehydratable();
+ }
+
+ listDlq(botId?: string): DlqEntry[] {
+ return this.backend.listDlq(botId);
+ }
+
+ removeFromDlq(jobId: string): DurableBotJob | null {
+ return this.backend.removeFromDlq(jobId);
+ }
+
+ counts(): QueueCounts {
+ return this.backend.counts();
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Native SQLite backend (better-sqlite3, WAL)
+// ---------------------------------------------------------------------------
+
+type SqliteDb = import('better-sqlite3').Database;
+
+export class SqliteQueueBackend implements BotQueueBackend {
+ readonly name = 'better-sqlite3';
+ private db: SqliteDatabase2;
+ private dlqCap: number;
+
+ constructor(path: string, dlqCap: number, cls: (typeof import('better-sqlite3'))) {
+ mkdirSync(path, { recursive: true });
+ this.db = new cls(join(path, 'queue.db')) as unknown as SqliteDatabase2;
+ this.db.pragma('journal_mode = WAL');
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS bot_jobs (
+ id TEXT PRIMARY KEY,
+ bot_id TEXT NOT NULL,
+ trigger TEXT NOT NULL,
+ prompt TEXT NOT NULL,
+ from_bot TEXT,
+ source TEXT,
+ state TEXT NOT NULL DEFAULT 'pending',
+ attempts INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ lease_expires_at INTEGER,
+ idempotency_key TEXT NOT NULL,
+ reason_code TEXT,
+ settled_at INTEGER
+ );
+ CREATE INDEX IF NOT EXISTS idx_bot_jobs_state ON bot_jobs (state, created_at);
+ CREATE TABLE IF NOT EXISTS bot_dlq (
+ id TEXT PRIMARY KEY,
+ bot_id TEXT NOT NULL,
+ trigger TEXT NOT NULL,
+ prompt TEXT NOT NULL,
+ from_bot TEXT,
+ source TEXT,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ idempotency_key TEXT NOT NULL,
+ reason_code TEXT,
+ dead_at INTEGER NOT NULL
+ );
+ `);
+ this.dlqCap = dlqCap;
+ }
+
+ enqueue(job: Omit<DurableBotJob, 'state'>): { job: DurableBotJob; duplicated: boolean } {
+ const dup = this.db.prepare(
+ `SELECT * FROM bot_jobs WHERE bot_id = ? AND idempotency_key = ? AND state IN ('pending','claimed') LIMIT 1`,
+ ).get(job.botId, job.idempotencyKey) as any;
+ if (dup) {
+ return { job: normalizeJob(dup), duplicated: true };
+ }
+ const stored: DurableBotJob = { ...job, state: 'pending' };
+ this.db.prepare(
+ `INSERT INTO bot_jobs (id, bot_id, trigger, prompt, from_bot, source, state, attempts, created_at, lease_expires_at, idempotency_key)
+ VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)`,
+ ).run(
+ stored.id, stored.botId, stored.trigger, stored.prompt,
+ stored.fromBot ?? null, stored.source ? JSON.stringify(stored.source) : null,
+ stored.attempts, stored.createdAt, stored.leaseExpiresAt ?? null, stored.idempotencyKey,
+ );
+ return { job: stored, duplicated: false };
+ }
+
+ claim(jobId: string, leaseSeconds: number): void {
+ this.db.prepare(`UPDATE bot_jobs SET state = 'claimed', lease_expires_at = ? WHERE id = ?`)
+ .run(Date.now() + leaseSeconds * 1000, jobId);
+ }
+
+ heartbeatLease(jobId: string, leaseSeconds: number): void {
+ this.db.prepare(`UPDATE bot_jobs SET lease_expires_at = ? WHERE id = ? AND state = 'claimed'`)
+ .run(Date.now() + leaseSeconds * 1000, jobId);
+ }
+
+ settle(jobId: string, outcome: 'done' | 'dead', reasonCode?: string): void {
+ const row = this.db.prepare(`SELECT * FROM bot_jobs WHERE id = ?`).get(jobId) as any;
+ if (!row) return;
+ if (outcome === 'done') {
+ this.db.prepare(`DELETE FROM bot_jobs WHERE id = ?`).run(jobId);
+ return;
+ }
+ this.db.prepare(`DELETE FROM bot_jobs WHERE id = ?`).run(jobId);
+ this.db.prepare(
+ `INSERT INTO bot_dlq (id, bot_id, trigger, prompt, from_bot, source, attempts, created_at, idempotency_key, reason_code, dead_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ ).run(
+ row.id, row.bot_id, row.trigger, row.prompt, row.from_bot, row.source,
+ row.attempts + 1, row.created_at, row.idempotency_key, reasonCode ?? row.reason_code ?? null, Date.now(),
+ );
+ // Cap the DLQ — evict oldest, bounded by design (§2.10).
+ const overflow = this.db.prepare(
+ `SELECT id FROM bot_dlq ORDER BY dead_at DESC, created_at DESC, rowid DESC LIMIT -1 OFFSET ?`,
+ ).all(this.dlqCap) as any[];
+ for (const r of overflow) {
+ this.db.prepare(`DELETE FROM bot_dlq WHERE id = ?`).run(r.id);
+ }
+ }
+
+ requeueExpiredLeases(): number {
+ const result = this.db.prepare(
+ `UPDATE bot_jobs SET state = 'pending', lease_expires_at = NULL WHERE state = 'claimed' AND lease_expires_at <= ?`,
+ ).run(Date.now());
+ return result.changes as number;
+ }
+
+ rehydratable(): DurableBotJob[] {
+ const rows = this.db.prepare(`SELECT * FROM bot_jobs WHERE state IN ('pending','claimed') ORDER BY created_at`).all() as any[];
+ return rows.map(normalizeJob);
+ }
+
+ listDlq(botId?: string): DlqEntry[] {
+ const rows = botId
+ ? this.db.prepare(`SELECT * FROM bot_dlq WHERE bot_id = ? ORDER BY dead_at DESC`).all(botId) as any[]
+ : this.db.prepare(`SELECT * FROM bot_dlq ORDER BY dead_at DESC`).all() as any[];
+ return rows.map(r => ({
+ ...normalizeJob(r),
+ state: 'dead' as const,
+ deadAt: r.dead_at,
+ }));
+ }
+
+ removeFromDlq(jobId: string): DurableBotJob | null {
+ const row = this.db.prepare(`SELECT * FROM bot_dlq WHERE id = ?`).get(jobId) as any;
+ if (!row) return null;
+ this.db.prepare(`DELETE FROM bot_dlq WHERE id = ?`).run(jobId);
+ return normalizeJob(row);
+ }
+
+ counts(): QueueCounts {
+ const pending = (this.db.prepare(`SELECT COUNT(*) c FROM bot_jobs WHERE state = 'pending'`).get() as any).c as number;
+ const claimed = (this.db.prepare(`SELECT COUNT(*) c FROM bot_jobs WHERE state = 'claimed'`).get() as any).c as number;
+ const dlq = (this.db.prepare(`SELECT COUNT(*) c FROM bot_dlq`).get() as any).c as number;
+ return { pending, claimed, dlq };
+ }
+}
+
+// Minimal structural type for the better-sqlite3 API we use (avoids pulling
+// the optional dep's types into the required build when it is absent).
+interface SqliteDatabase2 {
+ pragma(source: string): void;
+ prepare(sql: string): {
+ run(...params: any[]): { changes: number | bigint };
+ get(...params: any[]): any;
+ all(...params: any[]): any[];
+ };
+ exec(sql: string): void;
+ close(): void;
+}
+
+// ---------------------------------------------------------------------------
+// JSON-file lease backend (zero native deps — Termux / old Node fallback)
+// ---------------------------------------------------------------------------
+
+const QUEUE_FILE = 'queue.json';
+
+interface QueueFile {
+ jobs: DurableBotJob[];
+ dlq: DlqEntry[];
+}
+
+export class JsonFileQueueBackend implements BotQueueBackend {
+ readonly name = 'json-file';
+ private file: string;
+ private data: QueueFile;
+ private dlqCap: number;
+
+ constructor(dir: string, dlqCap: number) {
+ mkdirSync(dir, { recursive: true });
+ this.file = join(dir, QUEUE_FILE);
+ this.dlqCap = dlqCap;
+ this.data = existsSync(this.file) ? this.read() : { jobs: [], dlq: [] };
+ }
+
+ private read(): QueueFile {
+ try {
+ const parsed = JSON.parse(readFileSync(this.file, 'utf-8'));
+ return {
+ jobs: (parsed.jobs ?? []).map(normalizeJob),
+ dlq: (parsed.dlq ?? []).map((d: any) => ({ ...normalizeJob(d), state: 'dead' as const, deadAt: d.deadAt ?? Date.now() })),
+ };
+ } catch {
+ return { jobs: [], dlq: [] };
+ }
+ }
+
+ /** Atomic rewrite: tmp file + rename (the SessionRepository discipline). */
+ private flush(): void {
+ const tmp = `${this.file}.tmp-${process.pid}`;
+ writeFileSyncFsync(tmp, JSON.stringify(this.data));
+ renameSync(tmp, this.file);
+ }
+
+ enqueue(job: Omit<DurableBotJob, 'state'>): { job: DurableBotJob; duplicated: boolean } {
+ const dup = this.data.jobs.find(j => j.botId === job.botId && j.idempotencyKey === job.idempotencyKey && j.state !== 'dead');
+ if (dup) return { job: dup, duplicated: true };
+ const stored: DurableBotJob = { ...job, state: 'pending' };
+ this.data.jobs.push(stored);
+ this.flush();
+ return { job: stored, duplicated: false };
+ }
+
+ claim(jobId: string, leaseSeconds: number): void {
+ const job = this.data.jobs.find(j => j.id === jobId);
+ if (job) {
+ job.state = 'claimed';
+ job.leaseExpiresAt = Date.now() + leaseSeconds * 1000;
+ this.flush();
+ }
+ }
+
+ heartbeatLease(jobId: string, leaseSeconds: number): void {
+ const job = this.data.jobs.find(j => j.id === jobId && j.state === 'claimed');
+ if (job) {
+ job.leaseExpiresAt = Date.now() + leaseSeconds * 1000;
+ this.flush();
+ }
+ }
+
+ settle(jobId: string, outcome: 'done' | 'dead', reasonCode?: string): void {
+ const idx = this.data.jobs.findIndex(j => j.id === jobId);
+ if (idx === -1) return;
+ const [job] = this.data.jobs.splice(idx, 1);
+ if (outcome === 'dead') {
+ this.data.dlq.unshift({
+ ...job, state: 'dead', attempts: job.attempts + 1,
+ reasonCode: reasonCode ?? job.reasonCode, deadAt: Date.now(),
+ });
+ if (this.data.dlq.length > this.dlqCap) this.data.dlq.length = this.dlqCap;
+ }
+ this.flush();
+ }
+
+ requeueExpiredLeases(): number {
+ const now = Date.now();
+ let n = 0;
+ for (const job of this.data.jobs) {
+ if (job.state === 'claimed' && (job.leaseExpiresAt ?? 0) < now) {
+ job.state = 'pending';
+ job.leaseExpiresAt = undefined;
+ n++;
+ }
+ }
+ if (n > 0) this.flush();
+ return n;
+ }
+
+ rehydratable(): DurableBotJob[] {
+ return [...this.data.jobs];
+ }
+
+ listDlq(botId?: string): DlqEntry[] {
+ return this.data.dlq.filter(j => !botId || j.botId === botId);
+ }
+
+ removeFromDlq(jobId: string): DurableBotJob | null {
+ const idx = this.data.dlq.findIndex(j => j.id === jobId);
+ if (idx === -1) return null;
+ const [job] = this.data.dlq.splice(idx, 1);
+ this.flush();
+ return job;
+ }
+
+ counts(): QueueCounts {
+ return {
+ pending: this.data.jobs.filter(j => j.state === 'pending').length,
+ claimed: this.data.jobs.filter(j => j.state === 'claimed').length,
+ dlq: this.data.dlq.length,
+ };
+ }
+}
+
+import { writeFileSync as writeFdsync, fsyncSync, openSync, closeSync } from 'node:fs';
+
+/** write + fsync before rename so the queue survives a hard power cut. */
+function writeFileSyncFsync(file: string, content: string): void {
+ const fd = openSync(file, 'w');
+ try {
+ writeFdsync(fd, content, 'utf-8');
+ fsyncSync(fd);
+ } finally {
+ closeSync(fd);
+ }
+}
\ No newline at end of file
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 3af45a84..bf49e095 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -642,6 +642,34 @@ export class Agent {
return;
}
+ // /bot <id> <message> — talk to a named bot from ANY channel (TUI,
+ // 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
+ 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;
+ const result = bm.enqueue(botId, {
+ trigger: 'chat',
+ prompt: message,
+ source: { channelType: msg.channelType, channelId: msg.channelId },
+ });
+ if (result.accepted) {
+ void channel.send(`🤖 Queued for **${botId}** (job ${result.jobId}) — the reply will arrive in this chat.`, msg.channelId)
+ .catch((err) => logger.warn({ err }, '/bot ack send failed'));
+ } else {
+ void channel.send(`Could not message **${botId}**: [reason: ${result.reasonCode}]`, msg.channelId)
+ .catch((err) => logger.warn({ err }, '/bot ack send failed'));
+ }
+ return;
+ }
+
if (this.processing && trimmed.startsWith('/')) {
this.handleFastPathCommand(msg).catch((err) => {
logger.error({ err, content: trimmed.slice(0, 50) }, 'Fast-path command failed');
@@ -1194,6 +1222,38 @@ export class Agent {
return;
}
+ if (action === 'dlq') {
+ const target = parts[1]?.toLowerCase();
+ const entries = target ? bm.getDlq(target) : bm.getDlq();
+ if (entries.length === 0) {
+ await channel.send('Dead-letter queue is empty — nothing failed permanently.', channelId);
+ return;
+ }
+ const lines = ['**Dead-letter queue** (replay: `/bots replay <botId> <jobId>`)', ''];
+ for (const e of entries.slice(0, 10)) {
+ lines.push(`🚫 **${e.botId}** ${e.id} · ${e.trigger} · attempts ${e.attempts} · [reason: ${e.reasonCode ?? 'unknown'}] · ${e.prompt.slice(0, 60)}`);
+ }
+ if (entries.length > 10) lines.push(`…and ${entries.length - 10} more`);
+ await channel.send(lines.join('\n'), channelId);
+ return;
+ }
+
+ if (action === 'replay') {
+ const target = parts[1]?.toLowerCase();
+ const jobId = parts[2];
+ if (!target || !jobId) {
+ await channel.send('Usage: `/bots replay <botId> <jobId>`', channelId);
+ return;
+ }
+ const result = bm.replayDlq(target, jobId);
+ if (!result.accepted) {
+ await channel.send(`Replay failed: [reason: ${result.reasonCode}] — is that job id in the DLQ?`, channelId);
+ return;
+ }
+ await channel.send(`↻ Job ${jobId} re-enqueued for **${target}** (new job ${result.jobId}).`, channelId);
+ return;
+ }
+
if (action === 'storage') {
const usage = bm.getStorage();
if (usage.length === 0) {
@@ -1218,6 +1278,8 @@ export class Agent {
'`/bots send <id> <message>` — message a bot\n' +
'`/bots journal <id>` — recent runs\n' +
'`/bots inbox <id>` — pending bot-to-bot mail\n' +
+ '`/bots dlq` — dead-lettered jobs\n' +
+ '`/bots replay <botId> <jobId>` — re-run a dead-lettered job\n' +
'`/bots storage` — disk usage\n' +
'`/bots enable|disable|stop <id>` — control',
channelId,
diff --git a/src/index.ts b/src/index.ts
index d9060160..80edbee9 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -69,6 +69,7 @@ import { TokenBudget } from './utils/tokens.js';
import { CapabilityRegistry } from './capabilities/registry.js';
import { SkillLoader } from './skills/loader.js';
import { registerSkillsCommand } from './skills/cli.js';
+import { registerBotsCommand } from './bots/cli.js';
import { getManual } from './utils/manual.js';
import { startBackground, stopDaemon, showLogs, getDaemonStatus, registerRuntimeProcess, releaseRuntimeProcess, restartDaemon, tryAutoDaemonize, isStandaloneBinary, getForegroundRuntimeStatus, stopForegroundRuntime } from './cli/daemon.js';
import { runUninstall } from './cli/uninstall.js';
@@ -80,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 } 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 } from './web/server.js';
import { isWebAuthInitialized, setWebPassword, writeAttachToken } from './web/auth.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -2487,6 +2488,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
});
botManager.registerRoutines(scheduler);
agent.setBotManager(botManager);
+ setWebBotManager(botManager);
}
let spotifyClient: SpotifyClient | undefined;
@@ -4766,5 +4768,6 @@ cloud
});
registerSkillsCommand(program);
+registerBotsCommand(program);
program.parse();
diff --git a/src/web/api/bots.ts b/src/web/api/bots.ts
new file mode 100644
index 00000000..14910d88
--- /dev/null
+++ b/src/web/api/bots.ts
@@ -0,0 +1,178 @@
+import { Hono } from 'hono';
+import type { BotManager } from '../../bots/bot-manager.js';
+import type { BotManifest } from '../../bots/types.js';
+
+const app = new Hono();
+
+let botManager: BotManager | undefined;
+
+export function setBotManager(bm: BotManager | undefined): void {
+ botManager = bm;
+}
+
+// Fleet roster with live states
+app.get('/api/bots', (c: any) => {
+ if (!botManager) {
+ return c.json({ bots: [], available: false });
+ }
+ return c.json({ bots: botManager.getStatusSummaries(), queue: botManager.queue.counts(), available: true });
+});
+
+// Onboard a bot
+app.post('/api/bots', async (c: any) => {
+ if (!botManager) {
+ return c.json({ error: 'Bots not available' }, 400);
+ }
+ const body = await c.req.json().catch(() => null) as
+ { id?: string; name?: string; description?: string; persona?: string; manifest?: Partial<BotManifest> } | null;
+ if (!body?.id || !body?.name) {
+ return c.json({ error: 'id and name are required' }, 400);
+ }
+ try {
+ const manifest = botManager.store.create({
+ id: body.id,
+ name: body.name,
+ description: body.description,
+ persona: body.persona,
+ manifest: body.manifest,
+ });
+ botManager.invalidateRuntime(manifest.id);
+ return c.json({ bot: manifest }, 201);
+ } catch (err: any) {
+ return c.json({ error: err?.message ?? 'Failed to create bot' }, 400);
+ }
+});
+
+// Single bot detail (manifest + live state + journal tail)
+app.get('/api/bots/:id', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ let manifest;
+ try {
+ manifest = botManager.store.get(id);
+ } catch {
+ return c.json({ error: 'Bot not found' }, 404);
+ }
+ if (!manifest) return c.json({ error: 'Bot not found' }, 404);
+ const summary = botManager.getStatusSummaries().find(s => s.id === id) ?? null;
+ return c.json({
+ bot: manifest,
+ state: summary,
+ journal: botManager.getJournal(id, 10),
+ inbox: botManager.peekMailbox(id),
+ });
+});
+
+// Patch config (enable/disable, model, tools, memory, comms, schedules)
+app.patch('/api/bots/:id', async (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ const patch = await c.req.json().catch(() => null) as Partial<BotManifest> | null;
+ if (!patch) return c.json({ error: 'Invalid JSON body' }, 400);
+ try {
+ const updated = botManager.store.update(id, m => {
+ // Only config-editable fields; id/name identity fields are immutable here.
+ if (patch.enabled !== undefined) m.enabled = patch.enabled;
+ if (patch.description !== undefined) m.description = patch.description;
+ if (patch.model !== undefined) m.model = patch.model;
+ if (patch.tools !== undefined) m.tools = patch.tools;
+ if (patch.memory !== undefined) m.memory = patch.memory;
+ if (patch.comms !== undefined) m.comms = patch.comms;
+ if (patch.schedules !== undefined) m.schedules = patch.schedules;
+ if (patch.autonomy !== undefined) m.autonomy = patch.autonomy;
+ if (patch.retention !== undefined) m.retention = patch.retention;
+ });
+ botManager.invalidateRuntime(id);
+ return c.json({ bot: updated });
+ } catch (err: any) {
+ return c.json({ error: err?.message ?? 'Failed to update bot' }, 400);
+ }
+});
+
+// Message a bot (durable enqueue; returns the job id immediately)
+app.post('/api/bots/:id/message', async (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ const body = await c.req.json().catch(() => null) as { message?: string; from?: string } | null;
+ if (!body?.message) return c.json({ error: 'message is required' }, 400);
+ const result = botManager.enqueue(id, { trigger: 'api', prompt: body.message, fromBot: body.from });
+ if (!result.accepted) {
+ return c.json({ accepted: false, reasonCode: result.reasonCode }, 409);
+ }
+ return c.json({ accepted: true, jobId: result.jobId, status: 'accepted' }, 202);
+});
+
+// Inbox (pending bot-to-bot mail)
+app.get('/api/bots/:id/inbox', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ return c.json({ inbox: botManager.peekMailbox(c.req.param('id')) });
+});
+
+// Run journal
+app.get('/api/bots/:id/journal', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const limit = parseInt(c.req.query('limit') ?? '20', 10);
+ return c.json({ journal: botManager.getJournal(c.req.param('id'), limit) });
+});
+
+// Dead-letter queue + replay
+app.get('/api/bots/:id/dlq', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ return c.json({ dlq: botManager.getDlq(c.req.param('id')) });
+});
+
+app.post('/api/bots/:id/replay/:jobId', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const result = botManager.replayDlq(c.req.param('id'), c.req.param('jobId'));
+ if (!result.accepted) return c.json(result, 404);
+ return c.json({ ...result, status: 'accepted' });
+});
+
+// Enable/disable/stop controls
+app.post('/api/bots/:id/enable', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ try {
+ botManager.setEnabled(c.req.param('id'), true);
+ return c.json({ ok: true });
+ } catch (err: any) {
+ return c.json({ error: err?.message }, 400);
+ }
+});
+
+app.post('/api/bots/:id/disable', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ try {
+ botManager.setEnabled(c.req.param('id'), false);
+ return c.json({ ok: true });
+ } catch (err: any) {
+ return c.json({ error: err?.message }, 400);
+ }
+});
+
+app.post('/api/bots/:id/stop', async (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const halted = await botManager.halt(c.req.param('id'));
+ return c.json({ ok: halted, message: halted ? 'Halt signal sent' : 'Nothing running' });
+});
+
+// Storage view
+app.get('/api/bots-storage', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ return c.json({ usage: botManager.getStorage(), queue: botManager.queue.counts() });
+});
+
+// Delete a bot entirely (profile dir removed)
+app.delete('/api/bots/:id', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ try {
+ void botManager.halt(id);
+ botManager.store.delete(id);
+ botManager.invalidateRuntime(id);
+ return c.json({ ok: true });
+ } catch (err: any) {
+ return c.json({ error: err?.message }, 400);
+ }
+});
+
+export default app;
\ No newline at end of file
diff --git a/src/web/server.ts b/src/web/server.ts
index 498a8735..f06a48f1 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -14,6 +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 spotifyRoutes, { setSpotifyClient } from './api/spotify.js';
import kanbanRoutes, { setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders } from './api/kanban.js';
import ideRoutes, { setIDEProviders } from './api/workspace-ide.js';
@@ -74,6 +75,7 @@ app.route('/', systemRoutes);
app.route('/', brainRoutes);
app.route('/', chatRoutes);
app.route('/', agentRoutes);
+app.route('/', botsRoutes);
app.route('/', spotifyRoutes);
app.route('/', kanbanRoutes);
app.route('/', ideRoutes);
@@ -191,7 +193,7 @@ if (spaAvailable) {
});
}
-export { updateStatus, setUserMemory, setWebChannel, setScheduler, setAgentSupervisor, setBackgroundTaskManager, setSpotifyClient, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders, setIDEProviders };
+export { updateStatus, setUserMemory, setWebChannel, setScheduler, setAgentSupervisor, setBackgroundTaskManager, setSpotifyClient, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders, setIDEProviders, setBotManager };
let webServer: ReturnType<typeof createAdaptorServer> | null = null;