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): control the fleet from Telegram — tappable roster, files not paths, every /bots command listed (ADR-023)

Salman Qureshi9975db46c5a7
diff --git a/.lint-baseline.json b/.lint-baseline.json
index 61f86476..efdf5e2c 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-10T15:47:23.840Z",
+ "generatedAt": "2026-10-10T16:18:00.110Z",
"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": 279,
+ "@typescript-eslint/no-unused-vars": 278,
"no-console": 135,
"no-control-regex": 27,
"no-func-assign": 5,
diff --git a/BOTS-ARCHITECTURE.md b/BOTS-ARCHITECTURE.md
index 397d610c..81aa74f4 100644
--- a/BOTS-ARCHITECTURE.md
+++ b/BOTS-ARCHITECTURE.md
@@ -1,37 +1,37 @@
-undefundefinedneduuuuundefineddefundefinedneddundefinedfineddundefundefinednedfundefinedneddefundefinednedundeundefinedinedundefinedfinedundefinedMerundefinedurundefinedundefinedBundefinedundefinedundefinedundefined—undefinedundefinedeundefinedeundefinedrundefinedhundefined&undefinedundefinedrchiundefinedecundefinedure
+# Mercury Bots — Research & Architecture
->undefinedSundefinedundefinedtuundefined:undefineddesignundefinedundefinedroundefinedosaundefined undefinedundefinedreundefinedimplementationundefinedundefined Branch `Mercurundefinedundefinedbots`.
-> Research basis: Hermes Agent (Nous Research)undefined undefinedpenClawundefined Groundefined-on-X (`xai-org/grok-prompts`)undefined production messaging-bot/queue patternsundefined and a full audit of Mercury's current architecture (Sept undefinedundefinedundefinedundefined).
+> Status: design proposal (pre-implementation). Branch `Mercury-bots`.
+> Research basis: Hermes Agent (Nous Research), OpenClaw, Grok-on-X (`xai-org/grok-prompts`), production messaging-bot/queue patterns, and a full audit of Mercury's current architecture (Sept 2026).
---
-undefinedundefined undefined. What this is
+## 0. What this is
Mercury Bots adds a second kind of agent to Mercury Code, alongside the main conversational agent:
- **Bots are persistent, persona-scoped specialists.** A marketing bot, a research bot, a publishing bot — each with its own character, own model/provider, own scoped memory, own tool permissions. A bot "acts as" its specialty and nothing else.
-- **Bots are near-zero-interaction.** undefinedhey never prompt the user mid-run. Everything they need (persona, scopes, memory access, communication links, schedules) is configured once at setup; at runtime they run fully automatic and **fail closed** (a permission they don't have is a denial, not a question).
+- **Bots are near-zero-interaction.** They never prompt the user mid-run. Everything they need (persona, scopes, memory access, communication links, schedules) is configured once at setup; at runtime they run fully automatic and **fail closed** (a permission they don't have is a denial, not a question).
- **Bots never block the main agent.** The Mercury core stays available while bots run. Bots execute as decoupled async work in the same process — not one thread/process per bot — so they respect low-end hardware (Termux, Raspberry Pi, small VPS).
- **Bots are configured at creation and composable afterwards.** Two bots can be linked (research bot feeds the publishing bot), memory access is opt-in per bot, and inter-bot communication is an explicit configured capability.
- **Bots are reachable everywhere Mercury is**: the `/bots` command in the TUI, the local HTTP API (Hono), Mercury Cloud (WS relay), and messaging channels (Telegram first).
---
-## undefined. Research summary
+## 1. Research summary
-### undefined.1 How the competitors do it
+### 1.1 How the competitors do it
| Aspect | Hermes Agent (Nous) | OpenClaw | Grok on X |
|---|---|---|---|
| Unit of isolation | **Profile = whole home** (`~/.hermes/profiles/<name>/`: `SOUL.md`, `config.yaml`, `.env`, memory, sessions, cron) | **Agent entry inside one Gateway process** (own workspace, own SQLite store, per-agent tool allow/deny) | Versioned Jinja **system-prompt templates** per surface, additive over a base prompt |
-| Execution model | N gateway processes, or one multiplexing process, or undefinedesktop's **warm pool (max undefined, ~60 MB each, 10-min idle reap, 30s slot wait)**; subagents on a thread pool (max 3 default) | **In-process, pure TS + promises, no worker threads**; RPC returns `{runId, accepted}` then streams; **lane-aware FIFO queue** (per-session lanes + global lane `max(8, cpus*4)`, separate `cron`/`subagent` lanes) | Server-side queueing; replies async, decoupled from user session |
+| Execution model | N gateway processes, or one multiplexing process, or Desktop's **warm pool (max 3, ~60 MB each, 10-min idle reap, 30s slot wait)**; subagents on a thread pool (max 3 default) | **In-process, pure TS + promises, no worker threads**; RPC returns `{runId, accepted}` then streams; **lane-aware FIFO queue** (per-session lanes + global lane `max(8, cpus*4)`, separate `cron`/`subagent` lanes) | Server-side queueing; replies async, decoupled from user session |
| Memory | Per-profile by construction; shared only via external memory-provider plugins; subagents **blocked from memory**; write-approval staging | Per-agent by default; cross-agent search removed; sharing explicit (`extraPaths`, wiki vaults) | Static prompt constraints; no long-term memory on X surface |
-| Bot↔bot comms | `message_agent(target, message)` fire-and-forget with attribution + delivery receipts (`queued→settled`) + typed failure codes; group rooms (undefined–6 bots, ≤10 msgs / ≤3 rounds, `[SILENT]` tokens) | No free-form DMs; deterministic bindings + coordinator→specialist delegation (`subagents.allowAgents`) | N/A (single bot) |
+| Bot↔bot comms | `message_agent(target, message)` fire-and-forget with attribution + delivery receipts (`queued→settled`) + typed failure codes; group rooms (2–6 bots, ≤10 msgs / ≤3 rounds, `[SILENT]` tokens) | No free-form DMs; deterministic bindings + coordinator→specialist delegation (`subagents.allowAgents`) | N/A (single bot) |
| Sandboxing | 8-layer defense; approvals **fail closed** (timeout = deny); dangerous-command regexes + hardline patterns that survive `--yolo`; container backends skip checks (container is the boundary) | Per-agent `tools.allow`/`tools.deny`; sandbox modes `off/non-main/all` with `shared/agent` scope; "deny can't be re-enabled by sandboxing"; candid: "Gateway process always stays on the host" | Hard output caps, no-markdown-on-X, language matching, never tag-spam reply target |
| Scheduling | First-class cron: `jobs.json`, every run = fresh agent, execution history DB (`claimed→running→completed/failed/unknown`), `wakeAgent` gate scripts skip the LLM when nothing changed | Embedded cron runs on dedicated `cron` lanes | Grok Tasks/Automations: pausable/resumable/editable **with run history retained**; limitation: one-shot prompts, no multi-step branching |
| Never-fail | Stale-PID recovery; delegation explicitly **not durable** (restart cancels children) | Input persisted to SQLite before ack; per-run `activeWriterRunId` verified on every transcript append; in-memory queue not replayed on restart | Load-shedding (mentions silently dropped under load — the failure mode we must avoid) |
-### 1.undefined What the distributed-systems evidence says
+### 1.2 What the distributed-systems evidence says
- **No broker.** The convergent single-machine design puts the durable queue **in the DB you already have** (SQLite lease-queue with heartbeats / Postgres `SKIP LOCKED`). Enqueue is transactional with state writes; expired leases auto-requeue work from crashed workers.
- **Low-end hardware verdict:** a Node `child_process` is a full V8 instance (~30–70 MB RSS). A 4 GB Pi fits 1–5 Node processes. The winning pattern is **one process, many agents as async tasks**; `worker_threads` only when true CPU parallelism is needed. Process-per-agent loses.
@@ -245,6 +245,23 @@ Deliverables live in an owner-visible folder (`BotStore.deliverablesDir`): final
| Memory extraction after productive runs | `memory-extract.ts` | The bot's own namespace accumulates sources, decisions, locations |
| Crew provider lane | `resolveProvider` | Stage work on a cheaper provider |
+### 2.14 Liveness contract (Oct 2026)
+
+Bots are meant to be running continuously. "Running" does not mean calling a model all the time — it means **alive**: idle between runs, never parked by an optimisation, never dead without the owner being told. Everything in §2.12–2.13 that can stop a bot must therefore be a *cooldown*, not a *halt*:
+
+| Stop condition | Behaviour | Auto-resume |
+|---|---|---|
+| Three no-outcome runs in a row (routine) | Cooldown, not pause: `paused[key].until` = 6h, doubling per repeat to 24h (`pauseCount`) | Yes — the gate lets the next tick through after `until`; `/bots start` resumes now |
+| Daily / fleet token cap | Paused for the rest of the day | Yes — midnight rollover; the sweep pumps queued work then |
+| `/bots stop` / `stop all` / `disable` | Explicit owner hold | No — the owner asked |
+| Permanent failure (DLQ) | Job is dead-lettered; the bot is not | n/a — the next tick runs |
+
+Declared cadence is honoured: a `schedules[]` entry in `bot.yaml` runs at the interval written there (`minIntervalMinutes` defaults to 0); the 30-minute floor applies only to routines a bot creates for itself with `bot_schedule`. The doctor's `stale` check reports a bot whose routine has not fired in twice its cadence — the signal that something *else* stopped it. Bots run in the `BotManager` lane only: they never enter `Agent.processQueue`, never write to the main chat, never touch the owner's code session.
+
+### 2.15 Remote control (ADR-023, Oct 2026)
+
+The owner is on a phone more often than at the TUI. Channels that have buttons (Telegram) get a generic `sendWithActions(text, rows)`: each button carries a short token (`ba:<token>`, callback data is capped at 64 bytes) that maps to a slash command; a tap by an approved user is emitted as an ordinary `ChannelMessage` with that command as its content, so routing, permissions and replies are exactly what typing it would give. `/bots` uses it for the roster (Stop/Start, Run, Runs per lead or solo; Cost, Outputs, Doctor, Stop all for the fleet) and `/bots outputs` for one 📎 per file. Deliverables are pushed to the requesting remote chat as files (`BotManager.setSendFile` → `channel.sendFile`) after the text — a path on the owner's disk is useless on a phone. `/bots fetch <id> [name|latest]` sends one on demand; `/bots doctor` runs §2.12's checks from any chat.
+
### 2.11 Devices without native SQLite (old Node versions, Termux)
`better-sqlite3` is a native module: on unsupported Node versions or Termux/Android it may fail to install or load. Mercury already handles this exact problem for the second brain (optionalDependency + tmp-dir runtime probe, `src/memory/second-brain-db.ts:19-25`; `sql.js` ships as a regular dependency). Bots follow and extend the pattern:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa509089..d4cf47b7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,10 +1,22 @@
-#uununundefinedefundefinednedefineddefinedununundundefinedfinedundefundefinednedfinedundundefinedfinedfinedundundundefinedfinedfundefinednedundundefinedfinedfinedndefinedCundefinedundefinedngeundefinedundefinedg
+# Changelog
-##undefinedUnundefinedeundefinedeundefinedundefinededundefined—undefinedseeundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedeundefinedbundefinedundefinedsundefinedundefinedundefinedsundefinedundefinedandundefineddidundefined(ADRundefined022)
+## Unreleased — bots in your pocket (ADR-023)
--undefinedundefinedundefined`/bundefinedundefinedsundefinedundefinedosundefined [daundefineds]`undefinedundefined — undefinedoken sundefinedend peundefined bot and peundefined fleetundefined today against the undefinedapundefined the window's undefinedunsundefined failures, deliundefinederies and eundefinedpty runsundefined Also `GEundefined /api/bots-undefinedost`.
+- **Telegram controls.** `/bots` and `/bot` are in Telegram's command menu; the roster arrives with buttons — Stop/Start, Run and Runs per bot, plus Cost, Outputs, Doctor and Stop all for the fleet. A tap runs the slash command behind it as if you had typed it (same permissions, same reply). `/bots outputs` carries a 📎 button per delivered file.
+- **Files, not paths.** A task asked for from Telegram (or any remote chat) comes back with its delivered files attached. `/bots fetch <id> [name|latest]` sends one on demand.
+- **`/bots doctor`** runs the fleet health check from any chat; **`/bots help`** lists the commands. The TUI's slash completion, the busy-mode `/help`, and the docs now list every `/bots` subcommand.
+
+## Unreleased — bots stay online
+
+- **Idle, never dead.** A routine that keeps producing nothing is cooled down instead of parked: 6 hours, doubling to 24, then it resumes by itself (`/bots start` resumes it now). Budget pauses lift at midnight and queued work is pumped then.
+- **Declared cadence is honoured.** A schedule in `bot.yaml` runs as written; the 30-minute floor applies only to routines a bot creates for itself.
+- **Doctor `stale` check** flags a bot whose routine has not fired in twice its cadence; the roster shows when a cooled-down routine resumes.
+
+## 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 `PundefinedST /api/bots-stop-all` / `-start-all`.
+- **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.
diff --git a/DECISIONS.md b/DECISIONS.md
index 28fc5063..ea4e80bd 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -1,3 +1,15 @@
+## 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.
+
+## ADR-023: Bots from the phone — tappable controls, files not paths
+
+- **Context**: The bots surface was complete in the TUI and stale everywhere else: the TUI's slash completion listed 15 of ~35 `/bots` subcommands, the website table fewer, Telegram's command menu had no `bots` entry at all, and controlling a fleet from Telegram meant typing ids from memory. Results asked for from Telegram came back as `📁 Delivered → /Users/…` — a path on the owner's Mac, unreadable on a phone. The owner runs the fleet from the phone more than from the terminal.
+- **Decision**: One generic mechanism, no bot-specific Telegram code: `TelegramChannel.sendWithActions(text, rows)` renders buttons whose callback data is a short token (`ba:<token>`, 64-byte cap) mapped to a slash command in a bounded map; a tap by an approved user is emitted as an ordinary `ChannelMessage` whose content is that command. Nothing downstream knows about taps — `/bots stop ceo` from a button is routed, permission-checked and answered exactly as the typed one. `/bots` renders Stop/Start, Run, Runs per lead/solo and Cost, Outputs, Doctor, Stop all for the fleet when the channel has `sendWithActions`; `/bots outputs` renders one 📎 per file. `BotManager.setSendFile` pushes each deliverable to the requesting remote chat after the text; `/bots fetch` sends one on demand. `/bots doctor` (`BotManager.doctor()` over `runBotDoctor`) and `/bots help` exist as actions. The slash list, busy-mode `/help`, the Telegram command menu and the docs table list every subcommand. The liveness PR's doc edits (CHANGELOG, BOTS-ARCHITECTURE, website) had been corrupted into `undefined` strings by a bad replace; restored from the previous commit and rewritten here.
+- **Consequence**: The fleet is operable from a phone without typing ids: see, stop, start, run, inspect, fetch. The token map is per-process, so buttons on an old message after a restart answer "Expired — send /bots again" rather than running a stale command. Discord/Slack can adopt the same `sendWithActions` contract; until they do, `/bots` falls back to text there.
+
# Mercury — Decisions
> Architecture Decision Records. New ones appended as we go.
@@ -197,9 +209,3 @@
- **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.test.ts b/src/bots/bot-manager.test.ts
index a5af587b..5b38c3bb 100644
--- a/src/bots/bot-manager.test.ts
+++ b/src/bots/bot-manager.test.ts
@@ -1267,3 +1267,55 @@ describe('bot governance (ADR-020)', () => {
expect(registry.getCwd()).toBe(store.sandboxDir('anchored'));
});
});
+
+// ── ADR-023: remote surfaces get the files, and doctor lives on the manager ──
+
+describe('remote delivery and doctor (ADR-023)', () => {
+ let root: string;
+ let store: BotStore;
+ let manager: BotManager;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-remote-'));
+ store = new BotStore(join(root, 'bots'));
+ manager = makeManager(root);
+ });
+
+ afterEach(() => {
+ for (const m of activeManagers.splice(0)) m.dispose();
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('sends each delivered file to the remote chat that asked, after the text', async () => {
+ seedBot(store, 'courier');
+ mkdirSync(store.sandboxDir('courier'), { recursive: true });
+ writeFileSync(join(store.sandboxDir('courier'), 'report.md'), 'body');
+ type DeliverOpts = { tools: { bot_deliver: { execute: (input: { file: string }, ctx: unknown) => Promise<unknown> } }; onStepFinish?: (step: unknown) => void };
+ mockedGenerateText.mockImplementation((async (opts: DeliverOpts) => {
+ const r = await opts.tools.bot_deliver.execute({ file: join(store.sandboxDir('courier'), 'report.md') }, {});
+ opts.onStepFinish?.({ usage: { inputTokens: 10, outputTokens: 5 }, toolCalls: [{ toolName: 'bot_deliver', toolCallId: 'd', input: {} }], toolResults: [{ toolCallId: 'd', output: { type: 'text', value: r } }] });
+ return { text: 'Delivered.', finishReason: 'stop', usage: { inputTokens: 10, outputTokens: 5 } };
+ }) as never);
+ const events: string[] = [];
+ manager['notify'] = async (t, target) => { events.push(`text:${t}:${target}`); };
+ manager.setSendFile(async (t, target, file) => { events.push(`file:${t}:${target}:${file}`); });
+ manager.enqueue('courier', { trigger: 'chat', prompt: 'report please', source: { channelType: 'telegram', channelId: 'chat-42' } });
+ await vi.waitFor(() => {
+ expect(events.some(e => e.startsWith('file:telegram:chat-42:'))).toBe(true);
+ });
+ const text = events.indexOf('text:telegram:chat-42');
+ const file = events.findIndex(e => e.startsWith('file:telegram:chat-42:'));
+ expect(text).toBeGreaterThanOrEqual(0);
+ expect(file).toBeGreaterThan(text);
+ expect(events.find(e => e.startsWith('file:'))).toMatch(/report\.md$/);
+ // The bot thread (CLI) never gets a file push — the path is already there.
+ expect(events.some(e => e.startsWith('file:cli:'))).toBe(false);
+ });
+
+ it('doctor() runs the same fleet checks as the CLI', () => {
+ seedBot(store, 'fine');
+ const report = manager.doctor();
+ expect(report.checked).toBe(1);
+ expect(Array.isArray(report.findings)).toBe(true);
+ });
+});
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index f3724c17..3bdab17f 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -21,6 +21,7 @@ import { BotTaskStore, renderTaskPrompt, renderBatchDigest, isTerminalTask, type
import { createFleetDelegateTool, createFleetTasksTool, createFleetPipelineTool } from './tools/fleet-tasks.js';
import { createBotStateTool } from './tools/bot-state.js';
import { extractBotMemories } from './memory-extract.js';
+import { runBotDoctor, type DoctorReport } from './doctor.js';
import { createBotDeliverTool } from './tools/bot-deliver.js';
import { createBotScheduleTool, type BotScheduler } from './tools/bot-schedule.js';
import { createFleetStatusTool } from './tools/fleet-status.js';
@@ -147,6 +148,7 @@ export class BotManager {
private readonly skillsRoot?: BotManagerDeps['skillsRoot'];
private notify?: BotManagerDeps['notify'];
private alert?: (message: string) => Promise<void>;
+ private sendFile?: (channelType: string, channelId: string, filePath: string) => Promise<void>;
/** Deliver turn output to the invoking surface (wired by the Agent). */
setNotify(cb: NonNullable<BotManagerDeps['notify']>): void {
@@ -158,6 +160,21 @@ export class BotManager {
this.alert = cb;
}
+ /** Deliver a file to a remote chat (Telegram/Discord/Slack) — a path on the owner's disk is useless on a phone. */
+ setSendFile(cb: (channelType: string, channelId: string, filePath: string) => Promise<void>): void {
+ this.sendFile = cb;
+ }
+
+ /** Fleet health, same checks as `mercury bots doctor`. */
+ doctor(): DoctorReport {
+ return runBotDoctor({
+ store: this.store,
+ queue: this.queue,
+ journalFor: (id) => this.journalFor(id),
+ scheduledRoutineIds: this.scheduler?.getManifests().map(m => m.id),
+ });
+ }
+
/** Wire the main Scheduler so bots can self-schedule (bot_schedule tool). */
setScheduler(scheduler: BotSchedulerLike): void {
this.scheduler = scheduler;
@@ -968,6 +985,13 @@ export class BotManager {
if (sourceChannelId && sourceChannelId !== botThread && sourceChannelType !== 'cli') {
await this.notify(sourceChannelType, sourceChannelId, fullText).catch((e) =>
logger.warn({ e, botId }, 'Bot remote-channel result notify failed'));
+ // The files themselves, not just their paths (ADR-023).
+ if (this.sendFile) {
+ for (const file of output.deliverables) {
+ await this.sendFile(sourceChannelType, sourceChannelId, file).catch((e) =>
+ logger.warn({ e, botId, file }, 'Bot deliverable send to remote channel failed'));
+ }
+ }
}
}
diff --git a/src/channels/base.ts b/src/channels/base.ts
index 8f7a98c4..bf7986e4 100644
--- a/src/channels/base.ts
+++ b/src/channels/base.ts
@@ -2,12 +2,20 @@ import type { ChannelType, ChannelMessage } from '../types/channel.js';
export type PermissionMode = 'allow-all' | 'ask-me';
+/** A tappable button that runs a slash command as if the user had typed it (ADR-023). */
+export interface ChannelAction {
+ label: string;
+ command: string;
+}
+
export interface Channel {
readonly type: ChannelType;
start(): Promise<void>;
stop(): Promise<void>;
send(content: string, targetId?: string, elapsedMs?: number): Promise<void>;
sendFile(filePath: string, targetId?: string): Promise<void>;
+ /** Text with rows of tappable actions; channels without buttons leave this undefined and callers fall back to send(). */
+ sendWithActions?(content: string, rows: ChannelAction[][], targetId?: string): Promise<void>;
stream(content: AsyncIterable<string>, targetId?: string): Promise<string>;
typing(targetId?: string): Promise<void>;
askToContinue(question: string, targetId?: string): Promise<boolean>;
diff --git a/src/channels/telegram-actions.test.ts b/src/channels/telegram-actions.test.ts
new file mode 100644
index 00000000..2f597b3a
--- /dev/null
+++ b/src/channels/telegram-actions.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it, vi } from 'vitest';
+import { TelegramChannel } from './telegram.js';
+import type { ChannelMessage } from '../types/channel.js';
+
+/**
+ * Tappable bot controls (ADR-023): a message sent with action rows carries an
+ * inline keyboard, and a tap by an approved user turns into the slash command
+ * behind the button — emitted as an ordinary ChannelMessage so routing,
+ * permissions and replies are exactly what typing it would give.
+ */
+
+const CHAT_ID = 4242;
+const ADMIN = 7;
+const STRANGER = 99;
+
+function makeChannel() {
+ const config = { channels: { telegram: { admins: [{ userId: ADMIN, name: 'Owner' }], members: [], pending: [], pendingRequests: [] } } };
+ const channel = new TelegramChannel(config as never);
+ type Keyboard = { inline_keyboard: Array<Array<{ text: string; callback_data: string }>> };
+ const sendMessage = vi.fn<(chatId: number, text: string, opts: { reply_markup: Keyboard }) => Promise<{ message_id: number }>>(async () => ({ message_id: 1 }));
+ const bot = { api: { sendMessage } };
+ (channel as unknown as { bot: typeof bot }).bot = bot;
+ const received: ChannelMessage[] = [];
+ channel.onMessage(async (m) => { received.push(m); });
+ return { channel, bot, received };
+}
+
+/** Reach the private tap handler the way grammy would. */
+function tapHandler(channel: TelegramChannel): (ctx: unknown) => Promise<void> {
+ return (channel as unknown as { handleCallbackQuery(ctx: unknown): Promise<void> }).handleCallbackQuery.bind(channel);
+}
+
+function tap(data: string, userId: number) {
+ return {
+ callbackQuery: { data, message: { chat: { id: CHAT_ID } } },
+ from: { id: userId, first_name: 'T' },
+ answerCallbackQuery: vi.fn(async () => true),
+ };
+}
+
+describe('Telegram tappable actions', () => {
+ it('sends an inline keyboard whose rows mirror the given actions', async () => {
+ const { channel, bot } = makeChannel();
+ await channel.sendWithActions('roster', [
+ [{ label: '⏹ Stop ceo', command: '/bots stop ceo' }, { label: '🏃 Run', command: '/bots run ceo' }],
+ [{ label: '💰 Cost', command: '/bots cost' }],
+ ], `telegram:${CHAT_ID}`);
+ const keyboard = bot.api.sendMessage.mock.calls[0]![2]!.reply_markup.inline_keyboard;
+ expect(keyboard).toHaveLength(2);
+ expect(keyboard[0]).toHaveLength(2);
+ expect(keyboard[0][0].text).toBe('⏹ Stop ceo');
+ expect(keyboard[0][0].callback_data).toMatch(/^ba:[a-z0-9]+$/);
+ expect(keyboard[0][0].callback_data.length).toBeLessThanOrEqual(64);
+ });
+
+ it('a tap by an approved user emits the command as a message from that user', async () => {
+ const { channel, bot, received } = makeChannel();
+ await channel.sendWithActions('roster', [[{ label: 'Stop all', command: '/bots stop all' }]], `telegram:${CHAT_ID}`);
+ const data = bot.api.sendMessage.mock.calls[0]![2]!.reply_markup.inline_keyboard[0][0].callback_data;
+ const ctx = tap(data, ADMIN);
+ await tapHandler(channel)(ctx);
+ expect(received).toHaveLength(1);
+ expect(received[0]).toMatchObject({
+ channelId: `telegram:${CHAT_ID}`,
+ channelType: 'telegram',
+ senderId: String(ADMIN),
+ senderRole: 'admin',
+ content: '/bots stop all',
+ });
+ expect(ctx.answerCallbackQuery).toHaveBeenCalled();
+ });
+
+ it('a tap by an unapproved user is refused and emits nothing', async () => {
+ const { channel, bot, received } = makeChannel();
+ await channel.sendWithActions('roster', [[{ label: 'Stop all', command: '/bots stop all' }]], `telegram:${CHAT_ID}`);
+ const data = bot.api.sendMessage.mock.calls[0]![2]!.reply_markup.inline_keyboard[0][0].callback_data;
+ const ctx = tap(data, STRANGER);
+ await tapHandler(channel)(ctx);
+ expect(received).toHaveLength(0);
+ expect(ctx.answerCallbackQuery).toHaveBeenCalledWith(expect.objectContaining({ text: 'Not allowed' }));
+ });
+
+ it('an unknown or expired token answers without emitting', async () => {
+ const { channel, received } = makeChannel();
+ const ctx = tap('ba:nope', ADMIN);
+ await tapHandler(channel)(ctx);
+ expect(received).toHaveLength(0);
+ expect(ctx.answerCallbackQuery).toHaveBeenCalledWith(expect.objectContaining({ text: expect.stringContaining('Expired') }));
+ });
+});
diff --git a/src/channels/telegram.ts b/src/channels/telegram.ts
index fde122db..b1e46c30 100644
--- a/src/channels/telegram.ts
+++ b/src/channels/telegram.ts
@@ -3,7 +3,7 @@ import path from 'node:path';
import { Bot, InputFile, InlineKeyboard } from 'grammy';
import { autoRetry } from '@grammyjs/auto-retry';
import type { ChannelMessage } from '../types/channel.js';
-import { BaseChannel, type PermissionMode } from './base.js';
+import { BaseChannel, type PermissionMode, type ChannelAction } from './base.js';
import type { MercuryConfig, TelegramAccessUser, TelegramPendingRequest } from '../utils/config.js';
import {
addTelegramPendingRequest,
@@ -33,6 +33,13 @@ const MEMORY_ACTION_PREFIX = 'tg_memory';
type ApprovalResolver = () => void;
type ChoiceResolver = (value: string) => void;
+interface ActionTapContext {
+ callbackQuery: { data: string; message?: { chat?: { id?: number } } };
+ chat?: { id?: number };
+ from?: { id?: number; first_name?: string };
+ answerCallbackQuery: (args: { text: string }) => Promise<unknown>;
+}
+
export class TelegramChannel extends BaseChannel {
readonly type = 'telegram' as const;
private bot: Bot | null = null;
@@ -292,6 +299,8 @@ export class TelegramChannel extends BaseChannel {
{ command: 'models', description: 'List providers or switch AI model' },
{ command: 'code', description: 'Programming mode (plan / execute / off)' },
{ command: 'agents', description: 'List and manage sub-agents' },
+ { command: 'bots', description: 'Your bots: roster with controls, cost, outputs, stop/start' },
+ { command: 'bot', description: 'Message a bot: /bot <id> <task>' },
{ command: 'bg', description: 'Background tasks (list / cancel / run)' },
{ command: 'spotify', description: 'Spotify playback controls' },
{ command: 'skills', description: 'Browse and install skills from the registry' },
@@ -605,9 +614,51 @@ export class TelegramChannel extends BaseChannel {
}
}
+ /**
+ * Tappable actions (bots control, ADR-023): a message with inline buttons
+ * whose taps run slash commands exactly as if the user had typed them —
+ * same routing, same permissions, same replies. Commands are kept behind
+ * short tokens (callback data is capped at 64 bytes) in a bounded map.
+ */
+ private readonly actionTokens = new Map<string, string>();
+ private static readonly ACTION_TOKENS_MAX = 300;
+
+ async sendWithActions(content: string, rows: ChannelAction[][], targetId?: string): Promise<void> {
+ const chatIds = this.resolveTargetChatIds(targetId);
+ const chatId = chatIds[0];
+ if (!chatId || !this.bot) {
+ await this.send(content, targetId);
+ return;
+ }
+ const keyboard = new InlineKeyboard();
+ rows.forEach((row, i) => {
+ for (const button of row) {
+ const token = Math.random().toString(36).slice(2, 10);
+ this.actionTokens.set(token, button.command);
+ keyboard.text(button.label.slice(0, 40), `ba:${token}`);
+ }
+ if (i < rows.length - 1) keyboard.row();
+ });
+ while (this.actionTokens.size > TelegramChannel.ACTION_TOKENS_MAX) {
+ const oldest = this.actionTokens.keys().next().value;
+ if (oldest === undefined) break;
+ this.actionTokens.delete(oldest);
+ }
+ const html = mdToTelegram(content);
+ try {
+ await this.bot.api.sendMessage(chatId, html, { parse_mode: 'HTML', reply_markup: keyboard });
+ } catch {
+ await this.bot.api.sendMessage(chatId, this.stripHtml(html), { reply_markup: keyboard }).catch((e: unknown) => logger.warn({ e }, 'telegram actions send failed'));
+ }
+ }
+
/** Inline-keyboard taps (approvals, choices, access/memory admin actions). */
private async handleCallbackQuery(ctx: any): Promise<void> {
const data: string = ctx.callbackQuery.data;
+ if (data.startsWith('ba:')) {
+ await this.handleActionTap(ctx, data.slice(3));
+ return;
+ }
if (data.startsWith(`${ACCESS_ACTION_PREFIX}:`)) {
await this.handleAccessCallback(ctx, data);
return;
@@ -646,6 +697,34 @@ export class TelegramChannel extends BaseChannel {
await ctx.answerCallbackQuery({ text: action === 'no' ? 'Denied' : 'Approved' });
}
+ /** A tapped action runs its slash command as a message from the tapping user. */
+ // (the grammy context fields the handler reads; the rest is irrelevant here)
+ private async handleActionTap(ctx: ActionTapContext, token: string): Promise<void> {
+ const command = this.actionTokens.get(token);
+ const userId: number | undefined = ctx.from?.id;
+ const chatId: number | undefined = ctx.callbackQuery?.message?.chat?.id ?? ctx.chat?.id;
+ if (!command || !chatId) {
+ await ctx.answerCallbackQuery({ text: 'Expired — send /bots again' }).catch(() => {});
+ return;
+ }
+ if (!userId || !findTelegramApprovedUser(this.config, userId)) {
+ await ctx.answerCallbackQuery({ text: 'Not allowed' }).catch(() => {});
+ return;
+ }
+ await ctx.answerCallbackQuery({ text: command.slice(0, 60) }).catch(() => {});
+ this.emit({
+ id: `tap-${Date.now().toString(36)}-${token}`,
+ channelId: `telegram:${chatId}`,
+ channelType: 'telegram',
+ senderId: String(userId),
+ senderName: ctx.from?.first_name,
+ senderRole: this.isAdminUser(userId) ? 'admin' : 'member',
+ content: command,
+ timestamp: Date.now(),
+ metadata: { chatId, tapped: true },
+ });
+ }
+
/**
* Send a prompt card with an inline keyboard. Returns the message id (or
* undefined when sending failed) and remembers the card so the outcome can be
diff --git a/src/core/agent.ts b/src/core/agent.ts
index b61b9a11..46485d9f 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -624,11 +624,15 @@ export class Agent {
setBotManager(botManager: import('../bots/bot-manager.js').BotManager): void {
this.botManager = botManager;
botManager.setNotify(async (channelType, channelId, message) => {
- const channel = this.channels.get(channelType as any);
+ const channel = this.channels.get(channelType as ChannelType);
if (channel) {
await channel.send(message, channelId).catch((e) => logger.warn({ e }, 'bot notify channel send failed'));
}
});
+ botManager.setSendFile(async (channelType, channelId, filePath) => {
+ const channel = this.channels.get(channelType as any);
+ if (channel) await channel.sendFile(filePath, channelId);
+ });
botManager.setAlert(async (message) => {
const channel = this.channels.getNotificationChannel();
// The CLI is NOT a needs-you surface: an alert printed there lands in
diff --git a/src/core/commands/bots-command.ts b/src/core/commands/bots-command.ts
index 7e493d66..a556e1a9 100644
--- a/src/core/commands/bots-command.ts
+++ b/src/core/commands/bots-command.ts
@@ -4,6 +4,7 @@
*/
import type { Agent } from '../agent.js';
import type { ChannelMessage } from '../../types/channel.js';
+import type { Channel } from '../../channels/base.js';
import { formatRelative, formatBytes } from './format.js';
import path from 'node:path';
import { homedir } from 'node:os';
@@ -95,10 +96,72 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan
}
const running = summaries.filter(s => s.state === 'running').length;
lines.push('', `Running: ${running} | Queued: ${summaries.reduce((a, s) => a + (s.state === 'queued' ? 1 : 0), 0)}`);
+ // Tappable controls where the surface has them (Telegram): one row per
+ // lead/solo (crew follow their lead), plus a fleet row. Taps run the
+ // same /bots commands.
+ if (typeof channel.sendWithActions === 'function') {
+ const roots = summaries.filter(s => !s.parent).slice(0, 8);
+ const rows = roots.map(s => {
+ const off = s.state === 'disabled' || s.state === 'paused';
+ return [
+ { label: `${off ? '▶ Start' : '⏹ Stop'} ${s.name}`.slice(0, 40), command: `/bots ${off ? 'start' : 'stop'} ${s.id}` },
+ { label: '🏃 Run', command: `/bots run ${s.id}` },
+ { label: '📋 Runs', command: `/bots journal ${s.id}` },
+ ];
+ });
+ rows.push([
+ { label: '💰 Cost', command: '/bots cost' },
+ { label: '📁 Outputs', command: '/bots outputs' },
+ { label: '🩺 Doctor', command: '/bots doctor' },
+ { label: '🛑 Stop all', command: '/bots stop all' },
+ ]);
+ await channel.sendWithActions(lines.join('\n'), rows, channelId);
+ return;
+ }
await channel.send(lines.join('\n'), channelId);
return;
}
+ if (action === 'help') {
+ await sendBotsHelp(channel, channelId);
+ return;
+ }
+
+ if (action === 'doctor') {
+ const report = bm.doctor();
+ const errors = report.findings.filter(f => f.severity === 'error').length;
+ const lines = [report.findings.length === 0
+ ? `✅ Fleet healthy — ${report.checked} bot(s) checked, nothing actionable.`
+ : `🩺 **Fleet doctor** — ${errors} actionable, ${report.findings.length - errors} warning(s), ${report.checked} bot(s) checked`, ''];
+ for (const f of report.findings.slice(0, 25)) lines.push(`${f.severity === 'error' ? '❌' : '⚠️'} **${f.botId}** ${f.check}: ${f.detail}`);
+ if (report.findings.length > 25) lines.push(`…and ${report.findings.length - 25} more`);
+ await channel.send(lines.join('\n'), channelId);
+ return;
+ }
+
+ if (action === 'fetch' || action === 'get') {
+ // /bots fetch <id> [name|latest] — send a deliverable to THIS chat (a phone
+ // cannot open a path on the owner's machine).
+ const target = parts[1]?.toLowerCase();
+ if (!target || !bm.store.exists(target)) {
+ await channel.send('Usage: `/bots fetch <id> [name|latest]` — sends a delivered file to this chat.', channelId);
+ return;
+ }
+ const items = bm.listDeliverables(target);
+ const wanted = parts.slice(2).join(' ').trim();
+ const item = !wanted || wanted === 'latest' ? items[0] : items.find(d => d.name === wanted || d.name.endsWith(wanted) || path.basename(d.path) === wanted);
+ if (!item) {
+ await channel.send(items.length === 0 ? `**${target}** has delivered nothing yet.` : `No deliverable "${wanted}" — \`/bots outputs ${target}\` lists them.`, channelId);
+ return;
+ }
+ if (typeof channel.sendFile !== 'function' || channel.type === 'cli') {
+ await channel.send(`📁 ${tildify(item.path)}`, channelId);
+ return;
+ }
+ await channel.sendFile(item.path, channelId);
+ return;
+ }
+
if (action === 'open') {
const target = parts[1]?.toLowerCase();
const manifest = target ? bm.store.get(target) : null;
@@ -657,7 +720,12 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan
for (const d of items) {
lines.push(`${d.final ? '📄' : '📝'} ${formatRelative(d.mtimeMs)} · **${d.botId}** · ${d.name} (${formatBytes(d.bytes)})`);
}
- lines.push('', '📄 final · 📝 work in progress (under work/) · `/bots folder <id>` opens the folder');
+ lines.push('', '📄 final · 📝 work in progress (under work/) · `/bots folder <id>` opens the folder · `/bots fetch <id> [name]` sends a file here');
+ if (typeof channel.sendWithActions === 'function' && channel.type !== 'cli') {
+ const rows = items.slice(0, 6).map(d => [{ label: `📎 ${path.basename(d.path).slice(0, 36)}`, command: `/bots fetch ${d.botId} ${d.name}` }]);
+ await channel.sendWithActions(lines.join('\n'), rows, channelId);
+ return;
+ }
await channel.send(lines.join('\n'), channelId);
return;
}
@@ -775,6 +843,10 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan
return;
}
+ await sendBotsHelp(channel, channelId);
+}
+
+async function sendBotsHelp(channel: Pick<Channel, 'send'>, channelId: string): Promise<void> {
await channel.send(
'**Bots commands**\n' +
'`/bots` — roster with live states\n' +
@@ -793,6 +865,9 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan
'`/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 doctor` — fleet health check\n' +
+ '`/bots fetch <id> [name|latest]` — send a delivered file to this chat\n' +
+ '`/bots help` — this list\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/core/commands/fast-path-command.ts b/src/core/commands/fast-path-command.ts
index 452bb55c..59b1e5de 100644
--- a/src/core/commands/fast-path-command.ts
+++ b/src/core/commands/fast-path-command.ts
@@ -77,7 +77,7 @@ export async function handleFastPathCommand(agent: Agent, msg: ChannelMessage):
}
if (trimmed === '/help') {
- await channel.send('Agent is busy. Available: /sessions, /session, /agents, /halt, /stop, /progress, /spotify, /code, /research, /memory, /bg', msg.channelId);
+ await channel.send('Agent is busy. Available: /sessions, /session, /agents, /halt, /stop, /progress, /spotify, /code, /research, /memory, /bg, /bots (always available — the bot lane is separate), /bot <id> <task>', msg.channelId);
return;
}
diff --git a/src/ui/input-composer.tsx b/src/ui/input-composer.tsx
index 7d104aa4..af0a9cef 100644
--- a/src/ui/input-composer.tsx
+++ b/src/ui/input-composer.tsx
@@ -51,6 +51,29 @@ export const SLASH_COMMANDS: readonly string[] = [
'/bots enable ',
'/bots disable ',
'/bots stop ',
+ '/bots stop all',
+ '/bots start ',
+ '/bots start all',
+ '/bots run ',
+ '/bots cost',
+ '/bots show ',
+ '/bots outputs',
+ '/bots folder ',
+ '/bots fetch ',
+ '/bots tasks ',
+ '/bots dlq',
+ '/bots dlq clear',
+ '/bots replay ',
+ '/bots crew ',
+ '/bots promote ',
+ '/bots demote ',
+ '/bots permissions ',
+ '/bots add-crew ',
+ '/bots remove-crew ',
+ '/bots export ',
+ '/bots import ',
+ '/bots doctor',
+ '/bots help',
'/status',
'/progress',
'/menu',
diff --git a/website/docs/integrations/mercury-bots.mdx b/website/docs/integrations/mercury-bots.mdx
index c54a6283..175137c3 100644
--- a/website/docs/integrations/mercury-bots.mdx
+++ b/website/docs/integrations/mercury-bots.mdx
@@ -1,19 +1,19 @@
---
-undundefinedfinedndundundefinedfundefinednedfinedundefineddefinedd:uundefineddefinedndundefinedfinedundefinedundundefinedfinedundefinedcuundefinedundefined-undefinedundefinedundefinedundefined
-undefinediundefinedle:undefinedMeundefinedcuundefinedyundefinedBundefinedundefinedundefinedundefined—undefinedTundefinedeundefinedFleeundefined
-deundefinedcundefinediundefinedundefinedion:undefined"Perundefinediundefinedtent,undefinedundefinederundefinedonundefined-scopedundefinedundefinedgentsundefinedthundefinedt run outside your conversation — each undefinedith its own persona, sandbox, skills, perundefinedission scopes, and durable queueundefined Build fleets with lead bots and crews."
+id: mercury-bots
+title: Mercury Bots — The Fleet
+description: "Persistent, persona-scoped agents that run outside your conversation — each with its own persona, sandbox, skills, permission scopes, and durable queue. Build fleets with lead bots and crews."
keywords: [bots, fleet, persona, mercury bots, fleet lead, crew, dispatch, dlq, bundles]
---
# Mercury Bots — The Fleet
-Mercury Bots are **persistent, persona-scoped agents** that run *outside your conversation*. Unlike sub-agents undefinedwhich die with their taskundefined or channels (which answer as one persona), bots are long-lived specialists: each has a name, a character, its own private workspace, its own skill library and permission scopes, a per-bot token budget, and a durable job queue. Dispatch work and keep talking — the bot works in the background and delivers results in **its own thread**.
+Mercury Bots are **persistent, persona-scoped agents** that run *outside your conversation*. Unlike sub-agents (which die with their task) or channels (which answer as one persona), bots are long-lived specialists: each has a name, a character, its own private workspace, its own skill library and permission scopes, a per-bot token budget, and a durable job queue. Dispatch work and keep talking — the bot works in the background and delivers results in **its own thread**.
## Concepts
| Concept | What it is |
|---|---|
-| **Bot** | A persistent persona agent: undefinedbot.yamlundefined manifest + `permissions.yaml`, sandbox at `~undefined.mercury/bots/<id>/`, journal-backed history |
+| **Bot** | A persistent persona agent: `bot.yaml` manifest + `permissions.yaml`, sandbox at `~/.mercury/bots/<id>/`, journal-backed history |
| **Wake** | Turning a bot on for a turn (`/bots run <id> [routine]` or a dispatched task) |
| **Thread** | The bot's own chat — results, thinking streams, and journal history land here, never in your active chat |
| **Fleet lead** | A bot promoted to organize its own crew (`/bots promote <id>`) — tell it *what*, it decides *how* and who |
@@ -53,22 +53,25 @@ Run these inside a conversation with Mercury (CLI, Telegram, Discord, Slack, or
| Command | Description |
|---------|-------------|
-| `/bots` | Roster with live states |
-| `/bots create <id> "Name" "Description"` | Onboard a bot (walks persona, workspace, budget, permission tiers) |
-| `/bots open <id>` | Open the bot's own thread |
-| `/bot <id> <message>` or `@<id> <message>` | Dispatch a task; the result lands only in the bot's thread |
-| `/bots persona <id> <text>` | Replace the bot's character |
-| `/bots edit <id>` | Change name, description, model, budget |
-| `/bots delete <id>` | Remove the bot and its sandbox |
-| `/bots promote <id>` / `/bots demote <id>` | Make lead / return to solo |
-| `/bots stop <id>` / `/bots start <id>` | Stop holds jobs (resumable); start resumes the whole subtree for leads |
-| `/bots enable <id>` / `/bots disable <id>` | Suspend/reactivate (imported bots start disabled) |
+| `/bots` | Roster with live states — on Telegram with tappable Stop/Start/Run/Runs buttons per bot and a fleet row (Cost, Outputs, Doctor, Stop all) |
+| `/bots create <id> "Name" "Description"` | Onboard a bot (persona, permission tier, fleet, budget size, and where results land) |
+| `/bots open <id>` | Open the bot's own thread (TUI) |
+| `/bot <id> <message>` or `@<id> <message>` | Dispatch a task; the result (and any delivered files) come back to the chat that asked |
+| `/bots cost [days]` | Token spend per bot and fleet, today against the caps |
+| `/bots outputs [id]` · `/bots folder <id>` · `/bots fetch <id> [name]` | What was delivered; open the folder; send a file to this chat |
+| `/bots show <id> [runId]` · `/bots journal <id>` | What a run did (tools, deliveries, reply) · recent runs |
+| `/bots tasks <leadId>` | A lead's delegated tasks and their results |
+| `/bots budget <id> <tokens\|suggest\|none>` | Daily token cap (default 5M; none = unlimited) |
+| `/bots persona <id> <text>` · `/bots edit <id> <field> <value>` | Character · any config field |
+| `/bots permissions <id> [readonly\|builder\|operator\|full]` | Capability tier |
+| `/bots promote <id>` / `demote` · `/bots crew <leadId>` · `/bots add-crew` / `remove-crew` | Fleet structure |
+| `/bots stop <id>` / `start <id>` · `/bots stop all` / `start all` | Hold and resume one bot (and its crew) · the whole fleet |
+| `/bots enable <id>` / `disable <id>` | Suspend/reactivate (imported bots start disabled) |
| `/bots run <id> [routine]` | Fire a routine now, or a bare wake |
-| `/bots journal <id>` | Recent runs |
-| `/bots dlq` | Failed jobs (replayable) |
-| `/bots replay <id> <jobId>` | Re-run a DLQ job non-destructively |
-| `/bots export <id> [path]` | Bundle export (a lead's carries its crew) |
-| `/bots import <path>` | Recreate from a bundle (starts disabled) |
+| `/bots dlq [clear [id]]` · `/bots replay <id> <jobId>` | Failed jobs; drop them; re-run one |
+| `/bots doctor` · `/bots storage` | Fleet health · disk usage |
+| `/bots export <id> [path]` · `/bots import <path>` | Bundles (a lead's carries its crew; imports start disabled) |
+| `/bots help` | This list, inside any chat |
CLI mirrors the read-only surface — `mercury bots doctor` (fleet health check, exit 1 when actionable), `mercury bots list`, `mercury bots storage`.
@@ -90,7 +93,8 @@ Every unattended run is governed:
- **A turn is capped** at 300k tokens and 20 minutes (`autonomy.maxTokensPerTurn`, `maxTurnMinutes` in `bot.yaml`); long context is compacted automatically.
- **Every bot has a daily token cap** — 5M unless you set one with `/bots budget <id> <tokens|suggest|none>` — and the fleet has one (`bots.fleetDailyTokenBudget`). You are warned at 80%; at 100% the bot pauses until tomorrow.
-- **A routine tick is skipped, never queued,** while the bot is still busy or within 30 minutes of its last run (`schedules[].minIntervalMinutes`). Bot-created routines run at most every 30 minutes, at most three per bot.
+- **A routine tick is skipped, never queued,** while the bot is still busy or within its routine's minimum interval (`schedules[].minIntervalMinutes`). A cadence you declare in `bot.yaml` is honoured as written; routines a bot creates for itself run at most every 30 minutes, at most three per bot.
+- **Bots stay online.** A bot is idle between runs, never dead: a routine that keeps producing nothing is cooled down (6 hours, doubling to a day) and resumes by itself; budget pauses lift at midnight and queued work is pumped then; `/bots doctor` flags a bot whose routine has not fired in twice its cadence (`stale`). Bots run in their own lane — they never touch your main chat or code session.
- **Leads delegate typed tasks** with `fleet_delegate` — several at once, each with a goal and what "done" means — and are woken **once** with a digest when the batch finishes or its deadline passes. A lead's standard job can be declared as a **pipeline** in `bot.yaml` (`pipeline.stages`), and `fleet_pipeline` runs it end to end with no lead turn between stages:
```yaml
@@ -103,7 +107,11 @@ Every unattended run is governed:
- { name: package, bot: delivery-packager, goal: "Finalise {{previous}} for delivery", final: true }
```
- **Bots remember.** After a productive run, durable facts (sources, decisions, where things are) go into the bot's own memory, and every turn starts with a digest of its last five runs plus its own working-state note (`bot_state`). `bots.fleets.crewProvider` puts crew work on a cheaper provider.
-- **A run is judged by what it did,** not by what it says: delivered a file, took an action, delegated, or nothing. A routine that only writes notes gets one nudge to deliver; three empty runs in a row pause it (`/bots start` resumes). Monitoring routines can declare `expects: check` to be allowed to find nothing.
+- **A run is judged by what it did,** not by what it says: delivered a file, took an action, delegated, or nothing. A routine that only writes notes gets one nudge to deliver; three empty runs in a row cool it down (6h, doubling to 24h; it resumes by itself, or `/bots start` resumes it now). Monitoring routines can declare `expects: check` to be allowed to find nothing.
+
+## From Telegram
+
+Everything above works from your phone: `/bots` and `/bot` are in Telegram's command menu, and the roster comes with buttons — **Stop / Start**, **Run** and **Runs** per bot, and a fleet row with **Cost**, **Outputs**, **Doctor** and **Stop all**. A tap runs the same slash command you would have typed (same permissions, same reply). When a bot finishes a task you asked for from Telegram, the reply comes back to that chat **with the delivered files attached**, not a path on your Mac; `/bots outputs <id>` lists what a bot has delivered with a 📎 button per file, and `/bots fetch <id> [name|latest]` sends one.
## Bundles
@@ -124,7 +132,7 @@ The local dashboard ('Mercury Bots' section) shows the live roster, per-bot thre
- **`/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).
+- **`/bots doctor`** (in any chat) and **`mercury bots doctor`** — storage health, stale routines, whole-home write grants, outcome ratio, queue depth, journal rotation, and scheduler linkage (routines registered but never wired are flagged before they silently never fire).
## Security notes