Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): P0 — persistent persona-scoped bot runtime
Salman Qureshi69417f08d0bf
diff --git a/BOTS-ARCHITECTURE.md b/BOTS-ARCHITECTURE.mdnew file mode 100644index 00000000..18d04560--- /dev/null+++ b/BOTS-ARCHITECTURE.md@@ -0,0 +1,334 @@+# Mercury Bots — Research & Architecture++> 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).++---++## 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.** 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).++---++## 1. Research summary++### 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 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 (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.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.+- **Supervisor ≠ retries.** Retries are policy for *calls* (backoff + caps); supervision is policy for *processes* (unconditional restart, throttled, with exit-code semantics so intentional exits don't crash-loop — an OpenClaw production incident ran 2,972 restarts without this).+- **Failure-type-aware retries:** transient (429/timeout → exponential backoff + jitter) vs permanent (invalid input, permission denial, suspected prompt injection → straight to a replayable DLQ, never re-queued).+- **Idempotency keys** on every event and every side-effecting tool call, checked *before* the LLM call.+- **Every run is an inspectable record** (Grok's automations model): no fire-and-forget anywhere.+- Empirical ceiling on single-loop agents: hundreds of "I/O-bound" LLM agents still degrade one event loop (per-response CPU work accumulates) → the fix is *bounded concurrency*, not more processes. For Mercury's realistic scale (≤ dozens of bots), in-process + concurrency caps is correct.++### 1.3 What Mercury already has (audited Sept 2026)++- **Runtime**: single Node process; main loop is a **strictly serial queue** (`Agent.processQueue`, one `handleMessage` at a time, `src/core/agent.ts:1339`). Sub-agents (`SubAgent`, `src/core/sub-agent.ts`) already run as in-process coroutines — but share the main `CapabilityRegistry`/`PermissionManager` and hardcode `providers.getDefault()`.+- **Config**: `~/.mercury/mercury.yaml` + per-concern YAML files (`permissions.yaml`, `schedules.yaml`); soul files as markdown (`src/soul/`); `subagents:` config block is the schema precedent for a `bots:` block.+- **Memory**: `UserMemoryStore` (SQLite second-brain, FTS5) already parameterizes `userKey` and `dbPath` (`src/memory/user-memory.ts:95`) → per-bot scoped memory is nearly free.+- **Permissions**: `PermissionManager` with path-scoped manifests, `tempScopes`, per-context approval maps (`src/capabilities/permissions.ts`); web/cloud-originated requests already never inherit local allow-all — the exact isolation rule bots need.+- **Scheduling**: `node-cron` Scheduler with persisted manifests (`~/.mercury/schedules.yaml`); autonomous execution exists as **internal messages** (`processInternalPrompt`, auto-approved, silent).+- **Channels & surfaces**: grammY Telegram channel; Hono HTTP server (`src/web/server.ts`) with API modules; Mercury Cloud WS client with `agent.command` envelope **and an existing `agent.message.relay`** (agent-to-agent relay through the cloud).+- **Durability today**: WorkLedger (per-message work keys + retries), crash-flag + continuation on restart, background-task manager (child-process shells + agent tasks), stall-watchdog + memory governor.+- **Commands**: three hardcoded if/else command layers (CLI commander, agent slash commands incl. fast-path, pure-TUI). No `/bots` anywhere yet.++---++## 2. Architecture++### 2.1 The bot primitive: `~/.mercury/bots/<botId>/`++A bot is a **profile directory + a runtime**, mirroring Hermes' "bot = profile" primitive but executed OpenClaw-style (in-process lanes). On disk:++```+~/.mercury/bots/<botId>/+├── bot.yaml # machine config: model, provider, tools, memory, comms, schedules, ingress+├── persona.md # character + standing instructions (the "SOUL.md")+├── permissions.yaml # per-bot scope manifest (path scopes, allow/deny tool lists)+└── .env # bot-owned credentials (chmod 600) — never inherited by other bots+```++`bot.yaml` (schema mirrors the `subagents:` config precedent):++```yaml+id: researcher+name: "Research"+description: "Deep research specialist"+persona: persona.md # file, like soul files+enabled: true+model:+ provider: anthropic # optional; unset = inherit main default+ model: claude-sonnet-5+tools:+ allow: [web_search, fetch, read_file, memory_read, bot_send]+ deny: [shell, write_file, git_commit, delete_file] # deny always wins+memory:+ scope: own # own | shared-read | none+ sharedPaths: [] # opt-in reads into other bots' memory dirs+ allowCrossBotRecall: [publisher] # which bots' context this bot may search+comms:+ canMessage: [publisher] # roster; also injected into system prompt+ groups: [growth] # optional multi-bot rooms+schedules: # optional recurring routines+ - cron: "0 9 * * *"+ prompt: "Scan RSS sources and post findings to @publisher"+ deliver: bot-chat+autonomy:+ maxConcurrent: 1+ maxSteps: 25+ dailyTokenBudget: 200000 # hard cap; exceeded → pause, not die+```++**Persona is a markdown file, not config** (Grok's prompts are literally versioned templates; Hermes/OpenClaw both use markdown persona files; Mercury already does this for soul). `persona.md` holds character, voice, standing instructions, output conventions for each surface the bot serves.++### 2.2 Execution model — the decision++**Chosen: in-process async coroutines with a bot lane queue. No per-bot processes, no per-bot threads.**++Rationale (from §1.2): on Termux/Pi, per-bot V8 processes are unaffordable; Mercury's scale is dozens of bots, not thousands; and the main-agent non-blocking requirement is satisfied by *not routing bots through `Agent.processQueue`* — a separate `BotManager` runs each bot as its own coroutine loop with bounded concurrency, exactly like `SubAgent` does today but with full isolation of state (fixing sub-agents' two known blockers):++1. **Per-bot model**: resolve `provider/model` from the registry per bot (`getModelInstance()` already supports this; only `sub-agent.ts:160`'s `getDefault()` hardcode was the blocker).+2. **Per-bot registries**: each bot gets its **own** `CapabilityRegistry` + `PermissionManager` instances constructed from its manifest — no shared mutable cwd/channel-context swapping like `SubAgent` does (`sub-agent.ts:155–163`).++Concurrency budget: global bot lane capped at `max(2, cpus − 1)` concurrent bot turns (reuses `resource-manager.ts` semantics; per-bot `maxConcurrent` further limits). A queued bot turn waits; it does **not** block the main loop, and the main loop's LLM calls are never starved (bot lane shares only the event loop, and both sides are I/O-bound in practice).++**Escape hatch for later**: the `BotRuntime` interface is deliberately process-agnostic. A bot whose `autonomy.isolation: process` (P2) would run in a `worker_thread` for crash containment — the queue/manifest design doesn't change. This mirrors Hermes' warm-pool option without paying for it now.++### 2.3 Runtime shape++```+ChannelRegistry ── ingress (TUI /bots, HTTP API, Telegram, Cloud relay)+ │+ ▼+ BotIngress ── validates + dedupes (idempotency key) + enqueues ──► BotQueue (SQLite, lease-based)+ │+ ▼+ BotManager (own coroutine loop per enabled bot; global concurrency lane)+ │+ ▼+ BotTurn = one run of one bot:+ fresh context per turn + persona.md + scoped memory injection + tool map+ (AI SDK streamText/generateText, same provider layer as main agent)+ │+ ├── BotBus ──► in-process mailbox delivery to other bots (+ Cloud relay off-host)+ ├── Scheduler ──► cron-triggered internal bot turns (separate cron lane)+ └── BotJournal ──► every run recorded (input, steps, outcome, cost) — inspectable+```++Components:++- **`BotManager`** (mirrors `SubAgentSupervisor`, `src/core/supervisor.ts`): owns lifecycle, restarts, concurrency lane, health. Registered with `BackgroundTaskManager` as `type: 'agent'` tasks so `/bg list`, the TUI status bar, and `/bots` all show live bots.+- **`BotQueue`**: durable job store at `~/.mercury/bots/queue.*` with a **pluggable backend chosen by capability probe at startup** (see §2.11): better-sqlite3 (native) → sql.js (WASM) → JSON-file lease store. Logical schema is backend-agnostic: `jobs (id, bot_id, source, payload, idempotency_key UNIQUE, state pending|claimed|running|done|dead, lease_expires_at, attempts, created_at)` + DLQ view. Claim = pending-scan with a 60s heartbeat lease; expired leases auto-requeue; `attempts >= cap` (transient) → `dead` (inspectable/replayable). Enqueue happens in the same atomic commit as any state write that motivated it.+- **`BotBus`**: in-process mailboxes. `bot_send(target, message)` delivers fire-and-forget with attribution prefix + delivery receipt (`queued → delivered → settled`) and typed failure codes (`target_disabled`, `queue_full`, `busy_timeout`) — Hermes' `message_agent` semantics. Cross-instance delivery rides the **existing Cloud `agent.message.relay`** (`src/index.ts:3113`), so bot↔bot works Mercury-Cloud-to-Mercury-Cloud too.+- **`BotJournal`**: append-only run records at `~/.mercury/bots/<id>/journal.jsonl` — every turn's input source, transcript path, outcome, token cost, failures. Grok's "every run is an inspectable record" rule; also our audit trail.+- **Wake-ups**: `Scheduler` manifests gain a `botId` field; a scheduled bot routine enqueues a bot turn on the **cron lane** (never the reply lane). Optional `gateScript` (Hermes `wakeAgent` idea): a cheap check that skips the LLM entirely when nothing changed.++### 2.4 Memory scoping (configured at bot setup)++`UserMemoryStore` already takes `userKey` and `dbPath` (`src/memory/user-memory.ts:95`) — bots get **their own `user_key` per bot id** in the second-brain DB (or a private DB path for strict isolation). Configurable at creation:++- `memory.scope: none` → no memory injection at all; the bot is stateless between turns (pure function of its persona + task).+- `own` (default) → the bot reads/writes only its own memory namespace. Injection mirrors the main agent's site (`agent.ts:2067`), with the bot's `userKey`.+- `shared-read` → additionally **read-only** access to listed shared paths / other bots' namespaces (`allowCrossBotRecall`), enforced in the store, not by prompt.+- Write path: bot memory writes are allowed by default but **rate/size-capped**, and can be configured to require owner approval at review time (staged writes surfaced via `/bots memory pending`) — never by interrupting a run.++Cross-bot *context sharing* (the research-bot → publisher-bot case) is **not** memory sharing: it's `bot_send` with a structured payload or a shared artifact written to the shared workspace dir. Memory access stays minimal by default.++### 2.5 Sandboxing & permissions (fail-closed, no mid-run prompts)++Bots get their **own** `PermissionManager` seeded from `bots/<id>/permissions.yaml`:++- **Tool allow/deny**: `tools.deny` always wins (OpenClaw rule: deny can't be re-enabled). Default-deny for destructive tools (`shell`, `write_file`, `delete_file`, `git_commit`) unless explicitly allowed at setup.+- **No interactive approval for bots, ever.** A permission prompt inside a bot turn is auto-resolved **deny** and journaled (`auto_deny` reason code). This is Hermes' fail-closed rule applied to a non-interactive worker. The owner sees denials in `/bots <id> journal` and can widen scopes at setup/review time.+- **No allow-all inheritance**: a bot can never inherit the session's allow-all mode — mirrors and extends the existing `isGlobalAutoApproveActive` rule that web/cloud requests don't inherit local allow-all.+- **Path scopes**: bot file access is scope-based like the main agent's manifest, defaulting to the bot's own dir + explicitly granted workspace paths. `cwdOnly`-style escape gates apply.+- **Dangerous-pattern denylist** reused from the main permission system for any allowed shell (plus the hardline set that survives every mode).+- **Budgets as security**: per-bot `dailyTokenBudget` and turn caps are hard stops (pause + journal, resume next window), protecting low-end devices and wallets from runaway loops.++### 2.6 Never-fail contract++Inherited from Mercury's "always uses a solution" ethos, hardened:++1. **Durable enqueue before ack** — every bot trigger (message, cron, API, relay) is persisted in the queue before the ingress acknowledges.+2. **Lease-based claiming** — crashed turns are requeued when their lease expires; no work is lost to a crash.+3. **Failure-typed retries** — transient failures (provider 429/timeout) retry with backoff + jitter, cap 3; permanent failures (invalid input, permission denial, prompt-injection suspicion, context exhaustion after one compaction retry) go **straight to the DLQ** — never re-queued.+4. **Restart semantics with exit codes** — `BotManager` restarts disabled-crash bots unconditionally but throttled (e.g., 15s min backoff, ×2 up to 15 min), and *intentional* states (`disabled`, `removed`, config error) stop restarts — the OpenClaw crash-loop lesson.+5. **Idempotency** — every trigger carries an idempotency key (source + event id); duplicates are dropped at enqueue.+6. **Run journal + DLQ inspection** — `/bots <id> journal`, `/bots <id> dlq`, `/bots <id> replay <jobId>`. Nothing fails silently.+7. **Graceful shutdown** — SIGINT/SIGTERM: stop intake, finish or lease-release in-flight turns, confirm offsets; restart resumes from the queue.++### 2.7 Surfaces++| Surface | How |+|---|---|+| **TUI** | New `/bots` slash command (fast-path, like `/agents`) → interactive panel: list bots (live states), onboard (guided, fully automatic config generation), edit config/persona, view journal, enable/disable, send a message. Also a TUI page in `cli.ts` command layer. |+| **Local HTTP API** | Hono module `src/web/api/bots.ts`: `GET /api/bots`, `POST /api/bots` (onboard), `GET/PATCH/DELETE /api/bots/:id`, `POST /api/bots/:id/message` (enqueue; returns job id), `POST /api/bots/:id/enable|disable`, `GET /api/bots/:id/journal`, `POST /api/bots/:id/replay`. Auth: existing web auth + attach token. |+| **Mercury Cloud** | `agent.command` envelope gains `bot.*` command types (list, message, configure) — same pattern as existing `model.select`/`task.stop`; cross-instance bot↔bot via `agent.message.relay`. |+| **Telegram (first channel)** | Ingress adapter: configured per bot or globally (`bots.channels.telegram`), `@botname` mention or `/bot <name>` routing in the existing grammY channel; bot replies stream back through the channel. Pairing/allowlist rules inherited from the channel's existing access control. |+| **Webhooks (P1)** | Generic inbound webhook route on the Hono server (`POST /api/bots/:id/hooks/<hook>`) with HMAC verification + dedupe → enqueue. |++### 2.8 Onboarding flow (`/bots onboard`)++Zero-prompt at runtime means **most of the effort goes into setup**, which stays interactive (it's the one designed human moment):++1. Name + one-line specialty → 2. persona: pick a template (marketing, research, publisher, custom) and edit `persona.md` → 3. model/provider (inherit or pick) → 4. tools: template presets + toggles; deny list explicit → 5. memory scope → 6. comms: pick linkable bots, direction arrows → 7. schedules (optional) → 8. budgets. Result: validated `bot.yaml` + persona.md + permissions.yaml; bot enabled immediately (or saved disabled). A bot can also be created fully non-interactively via `mercury bots create --from bot.yaml` or the HTTP API (Cloud path).++### 2.9 What a bot turn reuses++Same primitives as the main agent, isolated per bot: provider registry (per-bot model), AI SDK streaming loop, capability tools (own registry instance), skill loading (bot can be granted a skill allowlist), memory injection (own namespace), internal-message pattern for autonomous execution (from `processInternalPrompt`), task board for cross-bot shared state, background-task visibility.++### 2.10 Retention & disk budget — nothing grows forever++A bot fleet is six growing stores per bot (queue DB, journals, transcripts, mailboxes, DLQ, memory). Rule: **every store has a hard cap + retention window enforced at write time**, never a cleanup cron you forget.++| Store | Policy (default) | Enforced |+|---|---|---|+| Run transcripts | Keep full transcripts for the **last 50 runs/bot**; older evicted — safe because the journal is the permanent compact record | At run completion |+| Journal | Rotate at 5 MB, keep 3 rotations (~15–20 MB/bot lifetime bound) | At write |+| Queue | Completed jobs deleted **in the same transaction** as the journal write; pending backlog capped at 100/bot (refuse with `queue_full`) | Per claim/settle |+| DLQ | Cap 100 entries, oldest evicted **with a notification on eviction** | At enqueue |+| Mailboxes | Delivered messages purged 72h after receipt settles | Heartbeat sweep |+| Bot memory | Per-bot record/char caps + consolidation (Hermes' `MEMORY.md` budget pattern) + second-brain staleness machinery | At write |+| Bot artifacts (files) | Scoped workspace dir, 500 MB quota, LRU eviction of temp artifacts | At write |++Plus: **SQLite hygiene** (WAL + periodic idle `wal_checkpoint(TRUNCATE)` + scheduled incremental vacuum — the queue is the classic churn/bloat table; native backend only — the sql.js/JSON backends instead get commit-flush + file compaction on rotation); **disk-aware degradation** (free-space check at startup/heartbeat; below ~500 MB → pause cron lanes, journal-only transcript mode, notify owner once — degrade appetite, never fill the disk); **visibility** (`/bots storage` usage table + `bots.retention:` config block + `mercury bots prune --older-than 30d`); all consistent with existing Mercury precedent (background-task records pruned after 1h; second-brain staleness movement).++Net: a bot running hourly for a year costs tens of MB; a 10-bot fleet stays under ~200 MB before pruning.++### 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:++**Backend chain (probed once at `BotQueue` init, logged):**+1. **better-sqlite3** (native, WAL, synchronous, fastest) — default when the probe passes.+2. **sql.js** (WASM SQLite, pure JS, zero native compilation, works on any Node ≥ 12 and every Termux) — slower (whole-DB-in-memory, flush-to-disk on commit), but the same SQL schema, same leases, same DLQ semantics.+3. **JSON-file lease store** (`queue.json` + atomic tmp-rename + `fsync`, the `SessionRepository` style) — zero-dependency last resort.++**Correctness never depends on SQLite.** The design deliberately requires nothing native SQLite uniquely provides: the queue has a **single writer** (the in-process `BotManager`), so `SKIP LOCKED`-style concurrency is unnecessary — what the design actually needs is *durability* (atomic rename + fsync gives that on any filesystem) and *lease expiry* (pure timestamp logic). SQLite buys speed and indexed state queries, not correctness. What degrades without it is bounded and cosmetic:+- FTS-based journal/search queries → keyword-scan fallback (small datasets after §2.10 caps).+- Throughput: the WASM/JSON backends are 2–10× slower on writes — irrelevant at bot scale (tens of jobs/hour, not thousands/second).+- `bots storage` and `doctor` report which backend is active, so degraded devices are visible, not silent.++**Bot memory** gets the same treatment: instead of the second brain's current hard requirement on native SQLite (it fails with a build hint today), a bot's scoped memory store falls back to sql.js, then to a JSONL-backed store implementing the same interface — bots must work everywhere the main agent works.++**Build/packaging guard:** `npm install` must never hard-fail on devices without a compiler — `better-sqlite3` stays in `optionalDependencies` (verify this stays true), and any install script failure is non-fatal. CI gains a job running the bot test suite with the native dep *removed*, so the fallback chain is exercised on every change — the same discipline as testing wire shapes per provider.++---++## 3. UX design (researched: Hermes Desktop, OpenClaw Control UI, Grok Automations, Claude Code/Codex/Aider conventions + full audit of Mercury's TUI/web)++### 3.1 Steal-list — what the best products converged on++1. **Roster as chat-app list, not admin table** (Hermes): avatar that doubles as live status (animates during a turn), last-message preview, timestamp, "needs you" badge. Presence = **last activity** (Hermes counts "wrote within 90s" / recent heartbeat), not connection status.+2. **Canonical "forever chat" per bot, born with the bot** (Hermes + Grok both converge): every run's results land in the bot's own thread; `/new`/`/reset` inside a bot chat are rerouted to `/compact` so the relationship can't be destroyed by accident. Run = **resumable thread** (Grok: clicking a run opens the transcript and you can continue it).+3. **CI-style runs list per bot** (Grok's "4 Succeeded / 2 Upcoming" + Overview/Runs tabs; Hermes' `cron runs` attempt ledger `claimed → running → completed/failed/unknown`): title-plus-summary rows, drill-down to full transcript.+4. **A `doctor`-style read-only fleet health check** (Hermes `cron doctor`): groups failed runs, failed *deliveries* (output produced but never delivered), silently-not-firing schedules (15-min grace), dead jobs — **with a meaningful exit code** (1 = actionable, 0 = healthy).+5. **Background completions have a guaranteed delivery target** (OpenClaw shipped `target: "none"` as default and users never learned tasks finished — a silent data-loss bug): completion of a routine/cron run always delivers somewhere (bot chat minimum), never vanishes.+6. **Push only decision-requiring events** ("needs you" badge = escalation primitive: @user mentions, approvals, failures with reason codes); everything else waits in the timeline. Quiet acks suppressed (OpenClaw drops ≤300-char `HEARTBEAT_OK`).+7. **Stream, never bare spinners** (Codex's 20-min bare spinner was a top complaint): elapsed timer + latest-activity line for anything >seconds. **Lossless interruption**: stop keeps partial output (Aider/Claude Code rule).+8. **Approvals must be un-hideable** (Claude Code bug family #60644: prompts rendered behind a transcript viewer sat invisible forever; OpenClaw bug: `/approve` queued behind the blocked run): approval/escalation surfaces render in a layer nothing can cover, and resolver commands bypass queues.+9. **Layer-naming error cards** (Hermes): name which layer failed (provider/auth/streaming/disk) with actions Retry / Switch provider / Open logs / Copy details. In chat channels, name the gate-level reason only (`[reason: provider_rate_limit]`), hide internals behind a verbose flag.+10. **Chat transport discipline** (Telegram/Slack research): typing indicator re-sent every ~4s, non-throwing; chunking at 4096 *code points* (not UTF-16 length) with paragraph→sentence→word fallback and frozen chunk boundaries; multi-bot attribution **allowlisted at a router chokepoint** (never pass agent-written identity fields through — spoofing vector); filter out a bot's own messages to prevent loops; remove loading indicators on every exit path including errors.++### 3.2 Mercury bot screens (TUI)++The `/bots` family maps onto audited primitives (all refs from the Sept 2026 UX audit):++| Screen | Renders with | Status |+|---|---|---|+| **Roster** (`/bots`) | New `BotsBody` in `mode: 'bots'` — windowed list-with-cursor panel per `GitPanel`/`ExplorerPanel` pattern; `STATUS_ICONS` (🔵 pending 🟢 running 🟡 paused ✅ completed ❌ failed ⛔ halted); each row: persona avatar/emoji, live state, last-message preview, last-run time, `⚠ needs-you` badge | New panel, new AppMode |+| **Bot chat** (`/bots <id>`) | The existing chat body with a segmented transcript — reuses streaming pipeline, `ToolCallCard`, markdown renderer verbatim | Reuse + transcript scoping |+| **Runs view** (`/bots <id> journal`) | `PlanProgressView`-style checklist (`☑ ▶ ☐`) summarizing recent runs + drill-down rows (run id, trigger, outcome, tokens, duration) | New, composed |+| **Run detail** (journal → Enter) | Transcript view via existing `Ctrl+O`-style transcript-viewer pattern; run resumes via "continue" | Reuse transcript viewer |+| **DLQ / incidents** (`/bots <id> dlq`) | Text table (the `/bg list` pattern) with reason codes + `replay` action | New, composed |+| **Storage** (`/bots storage`) | Text table of per-store usage/pruning state (the `/sessions` text-table pattern) | New, composed |+| **Onboard** (`/bots onboard`) | Stepwise `withMenu(selectWithArrowKeys)` pickers (menu pattern exists) + multi-line input for persona editing | Composed from menu/input primitives |+| **Status bar segment** | `🤖 Nbots` added to `TokenBarView` next to `⏳ Nbg`/`🤖 Nagents`; roster badge drives it | One segment |+| **Notifications** | New minimal surface: system notice row (existing `sendSystemNotice`) for failures/needs-you only; no toasts in v1 | New, minimal |++Control verbs unify on the `/agents` vocabulary (`pause | resume | stop | enable | disable`) — not `/bg cancel`.++### 3.3 The plumbing gap that decides smoothness++`CLIChannel.send/stream` accepts a `targetId` but **ignores it** — one global transcript. Per-bot chats require making `targetId` real: messages stored by `target:chatId`, TUI renders the active target's segment, `<Static>` keys stay per-target. This is the single biggest UX infrastructure task (est. the bulk of the TUI effort) and it also unlocks clean Telegram per-bot threads. The web SPA already half-supports this: SSE `broadcast` filters by `targetId` (`web.ts:111–116`); bots become threads with a `botId` dimension, rendered with the existing ThreadList + `StreamingMessage` + `ToolCallCard` stack.++Live-state updates ride the existing 2s `statusPollerTick` diff-check (same as sub-agents/bgTasks) — no push infra needed for the TUI; web gets a `bots` SSE topic.++### 3.4 Cross-surface consistency rules++One state, four renderers — TUI, web SPA, Telegram, HTTP API all read the same BotManager state and the same journal:+- Roster rows, run states, and reason codes use **one shared vocabulary** (`STATUS_ICONS` TUI ↔ badge colors web ↔ emoji Telegram).+- Per-bot chat is thread-scoped on every surface (Telegram: per-bot thread/topic where available).+- Typing indicators, chunking (4096 code points, frozen boundaries), and attribution prefixes ("Message from 🤖 researcher:") are identical on all chat surfaces.+- Config edits (web `/api/bots/:id` PATCH) apply atomically with the same validation everywhere; TUI is the setup wizard, web is the power editor (mirrors Hermes' quick/advanced creation split).++### 3.5 Fleet health: `mercury bots doctor`++Read-only, exit-code-bearing (1 = actionable), grouping per bot: last run failed (with recorded error) · last delivery failed · next scheduled run overdue past grace · DLQ depth over threshold · budget exceeded · scope/config validation errors. Companion ladder mirrors Hermes: `/bots` (list+states) → `/bots <id> journal` (runs ledger) → `/bots <id> dlq` (incidents, replayable) → `mercury bots doctor` (fleet sweep).++---++## 4. Phased implementation plan++**P0 — core runtime (the "bots exist and are safe" milestone)**+1. `bots/` module: config schema (`MercuryConfig.bots`), profile dir layout, validation, loader.+2. `BotManager` + bot turn loop (in-process coroutine, own registries, per-bot provider) — no queue yet (in-memory), journal on.+3. `/bots` command: list / onboard (interactive) / send / enable / disable / journal.+4. Permission isolation: per-bot `PermissionManager`, fail-closed auto-deny, no allow-all inheritance.+5. Memory scoping (`userKey` per bot, `none|own|shared-read`).+6. Tests: Vitest, colocated, tmp-dir injection (repo pattern); **provider wire-shape tests for the bot path across all providers** (LiteLLM/LM Studio are OpenAI-compat chat — see past drift).+7. Retention: write-time caps + journal rotation + SQLite checkpointing + `/bots storage` (§2.10) — cheap now, expensive to retrofit.++**P1 — durability + comms + surfaces**+7. `BotQueue` (SQLite, leases, DLQ) + idempotency; replace in-memory queue.+8. `BotBus` + `bot_send` tool + delivery receipts; Cloud relay bridging.+9. Scheduler integration (`botId` on manifests, cron lane, gate scripts).+10. HTTP API module; Telegram ingress (chunking/attribution rules per §3.1.10).+11. TUI per-bot chat: make `CLIChannel.targetId` real (transcript-by-target) — the biggest UX plumbing task; web `botId` thread dimension.+12. Notification surface: needs-you badge + system-notice rows (failures/escalations only, guaranteed completion delivery target — never OpenClaw's `target: "none"` default).+13. `mercury bots doctor` fleet health check (exit-code bearing) + DLQ/incidents with ack.++**P2 — scale + containment**+12. Optional `worker_thread` isolation mode for individual bots; warm-pool cap (Hermes-style, default 2–3).+13. Webhook ingress; group rooms (multi-bot deliberation with round caps).+14. Auto-skill synthesis from bot journals (ties into the roadmap's self-improvement wedge); bot skill marketplace presets.++---++## 5. Explicit non-goals (v1)++- No free-form user-chat takeover: bots are not the main agent; they don't answer in the owner's main session.+- No per-bot processes/threads by default (opt-in P2 only).+- No shared *write* memory between bots by default; sharing is structured (`bot_send`, artifacts), configured, and read-mostly.+- No human-in-the-loop prompts inside bot turns — fail closed, journal, review later.+- No cross-user bot sharing in v1 (Cloud relay is per-owner pairing, as today).++---++## 6. Decisions (resolved 2026-09-16, see ADR-012 in DECISIONS.md)++1. **Autonomous schedules in P0** — yes. Cron routines ship with the core runtime, on a dedicated cron lane.+2. **Default memory scope: `own`** — per-bot private namespace (Hermes/OpenClaw both default per-agent); configurable to `none`/`shared-read` at setup.+3. **Queue engine: SQLite lease queue** at `~/.mercury/bots/queue.db`, reusing the existing better-sqlite3 probe pattern.+4. **Bot↔bot delivery: fire-and-forget mailbox** (`bot_send` + delivery receipts), not nested invocation.+5. **SQLite-less devices (added 2026-09-16):** queue/memory storage backend chain better-sqlite3 → sql.js (WASM) → JSON-file lease store, chosen by runtime probe; correctness never depends on native SQLite (single-writer queue needs only durability); CI exercises the no-native path on every change (§2.11).\ No newline at end of filediff --git a/DECISIONS.md b/DECISIONS.mdindex de3d95cc..76315abd 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -104,4 +104,21 @@- Keep the 50 cap but remove hard-delete — still limits knowledge breadth- Increase cap to 200 — more headroom but still arbitrary- Tier-based caps (e.g., 20 durable + 30 active) — more complex, harder to tune-- **Consequence**: No memory is ever permanently lost to time. The subconscious layer archives everything, and the recall mechanism surfaces dormant memories when context demands it. The 30-day threshold is configurable and the recall scoring weights can be tuned based on real-world usage.\ No newline at end of file+- **Consequence**: No memory is ever permanently lost to time. The subconscious layer archives everything, and the recall mechanism surfaces dormant memories when context demands it. The 30-day threshold is configurable and the recall scoring weights can be tuned based on real-world usage.++## ADR-012: Mercury Bots — persistent persona-scoped agents, in-process++- **Context**: Mercury needs a second agent kind alongside the main conversational agent: multiple persistent "bots" (marketing, research, publisher, …), each with its own character, model, scoped memory, and tool permissions. Bots must never block the main agent loop, never prompt the user at runtime, respect low-end hardware (Termux/RPi), and never lose work. Competitor research (Hermes Agent profiles, OpenClaw gateway lanes, Grok-on-X prompt templates + Automations) and Mercury's own architecture audit (see `BOTS-ARCHITECTURE.md`) inform the design.+- **Decision**:+ - **Bot = profile dir + runtime**: `~/.mercury/bots/<botId>/` holds `bot.yaml`, `persona.md`, `permissions.yaml`, `.env` (mirrors Hermes' profile primitive; persona as markdown like soul files).+ - **In-process execution**: bots run as async coroutines in a `BotManager` with a durable SQLite lease queue (`~/.mercury/bots/queue.db`) — never through `Agent.processQueue`, never one thread/process per bot (unaffordable on Termux; per-bot `worker_thread` isolation is an opt-in P2 escape hatch).+ - **Full state isolation per bot**: own `CapabilityRegistry` + `PermissionManager` (fixing sub-agents' shared-registry hazard), own provider/model resolution, own memory namespace via `UserMemoryStore` `userKey` (default scope `own`; `none`/`shared-read` configurable).+ - **Fail-closed autonomy**: no interactive approvals inside bot turns — permission questions auto-deny and journal; deny-list beats allow-list; no allow-all inheritance; token/step budgets are hard stops.+ - **Never-fail contract**: durable enqueue-before-ack, lease-based claiming with expiry requeue, failure-typed retries (transient → backoff; denials/injection-suspect → DLQ, never retried), throttled supervisor restarts with exit-code semantics, idempotency keys, run journal + replayable DLQ.+ - **Bot↔bot comms**: fire-and-forget mailbox (`bot_send`, delivery receipts, typed failure codes), bridged cross-instance via the existing Cloud `agent.message.relay`. Cron routines (separate lane) in P0.+ - **Surfaces**: `/bots` TUI command, Hono HTTP API module, Mercury Cloud `bot.*` commands, Telegram ingress; generic webhooks in P1.+- **Alternatives considered**:+ - Hermes-style process-per-bot / warm process pool (~60MB/bot) — clean isolation but unaffordable on Termux/Pi; kept as P2 opt-in only+ - JSON-file lease queue — zero native deps but weak concurrent-writer semantics vs SQLite leases+ - Direct nested bot invocation (simpler reasoning) — couples runtimes, deadlock-prone with cyclic links+- **Consequence**: Bots share the process (cheap: dozens on a Pi) but not state; the main agent's serial queue is untouched; all bot state survives crashes via the queue + journal. Sub-agent model/registry hardcoding (`providers.getDefault()`, shared registries) gets generalized as a side effect. Requires per-provider wire-shape tests for the bot LLM path (LiteLLM/LM Studio are OpenAI-compat chat).\ No newline at end of filediff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsnew file mode 100644index 00000000..b77d7e6c--- /dev/null+++ b/src/bots/bot-manager.test.ts@@ -0,0 +1,359 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++// Mock only generateText; tool()/zodSchema/stepCountIs must stay real so the+// CapabilityRegistry tool factories still construct.+vi.mock('ai', async (importOriginal) => {+ const actual = await importOriginal<typeof import('ai')>();+ return {+ ...actual,+ generateText: vi.fn(),+ };+});++import { generateText } from 'ai';+import { BotManager } from './bot-manager.js';+import { BotStore } from './store.js';+import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';+import type { BotManifest } from './types.js';++const mockedGenerateText = vi.mocked(generateText);++function scriptedProvider(name = 'stub') {+ return {+ name,+ model: 'stub-model',+ generateText: async () => ({ text: 'ok', inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub-model', provider: name }),+ streamText: async function* () { yield { text: 'ok', done: true }; },+ isAvailable: () => true,+ getModelInstance: () => ({}),+ getModel: () => 'stub-model',+ } as any;+}++const providersRegistry = {+ get: (name?: string) => (name === 'stub' ? scriptedProvider('stub') : undefined),+ getDefault: () => scriptedProvider('default'),+} as any;++const tokenBudget = {+ recordUsage: () => {},+ getRemaining: () => 100000,+ getStatusText: () => 'budget ok',+ getUsagePercentage: () => 0,+} as any;++function makeManager(root: string, overrides: Partial<MercuryConfig> = {}): BotManager {+ const config = getDefaultConfig() as MercuryConfig;+ config.bots.maxConcurrent = 4;+ Object.assign(config, overrides);+ return new BotManager({+ config,+ providers: providersRegistry,+ tokenBudget,+ store: new BotStore(join(root, 'bots')),+ userMemoryFactory: () => null, // no SQLite dependency in unit tests+ });+}++function seedBot(store: BotStore, id: string, manifestOverrides: Partial<BotManifest> = {}) {+ return store.create({ id, name: id.toUpperCase(), manifest: manifestOverrides });+}++beforeEach(() => {+ mockedGenerateText.mockReset();+});++describe('BotManager queue + turn lifecycle', () => {+ let root: string;+ let store: BotStore;+ let manager: BotManager;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-manager-'));+ store = new BotStore(join(root, 'bots'));+ manager = makeManager(root);+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('rejects jobs for unknown and disabled bots with typed reasons', async () => {+ expect(manager.enqueue('ghost', { trigger: 'chat', prompt: 'hi' })).toMatchObject({ accepted: false, reasonCode: 'target_unknown' });+ seedBot(store, 'sleepy', { enabled: false });+ expect(manager.enqueue('sleepy', { trigger: 'chat', prompt: 'hi' })).toMatchObject({ accepted: false, reasonCode: 'target_disabled' });+ });++ it('runs a chat turn to completion, journals it, and notifies', async () => {+ mockedGenerateText.mockResolvedValue({ text: 'done', finishReason: 'stop', usage: { inputTokens: 10, outputTokens: 5 } } as any);+ seedBot(store, 'researcher');+ const notifications: string[] = [];+ manager['notify'] = async (_t, _c, message) => { notifications.push(message); };++ const result = manager.enqueue('researcher', { trigger: 'chat', prompt: 'Summarize the market' });+ expect(result.accepted).toBe(true);+ // pump is synchronous-ish; the turn runs as a detached promise — wait for it+ await vi.waitFor(() => {+ const records = manager.getJournal('researcher');+ expect(records.length).toBe(1);+ expect(records[0].state).toBe('completed');+ });+ expect(notifications.some(n => n.includes('researcher'.toUpperCase()) || n.includes('RESEARCHER'))).toBe(true);+ const summary = manager.getStatusSummaries().find(s => s.id === 'researcher');+ expect(summary?.state).toBe('idle');+ expect(summary?.lastRunState).toBe('completed');+ });++ it('pauses the bot for the rest of the day when the daily token budget is hit', async () => {+ mockedGenerateText.mockImplementation(async (opts: any) => {+ opts.onStepFinish?.({ usage: { inputTokens: 100, outputTokens: 100 } });+ return { text: 'ok', finishReason: 'stop', usage: { inputTokens: 100, outputTokens: 100 } } as any;+ });+ seedBot(store, 'thrifty', { autonomy: { dailyTokenBudget: 1 } });+ manager.enqueue('thrifty', { trigger: 'chat', prompt: 'go' });+ await vi.waitFor(() => {+ const summary = manager.getStatusSummaries().find(s => s.id === 'thrifty');+ expect(summary?.state).toBe('paused');+ });+ // Budget-paused bots do not drain their queue+ expect(manager.getQueuedCount('thrifty')).toBe(0);+ });++ it('retries transient provider failures with backoff, bounded', async () => {+ mockedGenerateText.mockRejectedValue(new Error('HTTP 429: too many requests'));+ seedBot(store, 'flaky', { autonomy: { dailyTokenBudget: 100000 } });+ vi.useFakeTimers();+ try {+ manager.enqueue('flaky', { trigger: 'chat', prompt: 'go' });+ await vi.advanceTimersByTimeAsync(0);+ await vi.waitFor(() => expect(manager.getJournal('flaky').length).toBe(1));+ expect(manager.getJournal('flaky')[0].reasonCode).toBe('provider_rate_limit');+ } finally {+ vi.useRealTimers();+ }+ });++ it('degrades to a stateless bot when the memory store cannot be built', async () => {+ // Simulates a SQLite-less device: the store factory throws.+ const config = getDefaultConfig() as MercuryConfig;+ config.bots.maxConcurrent = 4;+ const manager = new BotManager({+ config,+ providers: providersRegistry,+ tokenBudget,+ store: new BotStore(join(root, 'bots')),+ userMemoryFactory: () => { throw new Error('better-sqlite3 is not available'); },+ });+ mockedGenerateText.mockResolvedValue({ text: 'stateless ok', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any);+ seedBot(store, 'nodb');+ manager.enqueue('nodb', { trigger: 'chat', prompt: 'hello' });+ await vi.waitFor(() => {+ const records = manager.getJournal('nodb');+ expect(records.length).toBe(1);+ expect(records[0].state).toBe('completed');+ });+ });+});++describe('BotManager mailboxes (bot-to-bot comms)', () => {+ let root: string;+ let store: BotStore;+ let manager: BotManager;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-mail-'));+ store = new BotStore(join(root, 'bots'));+ manager = makeManager(root);+ seedBot(store, 'researcher');+ seedBot(store, 'publisher');+ seedBot(store, 'offline', { enabled: false });+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('returns typed failures for unknown/disabled targets', () => {+ expect(manager.sendToBot('ghost', 'researcher', 'hi')).toMatchObject({ accepted: false, reasonCode: 'target_unknown' });+ expect(manager.sendToBot('offline', 'researcher', 'hi')).toMatchObject({ accepted: false, reasonCode: 'target_disabled' });+ });++ it('delivers mail and wakes an idle bot, attributed in the prompt', async () => {+ mockedGenerateText.mockImplementation(async ({ messages }: any) => {+ const sawMail = JSON.stringify(messages).includes('Message from 🤖 researcher');+ return { text: sawMail ? 'consumed handoff' : 'idle check', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;+ });+ const result = manager.sendToBot('publisher', 'researcher', 'Here are the findings');+ expect(result.accepted).toBe(true);+ await vi.waitFor(() => {+ const records = manager.getJournal('publisher');+ expect(records.length).toBe(1);+ expect(records[0].trigger).toBe('mailbox');+ });+ // The captured turn messages included the attributed mailbox content+ const firstCall = mockedGenerateText.mock.calls[0][0] as any;+ expect(JSON.stringify(firstCall.messages)).toContain('Message from 🤖 researcher');+ expect(JSON.stringify(firstCall.messages)).toContain('Here are the findings');+ });++ it('queues mail behind an active turn instead of dropping it', () => {+ // Simulate a running turn+ manager['running'].set('publisher', new Set(['busy']));+ manager.sendToBot('publisher', 'researcher', 'more findings');+ expect(manager.peekMailbox('publisher')).toHaveLength(1);+ // No mailbox-triggered job enqueued while running — mail waits for drain+ expect(manager.getQueuedCount('publisher')).toBe(0);+ });+});++describe('Per-bot permission isolation (fail-closed)', () => {+ let root: string;+ let store: BotStore;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-perms-'));+ store = new BotStore(join(root, 'bots'));+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('builds an isolated registry with no ask handler and a bot channel context', () => {+ const manifest = store.create({ id: 'writer', name: 'Writer' }) as BotManifest;+ const registry = createBotCapabilityRegistry({+ botId: 'writer',+ manifest,+ botDir: store.botDir('writer'),+ permissions: store.readPermissions('writer'),+ userMemory: null,+ config: getDefaultConfig() as MercuryConfig,+ });+ const pm = registry.permissions;+ expect(pm.getCurrentChannelType()).toBe('bot');+ // Fail-closed: with no ask handler and no allow-all, every approval denies+ expect(pm.isAutoApproveAll()).toBe(false);+ // Default all-cwd scope replaced by the bot's own dir only+ const scopes = pm.getManifest().capabilities.filesystem.scopes;+ expect(scopes).toHaveLength(1);+ expect(scopes[0].path).toBe(store.botDir('writer'));+ // Shell auto-approve list emptied; dangerous blocklist retained+ expect(pm.getManifest().capabilities.shell.autoApproved).toEqual([]);+ expect(pm.getManifest().capabilities.shell.blocked).toContain('sudo *');+ });++ it('fs write outside the bot scope is denied without prompting', async () => {+ const manifest = store.create({ id: 'writer', name: 'Writer' }) as BotManifest;+ const registry = createBotCapabilityRegistry({+ botId: 'writer',+ manifest,+ botDir: store.botDir('writer'),+ permissions: store.readPermissions('writer'),+ userMemory: null,+ config: getDefaultConfig() as MercuryConfig,+ });+ const outside = join(root, 'elsewhere.txt');+ const verdict = await registry.permissions.checkFsAccess(outside, 'write');+ expect(verdict.allowed).toBe(false);+ const inside = join(store.botDir('writer'), 'note.md');+ const insideVerdict = await registry.permissions.checkFsAccess(inside, 'write');+ expect(insideVerdict.allowed).toBe(true);+ });++ it('strips interactive and global-mutation tools from every bot toolset', () => {+ const manifest = store.create({ id: 'writer', name: 'Writer' }) as BotManifest;+ const registry = createBotCapabilityRegistry({+ botId: 'writer',+ manifest,+ botDir: store.botDir('writer'),+ permissions: store.readPermissions('writer'),+ userMemory: null,+ config: getDefaultConfig() as MercuryConfig,+ });+ const tools = filterBotTools(registry.getTools(), manifest);+ for (const forbidden of ['ask_user', 'approve_scope', 'approve_command', 'update_plan', 'delegate_task', 'install_skill', 'schedule_task', 'bot_send']) {+ expect(tools[forbidden]).toBeUndefined();+ }+ // Dangerous tools are denied by default (normalizeBotManifest)+ expect(tools['run_command']).toBeUndefined();+ expect(tools['write_file']).toBeUndefined();+ // Read-only tools survive the default deny list+ expect(tools['read_file']).toBeDefined();+ expect(tools['list_dir']).toBeDefined();+ });++ it('a non-empty allow list restricts the toolset exactly to that list', () => {+ const manifest = store.create({+ id: 'reader',+ name: 'Reader',+ manifest: { tools: { allow: ['read_file'], deny: [] } },+ }) as BotManifest;+ const registry = createBotCapabilityRegistry({+ botId: 'reader',+ manifest,+ botDir: store.botDir('reader'),+ permissions: store.readPermissions('reader'),+ userMemory: null,+ config: getDefaultConfig() as MercuryConfig,+ });+ const tools = filterBotTools(registry.getTools(), manifest);+ expect(Object.keys(tools)).toEqual(['read_file']);+ });++ it('bot-blocked commands extend the shell denylist', () => {+ const manifest = store.create({ id: 'writer', name: 'Writer' }) as BotManifest;+ store.writePermissions('writer', { paths: [{ scope: 'self', read: true, write: true }], blockedCommands: ['curl *'] });+ const registry = createBotCapabilityRegistry({+ botId: 'writer',+ manifest,+ botDir: store.botDir('writer'),+ permissions: store.readPermissions('writer'),+ userMemory: null,+ config: getDefaultConfig() as MercuryConfig,+ });+ expect(registry.permissions.getManifest().capabilities.shell.blocked).toContain('curl *');+ });+});++describe('bot_send tool scoping', () => {+ let root: string;+ let store: BotStore;+ let manager: BotManager;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-send-'));+ store = new BotStore(join(root, 'bots'));+ manager = makeManager(root);+ seedBot(store, 'publisher');+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('is only available for bots with a configured roster and rejects unlinked targets', async () => {+ const { createBotSendTool } = await import('./tools/bot-send.js');+ // The publisher bot is idle, so sendToBot wakes it and its wake-turn+ // drains the mailbox immediately — verify via the journal instead.+ mockedGenerateText.mockImplementation(async ({ messages }: any) => {+ void messages;+ return { text: 'handled', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;+ });+ const tool = createBotSendTool(manager, 'researcher', ['publisher']) as any;+ const denied = await tool.execute({ target: 'stranger', message: 'hi' });+ expect(denied).toContain('not configured');+ const ok = await tool.execute({ target: 'publisher', message: 'findings' });+ expect(ok).toContain('Queued for publisher');+ await vi.waitFor(() => {+ const records = manager.getJournal('publisher');+ expect(records.length).toBe(1);+ expect(records[0].trigger).toBe('mailbox');+ });+ const firstCall = mockedGenerateText.mock.calls[0][0] as any;+ expect(JSON.stringify(firstCall.messages)).toContain('Message from 🤖 researcher');+ });+});\ No newline at end of filediff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsnew file mode 100644index 00000000..b0517396--- /dev/null+++ b/src/bots/bot-manager.ts@@ -0,0 +1,506 @@+import { cpus } from 'node:os';+import { randomUUID } from 'node:crypto';+import type { Tool } from 'ai';+import type { MercuryConfig } from '../utils/config.js';+import type { ProviderRegistry } from '../providers/registry.js';+import type { TokenBudget } from '../utils/tokens.js';+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, BOT_JOURNAL_FILENAME, isValidCronExpression } from './store.js';+import { BotJournal } from './journal.js';+import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';+import { createBotSendTool } from './tools/bot-send.js';+import { runBotTurn, isTransientFailure, type BotTurnMail } from './bot-turn.js';+import { logger } from '../utils/logger.js';+import type {+ BotLiveState,+ BotManifest,+ BotRunRecord,+ BotStatusSummary,+ BotTrigger,+} from './types.js';++export interface BotJob {+ id: string;+ botId: string;+ trigger: BotTrigger;+ prompt: string;+ /** Mailbox attribution — set for bot-to-bot deliveries. */+ fromBot?: string;+ /** Originating surface for completion delivery. */+ source?: { channelType: string; channelId: string };+ createdAt: number;+ attempts: number;+}++export interface BotSendResult {+ accepted: boolean;+ jobId?: string;+ reasonCode?: 'target_disabled' | 'target_unknown' | 'queue_full' | 'not_linked';+}++export interface BotManagerDeps {+ config: MercuryConfig;+ providers: ProviderRegistry;+ tokenBudget: TokenBudget;+ store?: BotStore;+ /** Per-bot memory factory (P0-5 wires the default: UserMemoryStore with bot:<id> key). */+ userMemoryFactory?: (botId: string, manifest: BotManifest) => UserMemoryStore | null;+ /** Deliver turn output to the invoking surface (chat/telegram/api). */+ notify?: (channelType: string, channelId: string, message: string) => Promise<void>;+}++const MAX_TRANSIENT_ATTEMPTS = 3;+const MAILBOX_CAPACITY = 100;++/**+ * Owns the bot fleet: per-bot job queues, isolated turn runtimes, mailboxes,+ * run journals, and live statuses. Bots never touch Agent.processQueue —+ * they run as independent coroutines in this manager (BOTS-ARCHITECTURE.md §2.2).+ */+export class BotManager {+ readonly store: BotStore;+ private readonly config: MercuryConfig;+ private readonly providers: ProviderRegistry;+ private readonly tokenBudget: TokenBudget;+ private readonly userMemoryFactory?: BotManagerDeps['userMemoryFactory'];+ private notify?: BotManagerDeps['notify'];++ /** Deliver turn output to the invoking surface (wired by the Agent). */+ setNotify(cb: NonNullable<BotManagerDeps['notify']>): void {+ this.notify = cb;+ }++ private queues: Map<string, BotJob[]> = new Map();+ private mailboxes: Map<string, BotTurnMail[]> = new Map();+ private running: Map<string, Set<string>> = new Map(); // botId → running job ids+ private aborts: Map<string, AbortController> = new Map(); // job key → controller+ private registries: Map<string, { registry: CapabilityRegistry; tools: Record<string, Tool> }> = new Map();+ private activity: Map<string, string> = new Map(); // botId → current activity+ private lastRun: Map<string, { at: number; state: BotRunRecord['state'] }> = new Map();+ private needsYou: Set<string> = new Set();+ private journals: Map<string, BotJournal> = new Map();+ private userMemories: Map<string, UserMemoryStore | null> = new Map();+ private disabled = new Set<string>();+ /** Per-bot daily token usage: botId → { day (UTC yyyy-mm-dd), tokens }. */+ private dailyTokens: Map<string, { day: string; tokens: number }> = new Map();+ private pausedForBudget = new Set<string>();++ constructor(deps: BotManagerDeps) {+ this.config = deps.config;+ this.providers = deps.providers;+ this.tokenBudget = deps.tokenBudget;+ this.userMemoryFactory = deps.userMemoryFactory ?? ((botId, manifest) => {+ // Default: per-bot namespace in the shared second-brain DB.+ // scope 'none' = stateless bot. SQLite-less devices degrade to a+ // stateless bot until the sql.js/JSONL fallback lands (P1, §2.11).+ const scope = manifest.memory?.scope ?? 'own';+ if (scope === 'none') return null;+ try {+ return new UserMemoryStoreImpl(this.config, `bot:${botId}`);+ } catch (err: any) {+ logger.warn({ botId, err: err?.message }, 'Bot memory store unavailable (no native SQLite) — running stateless');+ return null;+ }+ });+ this.notify = deps.notify;+ this.store = deps.store ?? new BotStore();+ }++ /** Fleet-wide concurrency cap: config override or clamp(2, cpus-1). */+ private fleetCap(): number {+ const configured = this.config.bots?.maxConcurrent ?? 0;+ if (configured > 0) return configured;+ return Math.max(2, Math.min(cpus().length - 1, 8));+ }++ private journalFor(botId: string): BotJournal {+ let j = this.journals.get(botId);+ if (!j) {+ const manifest = this.store.get(botId);+ const retention = { ...(this.config.bots?.retention ?? {}), ...(manifest?.retention ?? {}) };+ j = new BotJournal(this.store.botDir(botId), retention.journalRotateBytes, retention.journalKeepRotations);+ this.journals.set(botId, j);+ }+ return j;+ }++ private getOrCreateJournal(botId: string): BotJournal {+ return this.journalFor(botId);+ }++ enqueue(botId: string, job: { trigger: BotTrigger; prompt: string; fromBot?: string; source?: { channelType: string; channelId: string } }): { jobId: string; accepted: boolean; reasonCode?: string } {+ const manifest = this.store.get(botId);+ if (!manifest) return { jobId: '', accepted: false, reasonCode: 'target_unknown' };+ if (!manifest.enabled || this.disabled.has(botId)) return { jobId: '', accepted: false, reasonCode: 'target_disabled' };++ const queue = this.queues.get(botId) ?? [];+ this.queues.set(botId, queue);+ if (queue.length >= MAILBOX_CAPACITY) {+ return { jobId: '', accepted: false, reasonCode: 'queue_full' };+ }+ const id = randomUUID().slice(0, 8);+ queue.push({ id, botId, trigger: job.trigger, prompt: job.prompt, fromBot: job.fromBot, source: job.source, createdAt: Date.now(), attempts: 0 });+ this.pump(botId);+ return { jobId: id, accepted: true };+ }++ /** Fire-and-forget mailbox delivery from another bot. */+ sendToBot(targetBotId: string, fromBot: string, content: string): BotSendResult {+ const manifest = this.store.get(targetBotId);+ if (!manifest) return { accepted: false, reasonCode: 'target_unknown' };+ if (!manifest.enabled || this.disabled.has(targetBotId)) return { accepted: false, reasonCode: 'target_disabled' };++ const box = this.mailboxes.get(targetBotId) ?? [];+ if (box.length >= MAILBOX_CAPACITY) {+ return { accepted: false, reasonCode: 'queue_full' };+ }+ box.push({ from: fromBot, content });+ this.mailboxes.set(targetBotId, box);++ // If the bot is idle (no running turn, empty job queue), wake it with a+ // mailbox-driven turn so mail is consumed promptly.+ const queue = this.queues.get(targetBotId) ?? [];+ const isRunning = (this.running.get(targetBotId)?.size ?? 0) > 0;+ let jobId: string | undefined;+ if (queue.length === 0 && !isRunning) {+ jobId = randomUUID().slice(0, 8);+ queue.push({ id: jobId, botId: targetBotId, trigger: 'mailbox', prompt: '', createdAt: Date.now(), attempts: 0 });+ this.queues.set(targetBotId, queue);+ this.pump(targetBotId);+ }+ return { accepted: true, jobId };+ }++ /** Poll-and-drain a bot's mailbox (used by turns and by inbox inspection). */+ drainMailbox(botId: string): BotTurnMail[] {+ const box = this.mailboxes.get(botId) ?? [];+ this.mailboxes.set(botId, []);+ return box;+ }++ peekMailbox(botId: string): BotTurnMail[] {+ return [...(this.mailboxes.get(botId) ?? [])];+ }++ /** Kick the queue: start turns while slots (per-bot and fleet-wide) exist. */+ private pump(botId: string): void {+ const manifest = this.store.get(botId);+ if (!manifest?.enabled || this.disabled.has(botId)) return;+ const today = new Date().toISOString().slice(0, 10);+ const used = this.dailyTokens.get(botId);+ if (used && used.day !== today) {+ this.dailyTokens.delete(botId);+ this.pausedForBudget.delete(botId);+ }+ if (this.pausedForBudget.has(botId)) {+ this.activity.set(botId, 'Paused — daily token budget reached');+ return;+ }+ const queue = this.queues.get(botId) ?? [];+ const running = this.running.get(botId) ?? new Set();+ this.running.set(botId, running);++ const perBotCap = manifest.autonomy?.maxConcurrent ?? 1;++ while (queue.length > 0 && running.size < perBotCap && this.fleetRunningCount() < this.fleetCap()) {+ const job = queue.shift()!;+ void this.executeTurn(job);+ }+ }++ /** Hard daily budget stop: pause (resume next UTC day), never die. */+ private recordBotTokens(botId: string, manifest: BotManifest, tokens: number): void {+ const today = new Date().toISOString().slice(0, 10);+ const entry = this.dailyTokens.get(botId);+ const next = entry && entry.day === today ? entry.tokens + tokens : tokens;+ this.dailyTokens.set(botId, { day: today, tokens: next });+ const cap = manifest.autonomy?.dailyTokenBudget;+ if (cap && next >= cap) {+ this.pausedForBudget.add(botId);+ logger.warn({ botId, used: next, cap }, 'Bot daily token budget reached — pausing until next day');+ }+ }++ private fleetRunningCount(): number {+ let total = 0;+ for (const s of this.running.values()) total += s.size;+ return total;+ }++ private async executeTurn(job: BotJob): Promise<void> {+ const { botId } = job;+ const running = this.running.get(botId) ?? new Set();+ this.running.set(botId, running);+ running.add(job.id);+ const controller = new AbortController();+ this.aborts.set(`${botId}:${job.id}`, controller);+ this.activity.set(botId, describeJob(job));++ const manifest = this.store.get(botId);+ if (!manifest) {+ running.delete(job.id);+ return;+ }++ try {+ const turn = this.buildTurn(botId, manifest, job, controller.signal);+ const output = await runBotTurn(turn.input);+ turn.cleanup();++ const record: BotRunRecord = {+ runId: job.id,+ botId,+ trigger: job.trigger,+ state: output.status === 'completed' ? 'completed' : output.status,+ startedAt: job.createdAt,+ durationMs: Date.now() - job.createdAt,+ tokensIn: output.tokensIn,+ tokensOut: output.tokensOut,+ summary: output.output.slice(0, 300),+ error: output.error,+ reasonCode: output.reasonCode,+ };+ this.journalFor(botId).append(record);+ this.lastRun.set(botId, { at: Date.now(), state: record.state });+ this.needsYou.delete(botId);+ this.recordBotTokens(botId, manifest, output.tokensIn + output.tokensOut);++ // Transient provider failures retry with backoff, bounded; permanent+ // failures journal and stop (never re-queued — BOTS-ARCHITECTURE §2.6).+ if (output.status === 'failed' && output.reasonCode && isTransientFailure(output.reasonCode) && job.attempts + 1 < MAX_TRANSIENT_ATTEMPTS) {+ const delay = Math.min(15000, 1000 * 2 ** job.attempts);+ logger.info({ botId, jobId: job.id, reasonCode: output.reasonCode, retryIn: delay }, 'Bot turn failed transiently — retrying');+ setTimeout(() => {+ this.enqueue(botId, { trigger: job.trigger, prompt: job.prompt, fromBot: job.fromBot });+ }, delay).unref?.();+ } else if (output.status === 'failed') {+ this.needsYou.add(botId);+ logger.warn({ botId, jobId: job.id, reasonCode: output.reasonCode }, 'Bot turn failed permanently — see journal/DLQ');+ }++ // Deliver the outcome (guaranteed delivery target: the bot's own chat+ // minimum — never silently dropped, BOTS-ARCHITECTURE §3.1.5).+ if (this.notify && output.status !== 'halted' && job.trigger !== 'mailbox') {+ const channelType = job.source?.channelType ?? (job.trigger === 'telegram' ? 'telegram' : 'bot');+ const channelId = job.source?.channelId ?? botId;+ const icon = output.status === 'completed' ? '🤖' : output.status === 'failed' ? '❌' : '⏸';+ const text = `${icon} **${manifest.name}** (${job.trigger}): ${output.output.slice(0, 800)}`;+ await this.notify(channelType, channelId, text).catch((e) =>+ logger.warn({ e, botId }, 'Bot completion notify failed'));+ }+ } catch (err: any) {+ logger.error({ botId, jobId: job.id, err: err?.message }, 'Bot turn crashed');+ this.journalFor(botId).append({+ runId: job.id,+ botId,+ trigger: job.trigger,+ state: 'failed',+ startedAt: job.createdAt,+ durationMs: Date.now() - job.createdAt,+ tokensIn: 0,+ tokensOut: 0,+ error: err?.message,+ reasonCode: 'unknown_error',+ });+ this.needsYou.add(botId);+ } finally {+ running.delete(job.id);+ this.aborts.delete(`${botId}:${job.id}`);+ if (running.size === 0) this.activity.delete(botId);+ this.pump(botId);+ }+ }++ private userMemoryFor(botId: string, manifest: BotManifest): UserMemoryStore | null {+ if (this.userMemories.has(botId)) return this.userMemories.get(botId) ?? null;+ const factory = this.userMemoryFactory;+ if (!factory) return null;+ let store: UserMemoryStore | null = null;+ try {+ store = factory(botId, manifest);+ } catch (err: any) {+ // Memory is an enhancement, never a hard dependency — a store that+ // fails to build (e.g. no native SQLite) degrades to a stateless bot.+ logger.warn({ botId, err: err?.message }, 'Bot memory store build failed — running stateless');+ }+ this.userMemories.set(botId, store);+ return store;+ }++ private buildTurn(botId: string, manifest: BotManifest, job: BotJob, signal: AbortSignal): { input: Parameters<typeof runBotTurn>[0]; cleanup: () => void } {+ const { registry, tools } = this.getOrCreateRuntime(botId, manifest);+ const userMemory = this.userMemoryFor(botId, manifest);++ const mail: BotTurnMail[] = [];+ // Deliveries from other bots arrive via the mailbox; drain at turn start.+ const pending = this.drainMailbox(botId);+ mail.push(...pending);++ return {+ input: {+ manifest,+ trigger: job.trigger,+ prompt: job.prompt,+ persona: this.store.readPersona(botId),+ mail,+ pollMail: () => this.drainMailbox(botId),+ capabilities: registry,+ tools,+ userMemory,+ provider: resolveProvider(this.providers, manifest),+ tokenBudget: this.tokenBudget,+ abortSignal: signal,+ },+ cleanup: () => { /* per-bot registries are persistent, nothing to restore */ },+ };+ }++ private getOrCreateRuntime(botId: string, manifest: BotManifest): { registry: CapabilityRegistry; tools: Record<string, Tool> } {+ const cached = this.registries.get(botId);+ if (cached) return cached;+ const registry = createBotCapabilityRegistry({+ botId,+ manifest,+ botDir: this.store.botDir(botId),+ permissions: this.store.readPermissions(botId),+ userMemory: this.userMemoryFor(botId, manifest),+ config: this.config,+ });+ const tools: Record<string, Tool> = { ...registry.getTools() };+ // bot_send is added per bot, scoped to its configured roster.+ if ((manifest.comms?.canMessage ?? []).length > 0) {+ tools.bot_send = createBotSendTool(this, botId, manifest.comms?.canMessage ?? []);+ }+ const filtered = filterBotTools(tools, manifest);+ this.registries.set(botId, { registry, tools: filtered });+ return { registry, tools: filtered };+ }++ invalidateRuntime(botId: string): void {+ this.registries.delete(botId);+ }++ /**+ * Register every enabled bot's cron routines with the main Scheduler+ * (manifest id `bot:<botId>:<name>`). Bot runs fire on the cron lane and+ * route to the bot lane, never through Agent.processQueue. Idempotent:+ * the Scheduler replaces existing tasks by id.+ */+ registerRoutines(scheduler: { addPersistedTask(m: any): void }): void {+ let count = 0;+ for (const manifest of this.store.list()) {+ if (!manifest.enabled) continue;+ for (const routine of manifest.schedules ?? []) {+ if (!isValidCronExpression(routine.cron)) {+ logger.warn({ botId: manifest.id, cron: routine.cron }, 'Invalid cron expression — routine skipped');+ continue;+ }+ scheduler.addPersistedTask({+ id: `bot:${manifest.id}:${routine.name}`,+ cron: routine.cron,+ description: routine.name,+ prompt: routine.prompt,+ botId: manifest.id,+ createdAt: new Date().toISOString(),+ });+ count++;+ }+ }+ if (count > 0) {+ logger.info({ routines: count }, 'Bot routines registered');+ }+ }++ // ---- control plane -------------------------------------------------------++ async halt(botId: string, jobId?: string): Promise<boolean> {+ const running = this.running.get(botId);+ if (!running || running.size === 0) return false;+ for (const id of running) {+ if (jobId && id !== jobId) continue;+ this.aborts.get(`${botId}:${id}`)?.abort();+ }+ this.queues.set(botId, jobId ? (this.queues.get(botId) ?? []).filter(j => j.id !== jobId) : []);+ return true;+ }++ async haltAll(): Promise<void> {+ for (const [botId] of this.running) {+ await this.halt(botId);+ }+ }++ setEnabled(botId: string, enabled: boolean): void {+ if (enabled) {+ this.disabled.delete(botId);+ this.store.setEnabled(botId, true);+ this.pump(botId);+ } else {+ this.disabled.add(botId);+ void this.halt(botId);+ this.store.setEnabled(botId, false);+ }+ this.invalidateRuntime(botId);+ }++ // ---- observation ---------------------------------------------------------++ getStatusSummaries(): BotStatusSummary[] {+ return this.store.list().map((m) => {+ const running = this.running.get(m.id);+ const queue = this.queues.get(m.id) ?? [];+ const last = this.lastRun.get(m.id);+ let state: BotLiveState = 'idle';+ if (!m.enabled || this.disabled.has(m.id)) state = 'disabled';+ else if (this.pausedForBudget.has(m.id)) state = 'paused';+ else if ((running?.size ?? 0) > 0) state = 'running';+ else if (queue.length > 0) state = 'queued';+ return {+ id: m.id,+ name: m.name,+ enabled: m.enabled,+ state,+ activity: this.activity.get(m.id),+ lastRunAt: last?.at,+ lastRunState: last?.state,+ needsYou: this.needsYou.has(m.id),+ };+ });+ }++ getJournal(botId: string, limit = 20): BotRunRecord[] {+ return this.journalFor(botId).read(botId, limit);+ }++ getStorage(): Array<{ id: string; bytes: number; journalBytes: number }> {+ return this.store.usage();+ }++ getQueuedCount(botId: string): number {+ return (this.queues.get(botId) ?? []).length;+ }+}++function resolveProvider(providers: ProviderRegistry, manifest: BotManifest) {+ const requested = manifest.model?.provider;+ const provider = requested ? providers.get(requested) : undefined;+ if (provider) return provider;+ if (requested) {+ logger.warn({ botId: manifest.id, requested }, 'Bot provider not registered — falling back to default');+ }+ return providers.getDefault();+}++function describeJob(job: BotJob): string {+ switch (job.trigger) {+ case 'chat': return job.prompt ? `Responding: ${job.prompt.slice(0, 60)}` : 'Responding';+ case 'mailbox': return job.fromBot ? `Handling message from ${job.fromBot}` : 'Handling mailbox';+ case 'cron': return `Scheduled routine: ${job.prompt.slice(0, 60)}`;+ default: return `Handling ${job.trigger} request`;+ }+}++// Re-exported for the /bots storage view.+export { BOT_JOURNAL_FILENAME };\ No newline at end of filediff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.tsnew file mode 100644index 00000000..b94666da--- /dev/null+++ b/src/bots/bot-turn.ts@@ -0,0 +1,223 @@+import { generateText, stepCountIs } from 'ai';+import type { Tool } from 'ai';+import type { CapabilityRegistry } from '../capabilities/registry.js';+import type { UserMemoryStore } from '../memory/user-memory.js';+import type { TokenBudget } from '../utils/tokens.js';+import type { BaseProvider } from '../providers/base.js';+import { classifyStreamCompletion } from '../core/stream-completion.js';+import { logger } from '../utils/logger.js';+import type { BotManifest, BotTrigger } from './types.js';++/** Mailbox messages injected mid-turn (bot-to-bot or queued user input). */+export interface BotTurnMail {+ from: string;+ content: string;+}++export interface BotTurnInput {+ manifest: BotManifest;+ trigger: BotTrigger;+ prompt: string;+ persona: string;+ /** Pending mailbox messages at turn start (attributed bot-to-bot handoffs). */+ mail: BotTurnMail[];+ /** Callback checked between rounds for newly arrived mailbox messages. */+ pollMail: () => BotTurnMail[];+ capabilities: CapabilityRegistry;+ tools: Record<string, Tool>;+ userMemory: UserMemoryStore | null;+ provider: BaseProvider;+ tokenBudget: TokenBudget;+ abortSignal: AbortSignal;+}++export interface BotTurnOutput {+ status: 'completed' | 'failed' | 'halted' | 'paused';+ output: string;+ tokensIn: number;+ tokensOut: number;+ error?: string;+ reasonCode?: string;+}++const MAX_STEPS_DEFAULT = 25;++/**+ * One run of one bot: a fresh-context tool loop over the bot's own provider,+ * persona, toolset, memory namespace, and fail-closed permission manager.+ * Structurally mirrors SubAgent.run() minus the shared-registry hazards:+ * every dependency here is already per-bot.+ */+export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {+ const { manifest, provider, capabilities, tools, tokenBudget, abortSignal } = input;+ const maxSteps = manifest.autonomy?.maxSteps ?? MAX_STEPS_DEFAULT;++ const system = buildBotSystemPrompt(input);+ const messages: any[] = [];++ for (const m of input.mail) {+ messages.push({ role: 'user', content: `Message from 🤖 ${m.from}:\n\n${m.content}` });+ }+ if (input.prompt) {+ messages.push({ role: 'user', content: input.prompt });+ }+ if (messages.length === 0) {+ messages.push({ role: 'user', content: 'You have no specific task. Check your inbox and report your status.' });+ }++ let tokensIn = 0;+ let tokensOut = 0;+ let lastResult: any = null;+ let stepsRemaining = maxSteps;++ try {+ while (stepsRemaining > 0 && !abortSignal.aborted) {+ const result = await generateText({+ model: provider.getModelInstance(),+ system,+ messages,+ tools,+ stopWhen: stepCountIs(stepsRemaining),+ abortSignal,+ experimental_include: { requestBody: false, responseBody: false },+ onStepFinish: ({ usage }) => {+ if (abortSignal.aborted) return;+ stepsRemaining--;+ if (usage) {+ tokensIn += usage.inputTokens ?? 0;+ tokensOut += usage.outputTokens ?? 0;+ }+ },+ });+ lastResult = result;++ const completion = classifyStreamCompletion({+ finishReason: (result as any)?.finishReason,+ hasText: Boolean(result?.text),+ hasToolCalls: true,+ });+ if (completion === 'interrupted') {+ throw new Error('Generation was interrupted before completion (no finish signal from provider)');+ }++ if (result.text) {+ messages.push({ role: 'assistant', content: result.text });+ }++ // Consume newly arrived mailbox messages before finishing, so a+ // handoff delivered mid-turn is not lost to the next scheduling gap.+ if (!abortSignal.aborted && stepsRemaining > 0) {+ const fresh = input.pollMail();+ if (fresh.length > 0) {+ for (const m of fresh) {+ messages.push({ role: 'user', content: `Message from 🤖 ${m.from}:\n\n${m.content}` });+ }+ continue;+ }+ }+ break;+ }++ if (abortSignal.aborted) {+ return { status: 'halted', output: 'Turn was halted.', tokensIn, tokensOut };+ }++ // Step budget exhausted with tool calls still pending — pause, never+ // report success on half-done work (sub-agent completion contract).+ if (stepsRemaining <= 0 && (lastResult as any)?.finishReason === 'tool-calls') {+ return {+ status: 'paused',+ output: 'Step budget reached before the turn completed — remaining work continues next turn.',+ tokensIn,+ tokensOut,+ reasonCode: 'step_budget',+ };+ }++ const output = (lastResult?.text || '').trim() || '(no text response)';++ tokenBudget.recordUsage({+ provider: provider.name,+ model: provider.getModel(),+ inputTokens: tokensIn,+ outputTokens: tokensOut,+ totalTokens: tokensIn + tokensOut,+ channelType: 'bot',+ });++ return { status: 'completed', output, tokensIn, tokensOut };+ } catch (err: any) {+ if (abortSignal.aborted) {+ return { status: 'halted', output: 'Turn was halted.', tokensIn, tokensOut };+ }+ return {+ status: 'failed',+ output: `Turn failed: ${err?.message ?? String(err)}`,+ tokensIn,+ tokensOut,+ error: err?.message ?? String(err),+ reasonCode: classifyFailure(err),+ };+ }+}++/** Map a provider/tool error to a typed reason code (retry vs permanent). */+export function classifyFailure(err: any): string {+ const msg = String(err?.message ?? err ?? '').toLowerCase();+ if (/rate.?limit|429|too many requests/.test(msg)) return 'provider_rate_limit';+ if (/timeout|etimedout|econnaborted|socket hang up/.test(msg)) return 'provider_timeout';+ if (/permission denied|blocked command|no permission/.test(msg)) return 'permission_denied';+ if (/api key|unauthorized|401|authentication/.test(msg)) return 'provider_auth';+ if (/quota|billing|402/.test(msg)) return 'provider_quota';+ if (/context|maximum.*tokens|too long/.test(msg)) return 'context_overflow';+ return 'unknown_error';+}++/** Transient failures may retry; permanent ones go straight to the DLQ. */+export function isTransientFailure(reasonCode: string): boolean {+ return reasonCode === 'provider_rate_limit' || reasonCode === 'provider_timeout';+}++function buildBotSystemPrompt(input: BotTurnInput): string {+ const { manifest } = input;+ let prompt = `You are "${manifest.name}", a Mercury bot (id: ${manifest.id}).\n`;+ if (manifest.description) {+ prompt += `Role: ${manifest.description}\n`;+ }+ prompt += '\n';+ prompt += input.persona;++ // Scoped memory injection — mirrors the main agent's injection site, but+ // into the bot's own namespace (scope own/shared-read; scope none = null).+ if (input.userMemory) {+ try {+ const query = input.mail.map(m => m.content).join(' ') || input.prompt;+ const relevant = input.userMemory.retrieveRelevant(query, { maxRecords: 5, maxChars: 900 });+ if (relevant?.context) {+ prompt += `\n\n[Bot memory — auto-retrieved context]\n${relevant.context}`;+ }+ } catch (err: any) {+ logger.warn({ botId: manifest.id, err: err?.message }, 'Bot memory retrieval failed — continuing without');+ }+ }++ prompt += `\n\nOperating rules:+- You run unattended: NEVER ask the user questions or wait for confirmation. If a required input is missing, state the assumption you are proceeding with.+- Actions you lack permission for are denied automatically (fail-closed). Do not attempt workarounds; report what you could not do.+- Stay in your specialty; say so plainly when a request falls outside it.`;++ const roster = manifest.comms?.canMessage ?? [];+ if (roster.length > 0) {+ prompt += `\n\nBots you can message via bot_send: ${roster.join(', ')}.`;+ }++ const toolNames = Object.keys(input.tools);+ if (toolNames.length > 0) {+ prompt += `\n\nAvailable tools: ${toolNames.join(', ')}`;+ }++ const remaining = input.tokenBudget.getRemaining();+ prompt += `\n\nToken budget remaining: ${remaining}`;++ return prompt;+}\ No newline at end of filediff --git a/src/bots/journal.ts b/src/bots/journal.tsnew file mode 100644index 00000000..e4433f37--- /dev/null+++ b/src/bots/journal.ts@@ -0,0 +1,99 @@+import { appendFileSync, existsSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { BOT_JOURNAL_FILENAME, assertValidBotId } from './store.js';+import type { BotRunRecord } from './types.js';++/**+ * Append-only per-bot run journal — the permanent compact record of every+ * run (one line per run; bulky transcripts are evicted separately, see+ * BOTS-ARCHITECTURE.md §2.10). Rotates at a byte threshold, keeping a fixed+ * number of rotations, so a bot running for years is bounded in size.+ */+export class BotJournal {+ private readonly dir: string;+ private readonly rotateBytes: number;+ private readonly keepRotations: number;++ constructor(dir: string, rotateBytes = 5 * 1024 * 1024, keepRotations = 3) {+ this.dir = dir;+ this.rotateBytes = rotateBytes;+ this.keepRotations = keepRotations;+ }++ append(record: BotRunRecord): void {+ assertValidBotId(record.botId);+ this.rotateIfNeeded();+ try {+ appendFileSync(join(this.dir, BOT_JOURNAL_FILENAME), JSON.stringify(record) + '\n', 'utf-8');+ } catch (err: any) {+ // Journaling must never break a run — the queue/state carries the outcome.+ console.error(`[bots] journal append failed for ${record.botId}: ${err?.message}`);+ }+ }++ /** Most recent records, newest last. */+ read(botId: string, limit = 20): BotRunRecord[] {+ assertValidBotId(botId);+ const file = join(this.dir, BOT_JOURNAL_FILENAME);+ if (!existsSync(file)) return [];+ const lines = readLines(file);+ return lines.slice(-limit);+ }++ counts(botId: string): { total: number; completed: number; failed: number; bytes: number } {+ assertValidBotId(botId);+ const file = join(this.dir, BOT_JOURNAL_FILENAME);+ const files = [file, ...rotationFiles(this.dir, this.keepRotations)];+ let total = 0, completed = 0, failed = 0, bytes = 0;+ for (const f of files) {+ if (!existsSync(f)) continue;+ bytes += statSync(f).size;+ for (const rec of readLines(f)) {+ total++;+ if (rec.state === 'completed') completed++;+ if (rec.state === 'failed') failed++;+ }+ }+ return { total, completed, failed, bytes };+ }++ private rotateIfNeeded(): void {+ const file = join(this.dir, BOT_JOURNAL_FILENAME);+ if (!existsSync(file) || statSync(file).size < this.rotateBytes) return;+ // Drop the oldest rotation first, then shift: .N-1→.N, …, journal→.1+ const oldest = join(this.dir, `${BOT_JOURNAL_FILENAME}.${this.keepRotations}`);+ if (existsSync(oldest)) rmSync(oldest);+ for (let i = this.keepRotations - 1; i >= 1; i--) {+ const from = join(this.dir, `${BOT_JOURNAL_FILENAME}.${i}`);+ const to = join(this.dir, `${BOT_JOURNAL_FILENAME}.${i + 1}`);+ if (existsSync(from)) renameSync(from, to);+ }+ renameSync(file, join(this.dir, `${BOT_JOURNAL_FILENAME}.1`));+ }+}++function readLines(file: string): BotRunRecord[] {+ const out: BotRunRecord[] = [];+ try {+ const content = statSync(file).size > 0 ? readFileSync(file, 'utf-8') : '';+ for (const line of content.split('\n')) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ try {+ out.push(JSON.parse(trimmed) as BotRunRecord);+ } catch { /* skip corrupt line — never break reads on one bad row */ }+ }+ } catch { /* missing/unreadable file = empty journal */ }+ return out;+}++function rotationFiles(dir: string, keep: number): string[] {+ const out: string[] = [];+ try {+ for (const name of readdirSync(dir)) {+ const match = /^journal\.jsonl\.(\d+)$/.exec(name);+ if (match && parseInt(match[1], 10) <= keep) out.push(join(dir, name));+ }+ } catch { /* no dir yet */ }+ return out;+}\ No newline at end of filediff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.tsnew file mode 100644index 00000000..e19b5140--- /dev/null+++ b/src/bots/registry-factory.ts@@ -0,0 +1,114 @@+import { homedir } from 'node:os';+import { resolve } from 'node:path';+import { CapabilityRegistry } from '../capabilities/registry.js';+import type { UserMemoryStore } from '../memory/user-memory.js';+import type { MercuryConfig } from '../utils/config.js';+import { logger } from '../utils/logger.js';+import type { BotManifest, BotPermissionsFile, BotPathScope } from './types.js';++/**+ * Tools a bot must never see, regardless of manifest. These are the tools+ * that prompt the user (bots run unattended), mutate the global permission+ * manifest, delegate to sub-agents, or manage schedules:+ */+const ALWAYS_STRIPPED = new Set([+ 'ask_user', // bots never ask questions mid-run+ 'approve_scope', // would persist scopes into the GLOBAL permissions.yaml+ 'approve_command', // same global-state mutation hazard+ 'update_plan', // plan UI has no bot surface+ 'delegate_task', // bots do not spawn sub-agents in P0+ 'list_agents',+ 'stop_agent',+ 'install_skill', // no skill installs from an unattended bot+ 'schedule_task', // bot schedules are managed via bot.yaml, not tools+ 'list_scheduled_tasks',+ 'cancel_scheduled_task',+ 'send_message', // channel messaging belongs to the owning surfaces+ 'send_file',+ 'bot_send', // replaced by the bot-scoped instance after filtering+]);++export interface BotRegistryDeps {+ botId: string;+ manifest: BotManifest;+ botDir: string;+ permissions: BotPermissionsFile;+ config: MercuryConfig;+ /** Per-bot memory store (P0-5); null until memory scoping is wired. */+ userMemory?: UserMemoryStore | null;+}++/**+ * Build a bot's own CapabilityRegistry + filtered toolset.+ *+ * Isolation model (BOTS-ARCHITECTURE.md §2.5):+ * - own PermissionManager instance — no shared mutable cwd/channel swapping+ * - NO ask handler: every approval path fails closed (auto-deny)+ * - channel type 'bot' — never 'internal' (internal auto-approves)+ * - shell auto-approve list emptied; safe-read classifier still applies+ * - no persistent-manifest writes: interactive mutation tools are stripped+ */+export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRegistry {+ const registry = new CapabilityRegistry();+ const pm = registry.permissions;++ // Reshape the manifest in place (never call save() — that writes the+ // global ~/.mercury/permissions.yaml, and bots have no path to it).+ const manifest = pm.getManifest();+ manifest.capabilities.filesystem.scopes = buildBotScopes(deps.permissions.paths, deps.botDir);+ manifest.capabilities.shell.autoApproved = [];+ manifest.capabilities.shell.blocked = [+ ...new Set([...manifest.capabilities.shell.blocked, ...(deps.permissions.blockedCommands ?? [])]),+ ];++ // Fail-closed core: no ask handler, no allow-all, non-internal context.+ // Granted scopes apply without prompting; everything else denies.+ pm.setAutoApproveAll(false);+ pm.setFailClosed(true);+ pm.setCurrentContext('bot', deps.botId);++ registry.setCwd(process.cwd());+ registry.registerAll();++ const tools = filterBotTools(registry.getTools(), deps.manifest);+ logger.info(+ { botId: deps.botId, tools: Object.keys(tools).length, scopes: manifest.capabilities.filesystem.scopes.length },+ 'Bot capability registry built (fail-closed, isolated)',+ );+ return registry;+}++/**+ * Tool-set filter: interactive/global-mutation tools always stripped, then+ * the manifest's allow/deny applied (deny wins; a non-empty allow restricts+ * the toolset to exactly that list).+ */+export function filterBotTools(all: Record<string, any>, manifest: BotManifest): Record<string, any> {+ const allow = manifest.tools?.allow ?? [];+ const deny = new Set(manifest.tools?.deny ?? []);+ const out: Record<string, any> = {};+ for (const [name, tool] of Object.entries(all)) {+ if (ALWAYS_STRIPPED.has(name)) continue;+ if (deny.has(name)) continue;+ if (allow.length > 0 && !allow.includes(name)) continue;+ out[name] = tool;+ }+ return out;+}++/**+ * Bot path scopes from permissions.yaml. 'self' resolves to the bot's own+ * profile dir; everything else resolves against cwd or home (~). An+ * unconfigured bot gets NO filesystem access (fail-closed) — but the store+ * always writes a default self scope at creation.+ */+function buildBotScopes(paths: BotPathScope[] | undefined, botDir: string): Array<{ path: string; read: boolean; write: boolean }> {+ const scopes: Array<{ path: string; read: boolean; write: boolean }> = [];+ for (const p of paths ?? []) {+ const resolved = p.scope === 'self'+ ? resolve(botDir)+ : resolve(p.scope.replace(/^~/, homedir()));+ scopes.push({ path: resolved, read: p.read ?? false, write: p.write ?? false });+ }+ return scopes;+}\ No newline at end of filediff --git a/src/bots/store.test.ts b/src/bots/store.test.tsnew file mode 100644index 00000000..41bb4ef4--- /dev/null+++ b/src/bots/store.test.ts@@ -0,0 +1,263 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { BotStore, assertValidBotId, validateBotManifest, BOT_PERSONA_FILENAME, BOT_PERMISSIONS_FILENAME } from './store.js';+import { BotJournal } from './journal.js';+import type { BotManifest } from './types.js';++describe('bot id validation', () => {+ it('accepts lowercase ids with dashes', () => {+ expect(() => assertValidBotId('researcher')).not.toThrow();+ expect(() => assertValidBotId('a1')).not.toThrow();+ expect(() => assertValidBotId('social-media')).not.toThrow();+ });++ it('rejects traversal, case, and oversized ids', () => {+ expect(() => assertValidBotId('../etc')).toThrow();+ expect(() => assertValidBotId('..')).toThrow();+ expect(() => assertValidBotId('Researcher')).toThrow();+ expect(() => assertValidBotId('a'.repeat(49))).toThrow();+ expect(() => assertValidBotId('')).toThrow();+ });+});++describe('BotStore', () => {+ let root: string;+ let store: BotStore;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bots-'));+ store = new BotStore(root);+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('creates a profile dir with manifest, persona, and fail-closed permissions', () => {+ const m = store.create({ id: 'researcher', name: 'Research', description: 'Deep research' });+ expect(m.id).toBe('researcher');+ expect(m.enabled).toBe(true);+ expect(existsSync(join(root, 'researcher', 'bot.yaml'))).toBe(true);+ expect(existsSync(join(root, 'researcher', BOT_PERSONA_FILENAME))).toBe(true);+ const perms = store.readPermissions('researcher');+ expect(perms.paths).toEqual([{ scope: 'self', read: true, write: true }]);+ const persona = store.readPersona('researcher');+ expect(persona).toContain('# Research');+ });++ it('rejects duplicate ids and invalid ids', () => {+ store.create({ id: 'alpha', name: 'Alpha' });+ expect(() => store.create({ id: 'alpha', name: 'Alpha 2' })).toThrow(/already exists/);+ expect(() => store.create({ id: '../escape', name: 'Bad' })).toThrow();+ expect(() => store.create({ id: '', name: 'Bad' })).toThrow();+ });++ it('lists created bots sorted by id', () => {+ store.create({ id: 'zeta', name: 'Zeta' });+ store.create({ id: 'alpha', name: 'Alpha' });+ const ids = store.list().map(m => m.id);+ expect(ids).toEqual(['alpha', 'zeta']);+ });++ it('round-trips manifest fields through YAML', () => {+ store.create({+ id: 'researcher',+ name: 'Research',+ manifest: {+ model: { provider: 'anthropic', model: 'claude-sonnet-5' },+ memory: { scope: 'shared-read', allowCrossBotRecall: ['publisher'] },+ comms: { canMessage: ['publisher'] },+ schedules: [{ name: 'morning-scan', cron: '0 9 * * *', prompt: 'Scan RSS' }],+ autonomy: { maxSteps: 30, dailyTokenBudget: 1000 },+ },+ });+ const loaded = store.get('researcher') as BotManifest;+ expect(loaded.model?.provider).toBe('anthropic');+ expect(loaded.model?.model).toBe('claude-sonnet-5');+ expect(loaded.memory?.scope).toBe('shared-read');+ expect(loaded.memory?.allowCrossBotRecall).toEqual(['publisher']);+ expect(loaded.comms?.canMessage).toEqual(['publisher']);+ expect(loaded.schedules?.[0].cron).toBe('0 9 * * *');+ expect(loaded.autonomy?.dailyTokenBudget).toBe(1000);+ });++ it('normalizes dangerous tools to deny-by-default when no allow list is set', () => {+ store.create({ id: 'writer', name: 'Writer' });+ const m = store.get('writer') as BotManifest;+ expect(m.tools?.deny).toContain('run_command');+ expect(m.tools?.deny).toContain('delete_file');+ // An explicit allow list opts in deliberately: with a non-empty allow,+ // only listed tools are available anyway, so deny stays exactly as written.+ store.create({ id: 'publisher', name: 'Publisher', manifest: { tools: { allow: ['read_file', 'shell'], deny: ['shell'] } } });+ const p = store.get('publisher') as BotManifest;+ expect(p.tools?.deny).toEqual(['shell']);+ expect(p.tools?.allow).toEqual(['read_file', 'shell']);+ });++ it('update mutates and persists', () => {+ store.create({ id: 'alpha', name: 'Alpha', manifest: { enabled: true } });+ const updated = store.update('alpha', m => { m.enabled = false; m.description = 'paused'; });+ expect(updated.enabled).toBe(false);+ expect((store.get('alpha') as BotManifest).enabled).toBe(false);+ expect((store.get('alpha') as BotManifest).updatedAt).not.toBe((store.get('alpha') as BotManifest).createdAt);+ });++ it('setEnabled flips enabled', () => {+ store.create({ id: 'alpha', name: 'Alpha' });+ store.setEnabled('alpha', false);+ expect((store.get('alpha') as BotManifest).enabled).toBe(false);+ });++ it('delete removes the profile dir entirely', () => {+ store.create({ id: 'alpha', name: 'Alpha' });+ expect(store.exists('alpha')).toBe(true);+ store.delete('alpha');+ expect(store.exists('alpha')).toBe(false);+ expect(existsSync(join(root, 'alpha'))).toBe(false);+ });++ it('skips malformed profile dirs on list instead of throwing', () => {+ store.create({ id: 'alpha', name: 'Alpha' });+ mkdirSync(join(root, 'broken'), { recursive: true });+ writeFileSync(join(root, 'broken', 'bot.yaml'), 'id: other\nname: Mismatch', 'utf-8');+ const ids = store.list().map(m => m.id);+ expect(ids).toEqual(['alpha']);+ });++ it('get rejects a manifest whose id does not match its directory', () => {+ const dir = join(root, 'researcher');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'bot.yaml'), 'id: other\nname: Spoof', 'utf-8');+ expect(() => store.get('researcher')).toThrow(/mismatched id/);+ });++ it('rejects manifests with invalid schedules or self-referencing links', () => {+ const errors = validateBotManifest({+ id: 'x',+ name: 'X',+ schedules: [{ name: 'bad', cron: 'every morning', prompt: 'go' }],+ memory: { scope: 'shared-read', allowCrossBotRecall: ['x'] },+ comms: { canMessage: ['x'] },+ });+ expect(errors.some(e => e.includes('cron'))).toBe(true);+ expect(errors.some(e => e.includes('allowCrossBotRecall'))).toBe(true);+ expect(errors.some(e => e.includes('canMessage'))).toBe(true);+ });++ it('validates cross-bot references against other bot ids only structurally', () => {+ const errors = validateBotManifest({ id: 'x', name: 'X', comms: { canMessage: ['valid-id'] } });+ expect(errors).toEqual([]);+ });++ it('usage reports per-bot byte sizes', () => {+ store.create({ id: 'alpha', name: 'Alpha', persona: 'x'.repeat(2048) });+ const usage = store.usage();+ expect(usage).toHaveLength(1);+ expect(usage[0].id).toBe('alpha');+ expect(usage[0].bytes).toBeGreaterThan(0);+ });++ it('persona can be rewritten', () => {+ store.create({ id: 'alpha', name: 'Alpha' });+ store.writePersona('alpha', '# New persona');+ expect(store.readPersona('alpha')).toBe('# New persona');+ });++ it('permissions round-trip through YAML', () => {+ store.create({ id: 'alpha', name: 'Alpha' });+ store.writePermissions('alpha', {+ paths: [{ scope: './work', read: true, write: true }],+ blockedCommands: ['rm -rf'],+ });+ const perms = store.readPermissions('alpha');+ expect(perms.paths?.[0].scope).toBe('./work');+ expect(perms.blockedCommands).toEqual(['rm -rf']);+ });+});++describe('BotJournal', () => {+ let root: string;+ let dir: string;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-journal-'));+ dir = join(root, 'researcher');+ mkdirSync(dir, { recursive: true });+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ const record = (runId: string, state: 'completed' | 'failed' = 'completed') => ({+ runId,+ botId: 'alpha',+ trigger: 'cron' as const,+ state,+ startedAt: Date.now(),+ durationMs: 100,+ tokensIn: 10,+ tokensOut: 20,+ });++ it('appends and reads records newest-last', () => {+ const journal = new BotJournal(dir);+ journal.append(record('r1'));+ journal.append(record('r2'));+ const recent = journal.read('alpha');+ expect(recent.map(r => r.runId)).toEqual(['r1', 'r2']);+ });++ it('read with limit returns the most recent window', () => {+ const journal = new BotJournal(dir);+ for (let i = 0; i < 5; i++) journal.append(record(`r${i}`));+ expect(journal.read('alpha', 2).map(r => r.runId)).toEqual(['r3', 'r4']);+ });++ it('counts states across rotations', () => {+ const journal = new BotJournal(dir);+ journal.append(record('r1'));+ journal.append(record('r2', 'failed'));+ const counts = journal.counts('alpha');+ expect(counts.total).toBe(2);+ expect(counts.completed).toBe(1);+ expect(counts.failed).toBe(1);+ expect(counts.bytes).toBeGreaterThan(0);+ });++ it('rotates at the byte threshold and keeps only N rotations', () => {+ const journal = new BotJournal(dir, 200, 2);+ // Each record is ~200 bytes; enough appends to force multiple rotations.+ for (let i = 0; i < 10; i++) journal.append(record(`r${i}`));+ expect(existsSync(join(dir, 'journal.jsonl'))).toBe(true);+ expect(existsSync(join(dir, 'journal.jsonl.1'))).toBe(true);+ // keepRotations=2 means at most .1 and .2 exist — the bounded window.+ expect(existsSync(join(dir, 'journal.jsonl.3'))).toBe(false);+ const counts = journal.counts('alpha');+ // Bounded: the retained history is at most (1 + keepRotations) rotations+ // worth of records, not all 10 — oldest records are evicted by design.+ expect(counts.total).toBeGreaterThanOrEqual(2);+ expect(counts.total).toBeLessThanOrEqual(6);+ // Each rotation is at most the threshold plus one record overshoot.+ expect(counts.bytes).toBeLessThan((1 + 2) * 200 + 6 * 300);+ });++ it('returns empty for an unknown bot dir without throwing', () => {+ const journal = new BotJournal(dir);+ expect(journal.read('nonexistent')).toEqual([]);+ expect(journal.counts('nonexistent').total).toBe(0);+ });++ it('skips corrupt lines instead of failing reads', () => {+ const journal = new BotJournal(dir);+ journal.append(record('r1'));+ const file = join(dir, 'journal.jsonl');+ const existing = readFileSync(file, 'utf-8');+ writeFileSync(file, existing + '{corrupt\n' + existing, 'utf-8');+ const recent = journal.read('alpha', 10);+ expect(recent.every(r => r.runId)).toBe(true);+ expect(recent).toHaveLength(2);+ });+});\ No newline at end of filediff --git a/src/bots/store.ts b/src/bots/store.tsnew file mode 100644index 00000000..086f2712--- /dev/null+++ b/src/bots/store.ts@@ -0,0 +1,315 @@+import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { join, resolve, sep } from 'node:path';+import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';+import { getMercuryHome } from '../utils/config.js';+import { logger } from '../utils/logger.js';+import type {+ BotManifest,+ BotPermissionsFile,+} from './types.js';++export const BOT_MANIFEST_FILENAME = 'bot.yaml';+export const BOT_PERSONA_FILENAME = 'persona.md';+export const BOT_PERMISSIONS_FILENAME = 'permissions.yaml';+export const BOT_ENV_FILENAME = '.env';+export const BOT_JOURNAL_FILENAME = 'journal.jsonl';++/** Lowercase alphanumeric ids — same discipline as skill ids (traversal guard). */+const BOT_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,47}$/;++/** Tools that are deny-by-default for every bot unless explicitly allowed. */+export const BOT_DANGEROUS_TOOLS = [+ 'run_command',+ 'write_file',+ 'edit_file',+ 'create_file',+ 'delete_file',+ 'git_commit',+ 'git_push',+] as const;++export function assertValidBotId(id: string): void {+ if (!BOT_ID_PATTERN.test(id)) {+ throw new Error(`Invalid bot id "${id}": must match ${BOT_ID_PATTERN.source} (lowercase letters, digits, dashes; max 48 chars)`);+ }+}++/**+ * Structural validation of a bot manifest. Returns error strings; an empty+ * array means the manifest is usable. Never throws on user input.+ */+export function validateBotManifest(manifest: Partial<BotManifest>): string[] {+ const errors: string[] = [];+ try {+ assertValidBotId(manifest.id ?? '');+ } catch (err: any) {+ errors.push(err.message);+ }+ if (!manifest.name || typeof manifest.name !== 'string' || manifest.name.trim().length === 0) {+ errors.push('name is required');+ }+ const schedules = manifest.schedules ?? [];+ for (const s of schedules) {+ if (!s.name || !s.prompt) errors.push(`schedule ${s.name || '(unnamed)'}: name and prompt are required`);+ if (!isValidCronExpression(s.cron ?? '')) {+ errors.push(`schedule ${s.name || '(unnamed)'}: "${s.cron}" is not a 5-field cron expression`);+ }+ }+ const crossRecall = manifest.memory?.allowCrossBotRecall ?? [];+ for (const other of crossRecall) {+ if (other === manifest.id) errors.push('allowCrossBotRecall cannot include the bot itself');+ }+ const canMessage = manifest.comms?.canMessage ?? [];+ for (const other of canMessage) {+ if (other === manifest.id) errors.push('canMessage cannot include the bot itself');+ }+ return errors;+}++export function isValidCronExpression(expr: string): boolean {+ if (typeof expr !== 'string') return false;+ const fields = expr.trim().split(/\s+/);+ return fields.length === 5 && fields.every(f => f.length > 0);+}++export interface CreateBotInput {+ id: string;+ name: string;+ description?: string;+ /** Persona markdown; omit to write the template. */+ persona?: string;+ manifest?: Partial<Omit<BotManifest, 'id' | 'name' | 'createdAt' | 'updatedAt'>>;+}++const DEFAULT_PERSONA_TEMPLATE = (name: string, description?: string) =>+`# ${name}++${description || 'A Mercury bot — a focused specialist.'}++## Character++You are ${name}. Stay in character at all times. You are a specialist:+stay inside your domain of expertise, and say so plainly when a request+falls outside it.++## Standing instructions++- Be concise and concrete; prefer decisions over deliberation.+- You never ask the user questions mid-run: if a required input is missing,+ state the assumption you are proceeding with.+- If you lack permission for an action, stop and report it in your summary+ instead of attempting a workaround.++## Output++- Lead with the outcome, then the details.+- Include the evidence (links, file paths, numbers) behind each claim.+`;++function atomicWrite(filePath: string, content: string, mode: number = 0o600): void {+ const tmp = `${filePath}.tmp-${process.pid}`;+ writeFileSync(tmp, content, { encoding: 'utf-8', mode });+ renameSync(tmp, filePath);+}++/**+ * Filesystem store for bot profiles: `~/.mercury/bots/<id>/`.+ * Mirrors SkillStore's dependency-injected-root testability and traversal+ * guards, and SessionRepository's atomic tmp+rename writes.+ */+export class BotStore {+ readonly botsRoot: string;++ constructor(botsRoot?: string) {+ this.botsRoot = resolve(botsRoot ?? join(getMercuryHome(), 'bots'));+ }++ /** Bot directory for an id, with traversal guard. Throws on invalid ids. */+ botDir(id: string): string {+ assertValidBotId(id);+ const dir = resolve(this.botsRoot, id);+ const root = resolve(this.botsRoot);+ if (!dir.startsWith(root + sep)) {+ throw new Error(`Invalid bot id "${id}": escapes the bots root`);+ }+ return dir;+ }++ list(): BotManifest[] {+ if (!existsSync(this.botsRoot)) return [];+ const manifests: BotManifest[] = [];+ for (const entry of readdirSync(this.botsRoot, { withFileTypes: true })) {+ if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_')) continue;+ try {+ const m = this.get(entry.name);+ if (m) manifests.push(m);+ } catch (err: any) {+ logger.warn({ botId: entry.name, err: err?.message }, 'Skipping unreadable bot profile');+ }+ }+ return manifests.sort((a, b) => a.id.localeCompare(b.id));+ }++ get(id: string): BotManifest | null {+ const file = join(this.botDir(id), BOT_MANIFEST_FILENAME);+ if (!existsSync(file)) return null;+ const raw = parseYaml(readFileSync(file, 'utf-8')) as Partial<BotManifest>;+ if (!raw || raw.id !== id) {+ throw new Error(`Bot manifest for "${id}" is missing or has a mismatched id`);+ }+ return normalizeBotManifest(raw);+ }++ exists(id: string): boolean {+ try {+ return existsSync(join(this.botDir(id), BOT_MANIFEST_FILENAME));+ } catch {+ return false;+ }+ }++ create(input: CreateBotInput): BotManifest {+ const id = input.id.toLowerCase();+ if (this.exists(id)) {+ throw new Error(`Bot "${id}" already exists`);+ }+ const now = new Date().toISOString();+ const manifest = normalizeBotManifest({+ ...input.manifest,+ id,+ name: input.name,+ description: input.description,+ enabled: input.manifest?.enabled ?? true,+ persona: input.manifest?.persona ?? BOT_PERSONA_FILENAME,+ createdAt: now,+ updatedAt: now,+ } as Partial<BotManifest>);+ const errors = validateBotManifest(manifest);+ if (errors.length > 0) {+ throw new Error(`Invalid bot manifest: ${errors.join('; ')}`);+ }++ const dir = this.botDir(id);+ mkdirSync(dir, { recursive: true });+ this.save(manifest);+ const personaFile = join(dir, manifest.persona ?? BOT_PERSONA_FILENAME);+ if (!existsSync(personaFile)) {+ writeFileSync(personaFile, input.persona ?? DEFAULT_PERSONA_TEMPLATE(input.name, input.description), 'utf-8');+ }+ const permFile = join(dir, BOT_PERMISSIONS_FILENAME);+ if (!existsSync(permFile)) {+ // Fail-closed default: only the bot's own dir, read+write.+ this.writePermissions(id, {+ paths: [{ scope: 'self', read: true, write: true }],+ });+ }+ return manifest;+ }++ save(manifest: BotManifest): void {+ assertValidBotId(manifest.id);+ const dir = this.botDir(manifest.id);+ if (!existsSync(dir)) {+ throw new Error(`Bot "${manifest.id}" does not exist`);+ }+ const errors = validateBotManifest(manifest);+ if (errors.length > 0) {+ throw new Error(`Invalid bot manifest: ${errors.join('; ')}`);+ }+ manifest.updatedAt = new Date().toISOString();+ atomicWrite(join(dir, BOT_MANIFEST_FILENAME), stringifyYaml(manifest));+ }++ update(id: string, mutator: (m: BotManifest) => void): BotManifest {+ const manifest = this.get(id);+ if (!manifest) throw new Error(`Bot "${id}" does not exist`);+ mutator(manifest);+ manifest.updatedAt = new Date().toISOString();+ this.save(manifest);+ return manifest;+ }++ setEnabled(id: string, enabled: boolean): BotManifest {+ return this.update(id, m => { m.enabled = enabled; });+ }++ delete(id: string): void {+ const dir = this.botDir(id);+ if (existsSync(dir)) {+ rmSync(dir, { recursive: true, force: true });+ logger.info({ botId: id }, 'Bot profile deleted');+ }+ }++ readPersona(id: string): string {+ const manifest = this.get(id);+ const personaName = manifest?.persona ?? BOT_PERSONA_FILENAME;+ const file = join(this.botDir(id), personaName);+ return existsSync(file) ? readFileSync(file, 'utf-8') : '';+ }++ writePersona(id: string, content: string): void {+ const manifest = this.get(id);+ const personaName = manifest?.persona ?? BOT_PERSONA_FILENAME;+ atomicWrite(join(this.botDir(id), personaName), content, 0o644);+ }++ readPermissions(id: string): BotPermissionsFile {+ const file = join(this.botDir(id), BOT_PERMISSIONS_FILENAME);+ if (!existsSync(file)) return {};+ return (parseYaml(readFileSync(file, 'utf-8')) ?? {}) as BotPermissionsFile;+ }++ writePermissions(id: string, permissions: BotPermissionsFile): void {+ atomicWrite(join(this.botDir(id), BOT_PERMISSIONS_FILENAME), stringifyYaml(permissions));+ }++ /** Directory sizes for the /bots storage view. */+ usage(): Array<{ id: string; bytes: number; journalBytes: number }> {+ if (!existsSync(this.botsRoot)) return [];+ const out: Array<{ id: string; bytes: number; journalBytes: number }> = [];+ for (const m of this.list()) {+ const dir = this.botDir(m.id);+ out.push({ id: m.id, bytes: treeSize(dir), journalBytes: journalTreeSize(dir) });+ }+ return out;+ }+}++function treeSize(dir: string): number {+ let total = 0;+ try {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const p = join(dir, entry.name);+ if (entry.isDirectory()) total += treeSize(p);+ else total += statSync(p).size;+ }+ } catch { /* unreadable entries count as 0 */ }+ return total;+}++function journalTreeSize(dir: string): number {+ return readdirSync(dir)+ .filter(f => f === 'journal.jsonl' || /^journal\.jsonl\.\d+$/.test(f))+ .reduce((acc, f) => {+ try { return acc + statSync(join(dir, f)).size; } catch { return acc; }+ }, 0);+}++function normalizeBotManifest(raw: Partial<BotManifest>): BotManifest {+ // Normalize deny list: dangerous tools are denied unless explicitly allowed+ // via tools.allow. Deny always wins over allow.+ const allow = raw.tools?.allow ?? [];+ const explicitDeny = raw.tools?.deny ?? [];+ const deny = new Set<string>(explicitDeny);+ if (allow.length === 0) {+ for (const t of BOT_DANGEROUS_TOOLS) deny.add(t);+ }+ return {+ ...raw,+ enabled: raw.enabled ?? false,+ persona: raw.persona ?? BOT_PERSONA_FILENAME,+ memory: { scope: raw.memory?.scope ?? 'own', allowCrossBotRecall: raw.memory?.allowCrossBotRecall },+ tools: { allow, deny: [...deny] },+ } as BotManifest;+}\ No newline at end of filediff --git a/src/bots/tools/bot-send.ts b/src/bots/tools/bot-send.tsnew file mode 100644index 00000000..40af69cd--- /dev/null+++ b/src/bots/tools/bot-send.ts@@ -0,0 +1,34 @@+import { tool, zodSchema } from 'ai';+import { z } from 'zod';+import type { BotManager, BotSendResult } from '../bot-manager.js';++/**+ * bot_send — fire-and-forget mailbox delivery to a linked bot (Hermes'+ * message_agent semantics: attributed, queued behind the target's active+ * turn, never a blocking nested invocation).+ */+export function createBotSendTool(manager: BotManager, senderBotId: string, canMessage: string[]) {+ const roster = canMessage.length > 0 ? canMessage.join(', ') : '(no bots linked)';+ return tool({+ description:+ `Send a message to another Mercury bot. Delivery is queued — the target bot consumes it on its next turn. ` ++ `You may message: ${roster}. Use this to hand off findings, request research, or coordinate.`,+ inputSchema: zodSchema(z.object({+ target: z.string().describe('Bot id to message'),+ message: z.string().min(1).max(20000).describe('Message content — be concrete and self-contained'),+ })),+ execute: async ({ target, message }: { target: string; message: string }) => {+ if (!canMessage.includes(target)) {+ return `Error: you are not configured to message bot "${target}". Linked bots: ${roster}`;+ }+ if (target === senderBotId) {+ return 'Error: you cannot message yourself.';+ }+ const result: BotSendResult = manager.sendToBot(target, senderBotId, message);+ if (!result.accepted) {+ return `Error delivering to ${target}: [reason: ${result.reasonCode}]`;+ }+ return `Queued for ${target} (job ${result.jobId}). Delivery is asynchronous — the bot will consume it on its next turn.`;+ },+ });+}\ No newline at end of filediff --git a/src/bots/types.ts b/src/bots/types.tsnew file mode 100644index 00000000..71189e05--- /dev/null+++ b/src/bots/types.ts@@ -0,0 +1,141 @@+import type { ProviderName } from '../utils/config.js';++/**+ * Mercury Bots — persistent persona-scoped agents (see BOTS-ARCHITECTURE.md).+ *+ * A bot is a profile directory (`~/.mercury/bots/<botId>/`) plus a runtime.+ * This file defines the on-disk manifest types; runtime state lives in+ * bot-manager.ts.+ */++export type BotMemoryScope = 'none' | 'own' | 'shared-read';++export type BotTrigger = 'chat' | 'mailbox' | 'cron' | 'api' | 'cloud' | 'telegram' | 'web';++export type BotRunState = 'completed' | 'failed' | 'halted' | 'paused' | 'denied';++export interface BotModelSelection {+ /** Provider name from the ProviderRegistry; unset = inherit main default. */+ provider?: ProviderName;+ /** Model slug override for the selected provider. */+ model?: string;+}++export interface BotToolAccess {+ /** Tools the bot may use. Empty/undefined = all tools except the deny list. */+ allow?: string[];+ /** Tools the bot must never use. Deny always wins over allow. */+ deny?: string[];+}++export interface BotMemoryConfig {+ /** none = stateless; own = private namespace (default); shared-read = also read listed bots. */+ scope: BotMemoryScope;+ /** Bot ids whose context this bot may search when scope is shared-read. */+ allowCrossBotRecall?: string[];+}++export interface BotCommsConfig {+ /** Bot ids this bot may message. Also injected into its system prompt as its roster. */+ canMessage?: string[];+}++export interface BotScheduleConfig {+ name: string;+ /** 5-field cron expression (node-cron syntax). */+ cron: string;+ prompt: string;+ /** Where the run's output lands. Default 'bot-chat'. */+ deliver?: 'bot-chat' | 'telegram' | 'none';+ /**+ * Cheap pre-check command; if it exits non-zero (nothing changed), the LLM+ * is skipped entirely (Hermes' wakeAgent gate pattern).+ */+ gateScript?: string;+}++export interface BotAutonomyConfig {+ maxConcurrent?: number;+ maxSteps?: number;+ /** Hard daily token cap. Exceeded → the bot pauses until the next day. */+ dailyTokenBudget?: number;+}++export interface BotRetentionConfig {+ transcriptRuns?: number;+ journalRotateBytes?: number;+ journalKeepRotations?: number;+ mailboxTtlHours?: number;+ dlqCap?: number;+ artifactQuotaBytes?: number;+}++/**+ * The machine-readable bot manifest — `~/.mercury/bots/<id>/bot.yaml`.+ * The persona lives in `persona.md`; tool path scopes in `permissions.yaml`.+ */+export interface BotManifest {+ id: string;+ name: string;+ description?: string;+ enabled: boolean;+ /** Persona file name inside the bot dir. Default 'persona.md'. */+ persona?: string;+ model?: BotModelSelection;+ tools?: BotToolAccess;+ memory?: BotMemoryConfig;+ comms?: BotCommsConfig;+ schedules?: BotScheduleConfig[];+ autonomy?: BotAutonomyConfig;+ retention?: BotRetentionConfig;+ createdAt?: string;+ updatedAt?: string;+}++/**+ * Per-bot permission manifest — `~/.mercury/bots/<id>/permissions.yaml`.+ * Deliberately minimal: bots are fail-closed, so only explicit grants exist.+ * There are no auto-approve lists for bots by design (P0-4 wires this into a+ * bot-local PermissionManager).+ */+export interface BotPermissionsFile {+ paths?: BotPathScope[];+ blockedCommands?: string[];+}++export interface BotPathScope {+ /** Directory (relative to cwd, or absolute) the bot may touch. */+ scope: string;+ read?: boolean;+ write?: boolean;+}++/** One journal entry — the permanent compact record of a bot run. */+export interface BotRunRecord {+ runId: string;+ botId: string;+ trigger: BotTrigger;+ state: BotRunState;+ startedAt: number;+ durationMs: number;+ tokensIn: number;+ tokensOut: number;+ summary?: string;+ error?: string;+ /** Typed failure code surfaced to senders/channels (e.g. provider_rate_limit). */+ reasonCode?: string;+}++/** Live bot state surfaced by /bots, the status bar, and the API. */+export type BotLiveState = 'disabled' | 'idle' | 'queued' | 'running' | 'paused';++export interface BotStatusSummary {+ id: string;+ name: string;+ enabled: boolean;+ state: BotLiveState;+ activity?: string;+ lastRunAt?: number;+ lastRunState?: BotRunState;+ needsYou: boolean;+}\ No newline at end of filediff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.tsindex 3ebdc281..27b87698 100644--- a/src/capabilities/permissions.ts+++ b/src/capabilities/permissions.ts@@ -290,6 +290,12 @@ export class PermissionManager {private currentChannelId: string = 'cli';private approvedCommandsByContext = new Map<string, Set<string>>();private approvedWritesByContext = new Map<string, Set<string>>();+ /**+ * Fail-closed mode (unattended agents, e.g. Mercury Bots): no interactive+ * approvals exist. Explicitly granted scopes apply without prompting;+ * everything else denies. Never combined with autoApproveAll.+ */+ private failClosed = false;private tempScopes: FileScope[] = [];@@ -298,6 +304,14 @@ export class PermissionManager {this.manifest = this.load();}+ setFailClosed(value: boolean): void {+ this.failClosed = value;+ }++ isFailClosed(): boolean {+ return this.failClosed;+ }+setCurrentChannelType(type: string): void {this.currentChannelType = type;}@@ -429,6 +443,15 @@ export class PermissionManager {if (tempScope && tempScope.write) return { allowed: true };}+ // Fail-closed mode (bots): the explicitly granted scope IS the approval.+ // No prompting in either direction — in-scope writes run, out-of-scope+ // writes deny, and nothing ever waits for a user who isn't there.+ if (this.failClosed) {+ if (scope && scope.write) return { allowed: true };+ if (tempScope && tempScope.write) return { allowed: true };+ return { allowed: false, reason: `Fail-closed: no granted write scope covers ${path}` };+ }+// Write access in ask-me mode: ALWAYS prompt the user, even if scope existsif (mode === 'write' && !this.isGlobalAutoApproveActive() && this.askHandler && this.currentChannelType !== 'internal') {const scopeAllows = (scope && scope.write) || (tempScope && tempScope.write);diff --git a/src/core/agent.ts b/src/core/agent.tsindex fbc2aef9..3af45a84 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -489,6 +489,7 @@ export class Agent {private completedStepCount = 0;private stepNarrative: import('../utils/tool-label.js').NarrativeStep[] = [];private supervisor?: import('../core/supervisor.js').SubAgentSupervisor;+ private botManager?: import('../bots/bot-manager.js').BotManager;readonly programmingMode: ProgrammingMode;readonly researchMode: ResearchMode;readonly saverMode: SaverMode;@@ -558,6 +559,21 @@ export class Agent {}}+ /** Wire the Mercury Bots runtime (see bots/bot-manager.ts, BOTS-ARCHITECTURE.md). */+ setBotManager(botManager: import('../bots/bot-manager.js').BotManager): void {+ this.botManager = botManager;+ botManager['notify'] = async (channelType, channelId, message) => {+ const channel = this.channels.get(channelType as any);+ if (channel) {+ await channel.send(message, channelId).catch((e) => logger.warn({ e }, 'bot notify channel send failed'));+ }+ };+ }++ getBotManager(): import('../bots/bot-manager.js').BotManager | undefined {+ return this.botManager;+ }+setSessionSyncEnabled(enabled: boolean): void {this.sessionSyncEnabled = enabled;}@@ -614,6 +630,18 @@ export class Agent {const trimmed = msg.content.trim();+ // Mercury Bots never touch the main message queue — /bots is always+ // fast-path, whether the main loop is busy or idle.+ if (trimmed.startsWith('/bots')) {+ const channel = this.channels.getChannelForMessage(msg);+ if (channel) {+ this.handleBotsCommand(trimmed, msg, channel).catch((err) => {+ logger.error({ err: (err as any)?.message ?? err, content: trimmed.slice(0, 50) }, '/bots command failed');+ });+ }+ return;+ }+if (this.processing && trimmed.startsWith('/')) {this.handleFastPathCommand(msg).catch((err) => {logger.error({ err, content: trimmed.slice(0, 50) }, 'Fast-path command failed');@@ -891,6 +919,12 @@ export class Agent {return;}+ // Bots run outside the main queue — /bots commands are always fast-path.+ if (trimmed.startsWith('/bots')) {+ await this.handleBotsCommand(trimmed, msg, channel);+ return;+ }+if (trimmed.startsWith('/bg')) {await this.handleBgCommand(trimmed, msg, channel);return;@@ -1017,6 +1051,179 @@ export class Agent {await channel.send('Agent is busy. Programming mode changes will be available after current task completes.', msg.channelId);}+ /**+ * /bots — Mercury Bots control surface (BOTS-ARCHITECTURE.md §2.7).+ * Always fast-path: bots live outside the main message queue, so bot+ * control stays responsive while the agent is busy.+ */+ private async handleBotsCommand(trimmed: string, msg: ChannelMessage, channel: any): Promise<void> {+ const bm = this.botManager;+ const channelId = msg.channelId;+ if (!bm) {+ await channel.send('Bots are not available (BotManager not wired).', channelId);+ return;+ }+ const rawArgs = trimmed.slice('/bots'.length).trim();+ const parts = rawArgs.length > 0 ? rawArgs.split(/\s+/) : [];+ const action = (parts[0] ?? '').toLowerCase();++ const stateIcons: Record<string, string> = { idle: '⚪', queued: '🔵', running: '🟢', paused: '🟡', disabled: '⛔' };+ const runIcons: Record<string, string> = { completed: '✅', failed: '❌', halted: '⛔', paused: '⏸', denied: '🚫' };++ if (action === '' || action === 'list') {+ const summaries = bm.getStatusSummaries();+ if (summaries.length === 0) {+ await channel.send('No bots configured. Use `/bots create <id> "Name" "Description"` to onboard one.', channelId);+ return;+ }+ const lines = [`**Bots** (${summaries.length})`, ''];+ for (const s of summaries) {+ const icon = stateIcons[s.state] ?? '❓';+ const lastRun = s.lastRunAt ? ` · last ${(s.lastRunState ?? '')} ${formatRelative(s.lastRunAt)}` : '';+ const activity = s.activity ? `\n ↳ ${s.activity}` : '';+ const attention = s.needsYou ? ' · ⚠ needs you' : '';+ lines.push(`${icon} **${s.name}** (${s.id}) — ${s.state}${attention}${lastRun}${activity}`);+ }+ 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)}`);+ await channel.send(lines.join('\n'), channelId);+ return;+ }++ if (action === 'create' || action === 'onboard') {+ // /bots create <id> "Name" "Description"+ const id = (parts[1] ?? '').toLowerCase();+ if (!id) {+ await channel.send('Usage: `/bots create <id> "Name" "Description"` — the bot starts with a fail-closed default profile you can refine via its profile files.', channelId);+ return;+ }+ const rest = trimmed.slice(trimmed.indexOf(id) + id.length).trim();+ const quoted = [...rest.matchAll(/"([^"]*)"/g)].map(m => m[1]);+ const name = quoted[0] ?? id.toUpperCase();+ const description = quoted[1];+ try {+ const manifest = bm.store.create({ id, name, description });+ bm.invalidateRuntime(id);+ await channel.send(`🤖 Bot **${manifest.name}** (\`${id}\`) onboarded — enabled, fail-closed defaults (dangerous tools denied, memory scope own, only its own directory writable).\nPersona: \`${bm.store.botDir(id)}/persona.md\` — edit it to shape the bot's character.`, channelId);+ } catch (err: any) {+ await channel.send(`Could not create bot "${id}": ${err?.message}`, channelId);+ }+ return;+ }++ if (action === 'send') {+ const target = parts[1]?.toLowerCase();+ const message = trimmed.slice(trimmed.indexOf(parts[1] ?? '') + (parts[1]?.length ?? 0)).trim();+ if (!target || !message) {+ await channel.send('Usage: `/bots send <id> <message>`', channelId);+ return;+ }+ const result = bm.enqueue(target, { trigger: 'chat', prompt: message, source: { channelType: msg.channelType, channelId } });+ if (!result.accepted) {+ await channel.send(`Could not message **${target}**: [reason: ${result.reasonCode}]`, channelId);+ return;+ }+ await channel.send(`🤖 Queued for **${target}** (job ${result.jobId}) — runs outside the main conversation.`, channelId);+ return;+ }++ if (action === 'enable' || action === 'disable') {+ const target = parts[1]?.toLowerCase();+ if (!target) {+ await channel.send(`Usage: \`/bots ${action} <id>\``, channelId);+ return;+ }+ try {+ bm.setEnabled(target, action === 'enable');+ await channel.send(`${action === 'enable' ? '✅ Enabled' : '⏸ Disabled'} bot **${target}**.`, channelId);+ } catch (err: any) {+ await channel.send(`Failed: ${err?.message}`, channelId);+ }+ return;+ }++ if (action === 'stop' || action === 'pause') {+ const target = parts[1]?.toLowerCase();+ if (!target) {+ await channel.send('Usage: `/bots stop <id>`', channelId);+ return;+ }+ const halted = await bm.halt(target);+ await channel.send(halted ? `⛔ Halt signal sent to **${target}** — it will stop after the current tool step.` : `**${target}** has nothing running.`, channelId);+ return;+ }++ if (action === 'journal') {+ const target = parts[1]?.toLowerCase();+ if (!target) {+ await channel.send('Usage: `/bots journal <id>`', channelId);+ return;+ }+ const records = bm.getJournal(target, 10);+ if (records.length === 0) {+ await channel.send(`No runs recorded yet for **${target}**.`, channelId);+ return;+ }+ const lines = [`**${target} — recent runs**`, ''];+ for (const r of [...records].reverse()) {+ const icon = r.state === 'completed' ? '✅' : r.state === 'failed' ? '❌' : r.state === 'paused' ? '⏸' : '⛔';+ const reason = r.reasonCode ? ` · [reason: ${r.reasonCode}]` : '';+ lines.push(`${icon} ${r.runId} · ${r.trigger} · ${r.state} · ${(r.durationMs / 1000).toFixed(1)}s · ${r.tokensIn + r.tokensOut} tok${reason}`);+ if (r.summary) lines.push(` ${r.summary.slice(0, 100)}`);+ }+ await channel.send(lines.join('\n'), channelId);+ return;+ }++ if (action === 'inbox') {+ const target = parts[1]?.toLowerCase();+ if (!target) {+ await channel.send('Usage: `/bots inbox <id>`', channelId);+ return;+ }+ const mail = bm.peekMailbox(target);+ if (mail.length === 0) {+ await channel.send(`**${target}** mailbox is empty.`, channelId);+ return;+ }+ const lines = [`**${target} — inbox** (${mail.length})`, ''];+ for (const m of mail) {+ lines.push(`🤖 from **${m.from}**: ${m.content.slice(0, 120)}`);+ }+ await channel.send(lines.join('\n'), channelId);+ return;+ }++ if (action === 'storage') {+ const usage = bm.getStorage();+ if (usage.length === 0) {+ await channel.send('No bot storage in use.', channelId);+ return;+ }+ const lines = ['**Bot storage**', ''];+ let total = 0;+ for (const u of usage) {+ total += u.bytes;+ lines.push(`**${u.id}**: ${formatBytes(u.bytes)} (journal ${formatBytes(u.journalBytes)})`);+ }+ lines.push('', `Total: ${formatBytes(total)} — caps are enforced at write time (transcripts keep last 50 runs; journals rotate at 5 MB).`);+ await channel.send(lines.join('\n'), channelId);+ return;+ }++ await channel.send(+ '**Bots commands**\n' ++ '`/bots` — roster with live states\n' ++ '`/bots create <id> "Name" "Description"` — onboard a bot\n' ++ '`/bots send <id> <message>` — message a bot\n' ++ '`/bots journal <id>` — recent runs\n' ++ '`/bots inbox <id>` — pending bot-to-bot mail\n' ++ '`/bots storage` — disk usage\n' ++ '`/bots enable|disable|stop <id>` — control',+ channelId,+ );+ }+private async handleBgCommand(trimmed: string, msg: ChannelMessage, channel: any): Promise<void> {const parts = trimmed.trim().split(/\s+/);const sub = parts.length > 1 ? parts[1] : '';@@ -4245,6 +4452,23 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub user}private async handleScheduledTask(manifest: ScheduledTaskManifest): Promise<void> {+ // Bot routines run on the bot lane, never through the main agent loop+ // (BOTS-ARCHITECTURE.md §2.3 — cron lane).+ if (manifest.botId) {+ if (!this.botManager) {+ logger.warn({ task: manifest.id, botId: manifest.botId }, 'Bot routine fired but BotManager is not wired');+ return;+ }+ logger.info({ task: manifest.id, botId: manifest.botId }, 'Bot routine firing');+ const result = this.botManager.enqueue(manifest.botId, {+ trigger: 'cron',+ prompt: manifest.prompt || manifest.description,+ });+ if (!result.accepted) {+ logger.warn({ botId: manifest.botId, reasonCode: result.reasonCode }, 'Bot routine could not be enqueued');+ }+ return;+ }logger.info({ task: manifest.id, channel: manifest.sourceChannelType }, 'Processing scheduled task');try {const channel = manifest.sourceChannelType@@ -7273,3 +7497,22 @@ Is this productive iteration or a stuck loop?`,}}}++/** Relative-time formatter for /bots run stamps (e.g. "3m ago"). */+function formatRelative(timestamp: number): string {+ const seconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000));+ if (seconds < 60) return `${seconds}s ago`;+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes}m ago`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return `${hours}h ago`;+ return `${Math.floor(hours / 24)}d ago`;+}++/** Human-readable byte size for /bots storage. */+function formatBytes(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;+}diff --git a/src/core/scheduler.ts b/src/core/scheduler.tsindex c7fd5e5e..166dfbe4 100644--- a/src/core/scheduler.ts+++ b/src/core/scheduler.ts@@ -24,6 +24,8 @@ export interface ScheduledTaskManifest {createdAt: string;sourceChannelId?: string;sourceChannelType?: string;+ /** Set for Mercury Bot routines — the run routes to the bot, not the main agent. */+ botId?: string;}const SCHEDULES_FILE = 'schedules.yaml';diff --git a/src/index.ts b/src/index.tsindex 77d928ee..d9060160 100644--- a/src/index.ts+++ b/src/index.ts@@ -51,6 +51,7 @@ import { Identity } from './soul/identity.js';import { ShortTermMemory, LongTermMemory, EpisodicMemory, migrateLegacyMemory } from './memory/store.js';import { buildConversationHistoryPayload, CloudSessionSynchronizer, SessionRepository } from './sessions/index.js';import { UserMemoryStore } from './memory/user-memory.js';+import { BotManager } from './bots/bot-manager.js';import { isBetterSqlite3Available } from './memory/second-brain-db.js';import { ProviderRegistry } from './providers/registry.js';import { Agent } from './core/agent.js';@@ -2470,6 +2471,24 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {agent.setSupervisor(supervisor);}+ // Mercury Bots: fleet manager runs outside the main message queue.+ if (config.bots?.enabled) {+ const botManager = new BotManager({+ config,+ providers,+ tokenBudget,+ userMemoryFactory: (_botId, manifest) => {+ const scope = manifest.memory?.scope ?? 'own';+ if (scope === 'none') return null;+ if (!userMemory) return null; // second brain unavailable — bots run stateless+ // Bots share the second-brain DB but are namespaced per bot.+ return new UserMemoryStore(config, `bot:${manifest.id}`);+ },+ });+ botManager.registerRoutines(scheduler);+ agent.setBotManager(botManager);+ }+let spotifyClient: SpotifyClient | undefined;if (config.spotify.clientId && config.spotify.clientSecret) {spotifyClient = new SpotifyClient(config);diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex c31b4399..d28f4d21 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -127,6 +127,16 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC'/session ','/session archive ','/session delete ',+ '/bots',+ '/bots list',+ '/bots create ',+ '/bots send ',+ '/bots journal ',+ '/bots inbox ',+ '/bots storage',+ '/bots enable ',+ '/bots disable ',+ '/bots stop ','/status','/progress','/menu',diff --git a/src/utils/config.ts b/src/utils/config.tsindex c9a74b21..2795f7bb 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -196,6 +196,19 @@ export interface MercuryConfig {maxConcurrent: number;mode: 'auto' | 'manual';};+ bots: {+ enabled: boolean;+ /** 0 = auto (clamp(2, cpus-1)). Fleet-wide cap on concurrent bot turns. */+ maxConcurrent: number;+ retention: {+ transcriptRuns: number;+ journalRotateBytes: number;+ journalKeepRotations: number;+ mailboxTtlHours: number;+ dlqCap: number;+ artifactQuotaBytes: number;+ };+ };spotify: {enabled: boolean;clientId: string;@@ -442,6 +455,18 @@ export function getDefaultConfig(): MercuryConfig {maxConcurrent: getEnvNum('SUBAGENTS_MAX_CONCURRENT', 0),mode: (process.env.SUBAGENTS_MODE as 'auto' | 'manual') || 'auto',},+ bots: {+ enabled: getEnvBool('BOTS_ENABLED', true),+ maxConcurrent: getEnvNum('BOTS_MAX_CONCURRENT', 0),+ retention: {+ transcriptRuns: getEnvNum('BOTS_RETENTION_TRANSCRIPT_RUNS', 50),+ journalRotateBytes: getEnvNum('BOTS_JOURNAL_ROTATE_BYTES', 5 * 1024 * 1024),+ journalKeepRotations: getEnvNum('BOTS_JOURNAL_KEEP_ROTATIONS', 3),+ mailboxTtlHours: getEnvNum('BOTS_MAILBOX_TTL_HOURS', 72),+ dlqCap: getEnvNum('BOTS_DLQ_CAP', 100),+ artifactQuotaBytes: getEnvNum('BOTS_ARTIFACT_QUOTA_BYTES', 500 * 1024 * 1024),+ },+ },spotify: {enabled: getEnvBool('SPOTIFY_ENABLED', false),clientId: getEnv('SPOTIFY_CLIENT_ID'),