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): cost view, run viewer, kill switch, DLQ clear, budget presets (ADR-022)

Salman Qureshi918a852b2a42
diff --git a/.lint-baseline.json b/.lint-baseline.json
index 14e9d7c8..61f86476 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-10T14:37:25.243Z",
+ "generatedAt": "2026-10-10T15:47:23.840Z",
"target": "src",
"rules": {
"(unknown)": 1,
@@ -9,7 +9,7 @@
"@typescript-eslint/no-require-imports": 6,
"@typescript-eslint/no-this-alias": 5,
"@typescript-eslint/no-unused-expressions": 100,
- "@typescript-eslint/no-unused-vars": 280,
+ "@typescript-eslint/no-unused-vars": 279,
"no-console": 135,
"no-control-regex": 27,
"no-func-assign": 5,
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e5f5daac..4c822e62 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,14 @@
# Changelog
+## Unreleased — see what the bots cost and did (ADR-022)
+
+- **`/bots cost [days]`** — token spend per bot and per fleet: today against the cap, the window's runs, failures, deliveries and empty runs. Also `GET /api/bots-cost`.
+- **`/bots show <id> [runId]`** — what a run actually did: the tool trace, delivered files, the reply, and a flag when the reply claimed more than the trace shows. Also `GET /api/bots/:id/runs[/:runId]`.
+- **Kill switch** — `/bots stop all` halts every bot and holds queued work; `/bots start all` resumes. Also `POST /api/bots-stop-all` / `-start-all`.
+- **`/bots dlq clear [id]`** — drop dead-lettered jobs (the journal keeps the runs). Also `DELETE /api/bots-dlq`.
+- **Onboarding budget presets** — `light` (1M/day), `standard` (the default, 5M), `heavy` (20M), a number, or `none`; the step also tells you where the bot's results will appear.
+- `GET /api/bots/:id/tasks` lists a lead's delegated tasks.
+
## Unreleased — fleets that coordinate (ADR-021)
Wave 2 of the bots work: how a lead hands out work and gets it back, how a bot remembers, and how a fleet's standard job runs without a lead turn between every step.
diff --git a/DECISIONS.md b/DECISIONS.md
index ed5e67d4..28fc5063 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -197,3 +197,9 @@
- **Crew lane**: `resolveProvider` sends a crew bot with no provider of its own to `bots.fleets.crewProvider` when set.
- **Alternatives considered**: tasks as rows in the SQLite queue (two backends to extend, no gain at this volume); waking the lead per result with a smarter prompt (still N turns); a scheduler-driven pipeline outside the task model (two orchestration paths); summarising the whole journal into the prompt (unbounded — five rows is the budget).
- **Consequence**: A fleet of five crew costs one lead turn to dispatch and one to synthesise, not seven. Pipelines run with zero lead turns in the middle. A bot's continuity is three things it never has to write: the journal digest, its note, and its memory. `bot_send(task)` callers see a digest instead of "✅ Task complete (job …)"; existing tests were updated accordingly. Wave 3 (cost views, run viewer, fleet kill switch, onboarding presets) is UI on top of this data.
+
+## ADR-022: Operating a fleet — cost, runs, kill switch
+
+- **Context**: ADR-020 and ADR-021 made bot behaviour bounded and legible in the journal, but the owner still had no view of where tokens went, no way to see what a run did without opening JSON files, no single stop, and a dead-letter queue full of pre-ADR-020 misclassified failures with no way to clear it. Onboarding presented the budget as optional.
+- **Decision**: Surfaces on top of the ADR-020/021 data, no new runtime behaviour: `BotJournal.usage(since)` aggregates runs, outcomes and tokens over rotations; `BotManager.costReport(days)` rolls bots up into fleets with today's spend against the effective cap; `listTranscripts` / `readTranscript` expose the per-run transcripts; `stopAll` / `startAll` cascade `stop` / `start` over every lead and solo; `clearDlq(botId?)` is implemented in both queue backends. The TUI gets `/bots cost`, `/bots show`, `/bots stop all` / `start all`, `/bots dlq clear`; the web API gets matching routes. Onboarding's budget step offers sizes (light / standard / heavy / number / none) with standard as the default that applies when the owner just types their first task, and names the deliverables folder.
+- **Consequence**: An owner can answer "what did this cost, what did it make, what did that run do, stop everything" from the chat. Pricing in currency is deliberately not shown: per-provider rates change and would be wrong more often than useful; tokens against caps is the stable unit.
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index e056f06c..f740e06b 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -11,7 +11,7 @@ import type { CapabilityRegistry } from '../capabilities/registry.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
import { UserMemoryStore as UserMemoryStoreImpl } from '../memory/user-memory.js';
import { BotStore, deliverableFileName, BOT_JOURNAL_FILENAME, BOT_PERMISSIONS_FILENAME, isValidCronExpression } from './store.js';
-import { BotJournal } from './journal.js';
+import { BotJournal, type BotTranscript, type BotUsage } from './journal.js';
import { BotQueue, idempotencyKeyFor, LEASE_SECONDS, type DurableBotJob } from './queue.js';
import { sweepSharedSandbox } from './retention.js';
import { proposeCrew } from './fleet-onboarding.js';
@@ -64,6 +64,26 @@ function replyTargetFor(job: BotJob): string | undefined {
return job.trigger === 'mailbox' && job.fromBot && job.prompt ? job.fromBot : undefined;
}
+export interface BotCostRow {
+ id: string;
+ name: string;
+ parent?: string;
+ today: BotUsage;
+ window: BotUsage;
+ /** Daily cap in effect (0 = unlimited). */
+ cap: number;
+ paused: boolean;
+}
+
+export interface BotCostReport {
+ days: number;
+ bots: BotCostRow[];
+ fleets: Array<{ id: string; name: string; members: number; today: BotUsage; window: BotUsage }>;
+ fleetToday: number;
+ fleetCap: number;
+ fleetPaused: boolean;
+}
+
export interface BotSendResult {
accepted: boolean;
jobId?: string;
@@ -1673,6 +1693,71 @@ export class BotManager {
return this.journalFor(botId).read(botId, limit);
}
+ /** Drop dead-lettered jobs (one bot or all); the journal still has the runs. */
+ clearDlq(botId?: string): number {
+ const n = this.queue.clearDlq(botId);
+ if (botId) { if (!this.getDlq(botId).length) this.needsYou.delete(botId); }
+ else this.needsYou.clear();
+ return n;
+ }
+
+ /**
+ * Where the tokens go (ADR-022): per bot — today's spend against its cap
+ * and the totals over a window — rolled up per fleet.
+ */
+ costReport(days = 7): BotCostReport {
+ const now = Date.now();
+ const dayStart = Date.parse(new Date(now).toISOString().slice(0, 10) + 'T00:00:00Z');
+ const since = now - days * 24 * 60 * 60 * 1000;
+ const bots: BotCostRow[] = [];
+ for (const m of this.store.list()) {
+ const journal = this.journalFor(m.id);
+ const today = journal.usage(m.id, dayStart);
+ const window = journal.usage(m.id, since);
+ bots.push({ id: m.id, name: m.name, parent: m.parent, today, window, cap: this.dailyCapFor(m), paused: this.pausedForBudget.has(m.id) });
+ }
+ const fleets = bots.filter(b => !b.parent).map(lead => {
+ const members = bots.filter(b => b.parent === lead.id || b.id === lead.id);
+ const sum = (pick: (b: BotCostRow) => BotUsage) => members.reduce((acc, b) => { const u = pick(b); acc.runs += u.runs; acc.tokensIn += u.tokensIn; acc.tokensOut += u.tokensOut; acc.deliverables += u.deliverables; acc.noOutcome += u.noOutcome; acc.completed += u.completed; acc.failed += u.failed; return acc; }, { runs: 0, completed: 0, failed: 0, noOutcome: 0, deliverables: 0, tokensIn: 0, tokensOut: 0 });
+ return { id: lead.id, name: lead.name, members: members.length, today: sum(b => b.today), window: sum(b => b.window) };
+ });
+ const fleetCap = this.config.bots?.fleetDailyTokenBudget ?? 0;
+ const fleetToday = this.fleetDailyTokens.day === new Date(now).toISOString().slice(0, 10) ? this.fleetDailyTokens.tokens : 0;
+ return { days, bots, fleets, fleetToday, fleetCap, fleetPaused: this.fleetPausedDay === new Date(now).toISOString().slice(0, 10) };
+ }
+
+ /** Fleet kill switch: stop every lead and solo (crew cascade), hold their jobs. */
+ async stopAll(): Promise<{ stopped: number; halted: number; heldJobs: number }> {
+ let stopped = 0, halted = 0, heldJobs = 0;
+ for (const m of this.store.list()) {
+ if (m.parent) continue;
+ const r = await this.stop(m.id);
+ stopped += 1 + r.crewStopped;
+ if (r.halted) halted++;
+ heldJobs += r.heldJobs;
+ }
+ logger.warn({ stopped, halted, heldJobs }, 'All bots stopped (kill switch)');
+ return { stopped, halted, heldJobs };
+ }
+
+ startAll(): { started: number; resumed: number } {
+ let started = 0, resumed = 0;
+ for (const m of this.store.list()) {
+ if (m.parent || !m.enabled) continue;
+ resumed += this.start(m.id).resumed;
+ started++;
+ }
+ return { started, resumed };
+ }
+
+ listTranscripts(botId: string): Array<{ runId: string; mtimeMs: number }> {
+ return this.journalFor(botId).listTranscripts(botId).map(t => ({ runId: t.runId, mtimeMs: t.mtimeMs }));
+ }
+
+ readTranscript(botId: string, runId?: string): BotTranscript | null {
+ return this.journalFor(botId).readTranscript(botId, runId);
+ }
+
getDlq(botId?: string): DurableBotJob[] {
return this.queue.listDlq(botId);
}
diff --git a/src/bots/fleet-tasks.test.ts b/src/bots/fleet-tasks.test.ts
index f65ed5cb..1ddd205a 100644
--- a/src/bots/fleet-tasks.test.ts
+++ b/src/bots/fleet-tasks.test.ts
@@ -270,3 +270,112 @@ describe('fleet tasks (ADR-021)', () => {
expect(DEFAULT_TASK_DEADLINE_MINUTES).toBe(120);
});
});
+
+// ── ADR-022: cost view, run viewer, kill switch, DLQ clear ────────────────
+
+describe('fleet operations (ADR-022)', () => {
+ let root: string;
+ let store: BotStore;
+ let manager: BotManager;
+ const managers: BotManager[] = [];
+ type StepOpts2 = { onStepFinish?: (step: { usage?: { inputTokens?: number; outputTokens?: number }; toolCalls?: unknown[]; toolResults?: unknown[] }) => void };
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-fleet-ops-'));
+ store = new BotStore(join(root, 'bots'));
+ const config = getDefaultConfig() as MercuryConfig;
+ config.bots.maxConcurrent = 4;
+ config.bots.fleetDailyTokenBudget = 1_000_000;
+ manager = new BotManager({ config, providers, tokenBudget, store, userMemoryFactory: () => null });
+ managers.push(manager);
+ mockedGenerateText.mockReset();
+ store.create({ id: 'lead', name: 'Lead', manifest: { fleetRole: 'lead' } });
+ manager.addCrew('lead', { id: 'alpha', name: 'Alpha' });
+ });
+ afterEach(() => {
+ for (const m of managers.splice(0)) m.dispose();
+ rmSync(root, { recursive: true, force: true });
+ });
+ const idle = (botId: string) => vi.waitFor(() => {
+ expect(manager.getStatusSummaries().find(s => s.id === botId)?.state).not.toBe('running');
+ expect(manager.getQueuedCount(botId)).toBe(0);
+ });
+
+ it('cost report: per-bot today vs cap, window totals, fleet rollup, empty-run count', async () => {
+ mockedGenerateText.mockImplementation((async (opts: StepOpts2) => {
+ opts.onStepFinish?.({ usage: { inputTokens: 1000, outputTokens: 100 }, toolCalls: [], toolResults: [] });
+ return reply('did a thing');
+ }) as never);
+ manager.enqueue('alpha', { trigger: 'chat', prompt: 'a' });
+ await idle('alpha');
+ manager.enqueue('lead', { trigger: 'cron', prompt: 'cycle', routineId: 'bot:lead:cycle' });
+ await idle('lead');
+ const report = manager.costReport(7);
+ const alpha = report.bots.find(b => b.id === 'alpha')!;
+ expect(alpha.today.tokensIn).toBe(1000);
+ expect(alpha.today.tokensOut).toBe(100);
+ expect(alpha.cap).toBe(5_000_000);
+ const lead = report.bots.find(b => b.id === 'lead')!;
+ expect(lead.window.noOutcome).toBe(1); // cron run with no deliverable/action
+ expect(report.fleets).toEqual([expect.objectContaining({ id: 'lead', members: 2 })]);
+ expect(report.fleets[0].window.runs).toBe(2);
+ expect(report.fleetCap).toBe(1_000_000);
+ expect(report.fleetToday).toBeGreaterThan(0);
+ });
+
+ it('transcripts: list and read a run, newest by default', async () => {
+ mockedGenerateText.mockImplementation((async () => reply('first reply')) as never);
+ manager.enqueue('alpha', { trigger: 'chat', prompt: 'one' });
+ await idle('alpha');
+ mockedGenerateText.mockImplementation((async () => reply('second reply')) as never);
+ manager.enqueue('alpha', { trigger: 'chat', prompt: 'two' });
+ await idle('alpha');
+ const runs = manager.listTranscripts('alpha');
+ expect(runs).toHaveLength(2);
+ const latest = manager.readTranscript('alpha')!;
+ expect(latest.output).toBe('second reply');
+ expect(latest.prompt).toBe('two');
+ expect(manager.readTranscript('alpha', runs[1].runId)?.output).toBe('first reply');
+ expect(manager.readTranscript('alpha', 'nope')).toBeNull();
+ });
+
+ it('kill switch stops every fleet and holds queued work; start all resumes', async () => {
+ let release!: () => void;
+ mockedGenerateText.mockImplementation((async (opts: { messages?: Array<{ content: string }> }) => {
+ if (opts.messages?.at(-1)?.content === 'slow') return new Promise((resolve) => { release = () => resolve(reply('late')); });
+ return reply('ok');
+ }) as never);
+ manager.enqueue('alpha', { trigger: 'chat', prompt: 'slow' });
+ manager.enqueue('alpha', { trigger: 'chat', prompt: 'queued one' });
+ await vi.waitFor(() => expect(manager.getStatusSummaries().find(s => s.id === 'alpha')?.state).toBe('running'));
+ const r = await manager.stopAll();
+ expect(r.stopped).toBe(2);
+ expect(r.halted).toBe(1);
+ expect(r.heldJobs).toBe(1);
+ release();
+ await idle('alpha');
+ // Held: nothing resumes on its own.
+ expect(manager.queue.pendingJobs('alpha')).toHaveLength(1);
+ const s = manager.startAll();
+ expect(s.started).toBe(1);
+ expect(s.resumed).toBe(1);
+ await idle('alpha');
+ expect(manager.queue.pendingJobs('alpha')).toHaveLength(0);
+ });
+
+ it('dlq clear drops dead jobs for one bot or all and clears the needs-you badge', async () => {
+ mockedGenerateText.mockImplementation((async () => { throw new Error('No LLM providers available — configure one'); }) as never);
+ manager.enqueue('alpha', { trigger: 'chat', prompt: 'x' });
+ await idle('alpha');
+ manager.enqueue('lead', { trigger: 'chat', prompt: 'y' });
+ await idle('lead');
+ await vi.waitFor(() => expect(manager.getDlq()).toHaveLength(2));
+ expect(manager.getStatusSummaries().find(s => s.id === 'alpha')?.needsYou).toBe(true);
+ expect(manager.clearDlq('alpha')).toBe(1);
+ expect(manager.getDlq('alpha')).toHaveLength(0);
+ expect(manager.getStatusSummaries().find(s => s.id === 'alpha')?.needsYou).toBe(false);
+ expect(manager.clearDlq()).toBe(1);
+ expect(manager.getDlq()).toHaveLength(0);
+ expect(manager.clearDlq()).toBe(0);
+ });
+});
diff --git a/src/bots/journal.ts b/src/bots/journal.ts
index 733ca3c1..8f74e4d8 100644
--- a/src/bots/journal.ts
+++ b/src/bots/journal.ts
@@ -84,6 +84,52 @@ export class BotJournal {
return { total, completed, failed, bytes };
}
+ /** Token and outcome totals for runs that started since `sinceMs` (all rotations). */
+ usage(botId: string, sinceMs = 0): BotUsage {
+ assertValidBotId(botId);
+ const out: BotUsage = { runs: 0, completed: 0, failed: 0, noOutcome: 0, deliverables: 0, tokensIn: 0, tokensOut: 0 };
+ const files = [join(this.dir, BOT_JOURNAL_FILENAME), ...rotationFiles(this.dir, this.keepRotations)];
+ for (const f of files) {
+ if (!existsSync(f)) continue;
+ for (const rec of readLines(f)) {
+ if ((rec.turnStartedAt ?? rec.startedAt) < sinceMs) continue;
+ out.runs++;
+ if (rec.state === 'completed') out.completed++;
+ if (rec.state === 'failed') out.failed++;
+ if (rec.outcome === 'none' && (rec.trigger === 'cron' || rec.trigger === 'api')) out.noOutcome++;
+ out.deliverables += rec.deliverables?.length ?? 0;
+ out.tokensIn += rec.tokensIn || 0;
+ out.tokensOut += rec.tokensOut || 0;
+ }
+ }
+ return out;
+ }
+
+ /** Transcript files, newest first (name = <when>-<runId>.json). */
+ listTranscripts(botId: string): Array<{ runId: string; file: string; mtimeMs: number }> {
+ assertValidBotId(botId);
+ const dir = join(this.dir, BOT_TRANSCRIPTS_DIRNAME);
+ try {
+ return readdirSync(dir)
+ .filter(n => n.endsWith('.json'))
+ .map(n => ({ runId: n.replace(/\.json$/, '').split('-').pop() ?? '', file: join(dir, n), mtimeMs: statSync(join(dir, n)).mtimeMs }))
+ .sort((a, b) => b.mtimeMs - a.mtimeMs);
+ } catch {
+ return [];
+ }
+ }
+
+ /** One run's transcript; the newest when no run id is given. */
+ readTranscript(botId: string, runId?: string): BotTranscript | null {
+ const entry = runId ? this.listTranscripts(botId).find(t => t.runId === runId) : this.listTranscripts(botId)[0];
+ if (!entry) return null;
+ try {
+ return JSON.parse(readFileSync(entry.file, 'utf-8')) as BotTranscript;
+ } catch {
+ return null;
+ }
+ }
+
private rotateIfNeeded(): void {
const file = join(this.dir, BOT_JOURNAL_FILENAME);
if (!existsSync(file) || statSync(file).size < this.rotateBytes) return;
@@ -99,6 +145,24 @@ export class BotJournal {
}
}
+export interface BotUsage {
+ runs: number;
+ completed: number;
+ failed: number;
+ /** Unattended runs that produced no deliverable or action. */
+ noOutcome: number;
+ deliverables: number;
+ tokensIn: number;
+ tokensOut: number;
+}
+
+export interface BotTranscript {
+ record: BotRunRecord;
+ prompt: string;
+ output: string;
+ trace: Array<{ name: string; ok: boolean; arg?: string; task?: boolean }>;
+}
+
/** Tail-read chunk: one journal line is ~300 bytes, so 64KB ≈ 200 records —
* far more than any viewer asks for, without scanning a 5MB rotated file. */
const READ_CHUNK_BYTES = 64 * 1024;
diff --git a/src/bots/queue.ts b/src/bots/queue.ts
index 7a538dc8..dce41f62 100644
--- a/src/bots/queue.ts
+++ b/src/bots/queue.ts
@@ -69,6 +69,8 @@ export interface BotQueueBackend {
/** Read a DLQ entry without removing it (replay does lookup-then-remove so a bot mismatch never destroys the entry). */
peekDlq(jobId: string): DurableBotJob | null;
removeFromDlq(jobId: string): DurableBotJob | null;
+ /** Drop every dead-lettered job (of one bot, or all). Returns the count removed. */
+ clearDlq(botId?: string): number;
/** Durable bot-to-bot mailbox (§2.6: a handoff must survive a crash). */
enqueueMail(mail: Omit<DurableMail, 'id'>): string;
drainMail(botId: string): DurableMail[];
@@ -212,6 +214,11 @@ export class BotQueue {
return this.backend.peekDlq(jobId);
}
+ clearDlq(botId?: string): number {
+ if (this.closed) return 0;
+ return this.backend.clearDlq(botId);
+ }
+
heartbeatLease(jobId: string, leaseSeconds: number = LEASE_SECONDS): void {
if (this.closed) return;
this.backend.heartbeatLease(jobId, leaseSeconds);
@@ -432,6 +439,13 @@ export class SqliteQueueBackend implements BotQueueBackend {
return normalizeJob(row);
}
+ clearDlq(botId?: string): number {
+ const before = (this.db.prepare(botId ? `SELECT COUNT(*) AS n FROM bot_dlq WHERE bot_id = ?` : `SELECT COUNT(*) AS n FROM bot_dlq`).get(...(botId ? [botId] : [])) as { n: number }).n;
+ if (botId) this.db.prepare(`DELETE FROM bot_dlq WHERE bot_id = ?`).run(botId);
+ else this.db.prepare(`DELETE FROM bot_dlq`).run();
+ return before;
+ }
+
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;
@@ -627,6 +641,13 @@ export class JsonFileQueueBackend implements BotQueueBackend {
return job;
}
+ clearDlq(botId?: string): number {
+ const before = this.data.dlq.length;
+ this.data.dlq = botId ? this.data.dlq.filter(j => j.botId !== botId) : [];
+ if (this.data.dlq.length !== before) this.flush();
+ return before - this.data.dlq.length;
+ }
+
counts(): QueueCounts {
return {
pending: this.data.jobs.filter(j => j.state === 'pending').length,
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 287fbc37..b61b9a11 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -1141,17 +1141,20 @@ export class Agent {
await this.offerFleetStep(bm, botId, manifest.name, msg, channel);
}
- // Final onboarding step: the daily token budget — optional and OFF by
- // default (no cap). "suggest" fills a generous number so heavy bots are
- // protected from runaway spend without ever being strangled.
- const suggested = this.config.bots?.suggestedDailyTokenBudget ?? 5_000_000;
+ // 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;
this.pendingBudgetFor = botId;
+ const home = homedir();
+ const folder = bm.store.deliverablesDir(botId);
await channel.send(
- `Final setup step — **daily token budget** for **${manifest.name}** (tokens/day):\n` +
- `• \`suggest\` — recommended, generous: ${suggested.toLocaleString()}/day\n` +
- `• a number — set your own cap\n` +
- `• \`none\` (or \`skip\`) — no cap (default)\n` +
- `Editable anytime: \`/bots budget ${botId} <tokens|suggest|none>\`. Or just type your first task — the budget stays unset.`,
+ `Last step — how much may **${manifest.name}** spend per day?\n` +
+ `• \`light\` — 1M tokens/day (a few runs)\n` +
+ `• \`standard\` — ${standard.toLocaleString()}/day (default — just type your first task)\n` +
+ `• \`heavy\` — 20M/day (a busy fleet)\n` +
+ `• 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}`,
).catch(() => {});
}
@@ -1255,7 +1258,7 @@ export class Agent {
/** Apply the budget answer typed after the persona step (or a later task). */
private async applyBudgetAnswer(bm: import('../bots/bot-manager.js').BotManager, botId: string, message: string, msg: ChannelMessage): Promise<boolean> {
const value = message.trim().toLowerCase();
- const isBudgetCommand = /^\d+$/.test(value) || ['suggest', 'none', 'skip'].includes(value);
+ const isBudgetCommand = /^\d+$/.test(value) || ['suggest', 'none', 'skip', 'light', 'standard', 'heavy', 'unlimited'].includes(value);
if (!isBudgetCommand) {
// Not a budget answer — treat as the user's first task; budget stays unset.
this.pendingBudgetFor = null;
@@ -1265,12 +1268,17 @@ export class Agent {
const manifest = bm.store.get(botId);
const suggested = this.config.bots?.suggestedDailyTokenBudget ?? 5_000_000;
let applied: string;
- if (value === 'suggest') {
- bm.store.update(botId, m => { m.autonomy = { ...m.autonomy, dailyTokenBudget: suggested }; });
- applied = `${suggested.toLocaleString()}/day`;
- } else if (value === 'none' || value === 'skip') {
+ const presets: Record<string, number> = { light: 1_000_000, heavy: 20_000_000 };
+ if (value === 'suggest' || value === 'standard' || value === 'skip') {
+ // The fleet default applies (ADR-020): nothing to write.
bm.store.update(botId, m => { if (m.autonomy) delete m.autonomy.dailyTokenBudget; });
+ applied = `${suggested.toLocaleString()}/day (default)`;
+ } else if (value === 'none' || value === 'unlimited') {
+ bm.store.update(botId, m => { m.autonomy = { ...m.autonomy, dailyTokenBudget: 0 }; });
applied = 'no cap (unlimited)';
+ } else if (presets[value]) {
+ bm.store.update(botId, m => { m.autonomy = { ...m.autonomy, dailyTokenBudget: presets[value] }; });
+ applied = `${presets[value].toLocaleString()}/day`;
} else {
const n = parseInt(value, 10);
bm.store.update(botId, m => { m.autonomy = { ...m.autonomy, dailyTokenBudget: n }; });
diff --git a/src/core/commands/bots-command.ts b/src/core/commands/bots-command.ts
index e765eaf0..61f053ac 100644
--- a/src/core/commands/bots-command.ts
+++ b/src/core/commands/bots-command.ts
@@ -344,7 +344,12 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan
if (action === 'stop' || action === 'pause') {
const target = parts[1]?.toLowerCase();
if (!target) {
- await channel.send('Usage: `/bots stop <id>`', channelId);
+ await channel.send('Usage: `/bots stop <id>` or `/bots stop all` (kill switch — every bot halts, queued work is held)', channelId);
+ return;
+ }
+ if (target === 'all') {
+ const r = await bm.stopAll();
+ await channel.send(`🛑 Kill switch: ${r.stopped} bot(s) stopped, ${r.halted} running turn(s) halted, ${r.heldJobs} queued job(s) held. Nothing runs until \`/bots start all\` (or per bot).`, channelId);
return;
}
const result = await bm.stop(target);
@@ -355,6 +360,12 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan
: `⛔ **${target}** stopped — nothing was running.${crewNote}${heldNote}`, channelId);
}
+ if (action === 'start' && parts[1]?.toLowerCase() === 'all') {
+ const r = bm.startAll();
+ await channel.send(`▶ Started ${r.started} fleet(s)/solo bot(s); ${r.resumed} held job(s) resumed; paused routines cleared.`, channelId);
+ return;
+ }
+
if (action === 'start') {
const target = parts[1]?.toLowerCase();
if (!target) {
@@ -440,13 +451,24 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan
}
if (action === 'dlq') {
+ // /bots dlq clear [id] — drop dead-lettered jobs (the journal keeps the runs).
+ if (parts[1]?.toLowerCase() === 'clear') {
+ const target = parts[2]?.toLowerCase();
+ if (target && !bm.store.exists(target)) {
+ await channel.send(`No bot "${target}".`, channelId);
+ return;
+ }
+ const n = bm.clearDlq(target);
+ await channel.send(n > 0 ? `🧹 Cleared ${n} dead-lettered job(s)${target ? ` for **${target}**` : ''}. The runs stay in \`/bots journal\`.` : 'Dead-letter queue was already empty.', channelId);
+ return;
+ }
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>`)', ''];
+ const lines = ['**Dead-letter queue** (replay: `/bots replay <botId> <jobId>` · clear: `/bots dlq clear [id]`)', ''];
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)}`);
}
@@ -637,6 +659,64 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan
return;
}
+ if (action === 'cost' || action === 'usage') {
+ // /bots cost [days] — where the tokens go, per bot and per fleet.
+ const days = Math.max(1, Math.min(90, parseInt(parts[1] ?? '7', 10) || 7));
+ const report = bm.costReport(days);
+ if (report.bots.length === 0) {
+ await channel.send('No bots configured.', channelId);
+ return;
+ }
+ const k = (n: number) => n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
+ const lines = [`**Bot token spend** — today and the last ${days} days`, ''];
+ if (report.fleetCap > 0) lines.push(`Fleet today: ${k(report.fleetToday)} / ${k(report.fleetCap)}${report.fleetPaused ? ' · ⛔ paused (cap reached)' : ''}`, '');
+ for (const fleet of report.fleets) {
+ const lead = report.bots.find(b => b.id === fleet.id)!;
+ const members = report.bots.filter(b => b.parent === fleet.id);
+ const row = (b: typeof lead, indent: string) => {
+ const capNote = b.cap > 0 ? ` / ${k(b.cap)}${b.paused ? ' ⛔' : ''}` : ' (no cap)';
+ const w = b.window;
+ const empty = w.noOutcome > 0 ? ` · ⚠ ${w.noOutcome} empty` : '';
+ return `${indent}**${b.name}** — today ${k(b.today.tokensIn + b.today.tokensOut)}${capNote} · ${days}d ${k(w.tokensIn + w.tokensOut)} in ${w.runs} runs (${w.failed} failed, ${w.deliverables} delivered${empty})`;
+ };
+ lines.push(row(lead, members.length ? '👑 ' : ''));
+ for (const m of members) lines.push(row(m, ' └─ '));
+ if (members.length) lines.push(` fleet total: ${days}d ${k(fleet.window.tokensIn + fleet.window.tokensOut)} · ${fleet.window.deliverables} delivered`);
+ }
+ const total = report.bots.reduce((a, b) => a + b.window.tokensIn + b.window.tokensOut, 0);
+ lines.push('', `All bots, ${days}d: ${k(total)} tokens. \`/bots budget <id>\` sets a cap; \`/bots show <id>\` opens a run.`);
+ await channel.send(lines.join('\n'), channelId);
+ return;
+ }
+
+ if (action === 'show' || action === 'transcript') {
+ // /bots show <id> [runId] — what a run actually did.
+ const target = parts[1]?.toLowerCase();
+ if (!target || !bm.store.exists(target)) {
+ await channel.send('Usage: `/bots show <id> [runId]` — the tool trace and reply of a run (newest when no id).', channelId);
+ return;
+ }
+ const t = bm.readTranscript(target, parts[2]);
+ if (!t) {
+ await channel.send(`No transcript${parts[2] ? ` for run ${parts[2]}` : ''} — transcripts exist for runs made after the governance update.`, channelId);
+ return;
+ }
+ const r = t.record;
+ const lines = [`**${target} · run ${r.runId}** — ${r.trigger} · ${r.state}${r.outcome ? ` · ${r.outcome}` : ''} · ${(r.tokensIn + r.tokensOut).toLocaleString()} tok · ${r.steps ?? '?'} steps${r.reasonCode ? ` · [${r.reasonCode}]` : ''}`, ''];
+ if (t.prompt) lines.push(`**Task:** ${t.prompt.replace(/\s+/g, ' ').slice(0, 240)}`, '');
+ if (t.trace.length > 0) {
+ lines.push(`**Tools (${t.trace.length}):**`);
+ for (const step of t.trace.slice(0, 25)) lines.push(`${step.ok ? '✓' : '✗'} ${step.name}${step.arg ? ` ${step.arg.slice(0, 70)}` : ''}`);
+ if (t.trace.length > 25) lines.push(`…and ${t.trace.length - 25} more`);
+ lines.push('');
+ }
+ for (const d of r.deliverables ?? []) lines.push(`📁 ${tildify(d)}`);
+ if (r.claimedWithoutAction) lines.push('⚠ The reply claimed delivery or execution the trace does not show.');
+ lines.push('', `**Reply:** ${t.output.slice(0, 1200)}${t.output.length > 1200 ? '…' : ''}`);
+ await channel.send(lines.join('\n'), channelId);
+ return;
+ }
+
if (action === 'tasks') {
// /bots tasks <leadId> — what a lead has delegated and what came back.
const target = parts[1]?.toLowerCase();
@@ -706,7 +786,10 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan
'`/bots edit <id> <field> <value>` — edit any config field anytime\n' +
'`/bots journal <id>` — recent runs\n' +
'`/bots inbox <id>` — pending bot-to-bot mail\n' +
- '`/bots dlq` — dead-lettered jobs\n' +
+ '`/bots dlq [clear [id]]` — dead-lettered jobs; clear drops them\n' +
+ '`/bots cost [days]` — token spend per bot and fleet, against caps\n' +
+ '`/bots show <id> [runId]` — what a run actually did (tools, deliverables, reply)\n' +
+ '`/bots stop all` / `/bots start all` — fleet kill switch\n' +
'`/bots replay <botId> <jobId>` — re-run a dead-lettered job\n' +
'`/bots storage` — disk usage\n' +
'`/bots enable|disable|stop|start <id>` — control (stop holds queued jobs; start resumes them)\n' +
diff --git a/src/web/api/bots.test.ts b/src/web/api/bots.test.ts
index 563407be..6520e6a4 100644
--- a/src/web/api/bots.test.ts
+++ b/src/web/api/bots.test.ts
@@ -176,4 +176,23 @@ describe('web bots API — cockpit', () => {
// Malformed bundle → 400
expect((await app.request('/api/bots/import', { method: 'POST', body: JSON.stringify({ nope: true }), headers: { 'Content-Type': 'application/json' } })).status).toBe(400);
});
-});
\ No newline at end of file
+});
+describe('web bots API — operations (ADR-022)', () => {
+ it('cost, tasks, runs, dlq clear and the kill switch are reachable', async () => {
+ store.create({ id: 'solo', name: 'Solo' });
+ const cost = await jreq(await app.request('/api/bots-cost?days=3'));
+ expect(cost.days).toBe(3);
+ expect(cost.bots.map((b: { id: string }) => b.id)).toContain('solo');
+ expect((await app.request('/api/bots/solo/tasks')).status).toBe(200);
+ expect((await app.request('/api/bots/ghost/tasks')).status).toBe(404);
+ const runs = await jreq(await app.request('/api/bots/solo/runs'));
+ expect(runs.runs).toEqual([]);
+ expect((await app.request('/api/bots/solo/runs/latest')).status).toBe(404);
+ expect(await jreq(await app.request('/api/bots-dlq', { method: 'DELETE' }))).toEqual({ cleared: 0 });
+ expect((await app.request('/api/bots-dlq?bot=ghost', { method: 'DELETE' })).status).toBe(404);
+ const stopped = await jreq(await app.request('/api/bots-stop-all', { method: 'POST' }));
+ expect(stopped.stopped).toBe(1);
+ const started = await jreq(await app.request('/api/bots-start-all', { method: 'POST' }));
+ expect(started.started).toBe(1);
+ });
+});
diff --git a/src/web/api/bots.ts b/src/web/api/bots.ts
index a87441c0..fa4dc35f 100644
--- a/src/web/api/bots.ts
+++ b/src/web/api/bots.ts
@@ -1,4 +1,5 @@
import { Hono } from 'hono';
+import type { Context } from 'hono';
import { readFileSync } from 'node:fs';
import type { BotManager } from '../../bots/bot-manager.js';
import type { BotManifest } from '../../bots/types.js';
@@ -413,6 +414,54 @@ app.get('/api/bots/:id/bundle', (c: any) => {
}
});
+// Token spend per bot and fleet (ADR-022)
+app.get('/api/bots-cost', (c: Context) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const days = Math.max(1, Math.min(90, parseInt(c.req.query('days') ?? '7', 10) || 7));
+ return c.json(botManager.costReport(days));
+});
+
+// Fleet kill switch
+app.post('/api/bots-stop-all', async (c: Context) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ return c.json(await botManager.stopAll());
+});
+app.post('/api/bots-start-all', (c: Context) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ return c.json(botManager.startAll());
+});
+
+// Drop dead-lettered jobs (all, or ?bot=<id>)
+app.delete('/api/bots-dlq', (c: Context) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const bot = c.req.query('bot') || undefined;
+ if (bot && !botManager.store.exists(bot)) return c.json({ error: 'Bot not found' }, 404);
+ return c.json({ cleared: botManager.clearDlq(bot) });
+});
+
+// A lead's delegated tasks
+app.get('/api/bots/:id/tasks', (c: Context) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ if (!botManager.store.exists(c.req.param('id'))) return c.json({ error: 'Bot not found' }, 404);
+ return c.json({ tasks: botManager.tasksFor(c.req.param('id')) });
+});
+
+// Run transcripts: list, and one run (newest when runId is "latest")
+app.get('/api/bots/:id/runs', (c: Context) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ if (!botManager.store.exists(c.req.param('id'))) return c.json({ error: 'Bot not found' }, 404);
+ return c.json({ runs: botManager.listTranscripts(c.req.param('id')) });
+});
+app.get('/api/bots/:id/runs/:runId', (c: Context) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ if (!botManager.store.exists(id)) return c.json({ error: 'Bot not found' }, 404);
+ const runId = c.req.param('runId');
+ const t = botManager.readTranscript(id, runId === 'latest' ? undefined : runId);
+ if (!t) return c.json({ error: 'Transcript not found' }, 404);
+ return c.json(t);
+});
+
// This bot's deliverables
app.get('/api/bots/:id/outputs', (c: any) => {
if (!botManager) return c.json({ error: 'Bots not available' }, 400);
diff --git a/website/docs/integrations/mercury-bots.mdx b/website/docs/integrations/mercury-bots.mdx
index 3f7da5e1..38e52353 100644
--- a/website/docs/integrations/mercury-bots.mdx
+++ b/website/docs/integrations/mercury-bots.mdx
@@ -121,6 +121,7 @@ The local dashboard ('Mercury Bots' section) shows the live roster, per-bot thre
## Observability
- **`/bots` roster** — live per-bot states (running / waiting / stopped / needs-you).
+- **`/bots cost [days]`** — token spend per bot and fleet against the caps; **`/bots show <id> [runId]`** — the tool trace, deliveries and reply of a run; **`/bots stop all`** — the kill switch; **`/bots dlq clear`** — drop dead-lettered jobs.
- **Journals** — per-bot run history with real timings, steps, tool calls, the outcome (`deliverable`, `action`, `delegated`, `message`, `none`) and delivered paths; a compact transcript per run is kept (last 50).
- **DLQ + replay** — failures classify honestly (`failed`, `timed out`) and replay non-destructively.
- **`mercury bots doctor`** — storage health, queue depth, journal rotation, and scheduler linkage (routines registered but never wired are flagged before they silently never fire).