Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): Bots 2.0 server — runs close themselves, an inbox, waste capped by rule
Salman Qureshi9a3c32d63440
diff --git a/DECISIONS.md b/DECISIONS.mdindex 73f4fb10..e7dd1e05 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -314,3 +314,15 @@- **Context**: ADR-028 gave the chat route files (#225) and the profile an avatar, but a bot could still only be *told* about a photo: `POST /api/bots/:id/message` read `message` and the durable job carried `{trigger, prompt, fromBot, source}`. The runtime could already read attachments (`withAttachments`, 8 MB image / 15 MB PDF, vision-gated), so the gap was purely the queue: a bot turn has no request, and the job is the only thing that survives a restart.- **Decision**: The job carries **paths**, not bytes — `attachments?: ChannelAttachment[]` on `BotJob` and `DurableBotJob`, stored as a JSON column (`attachments TEXT`, added by an idempotent `ALTER TABLE` like `run_after`), normalized on read. The route validates and writes the bytes with the same helper the chat route uses (`storeInlineAttachments`), then enqueues; files for a job that is refused (`409`) or a message that never arrives are deleted, so `uploads/` cannot accumulate orphans. `idempotencyKeyFor` now includes a hash of each attachment's bytes (not its path, which is a fresh random name per upload): the same caption with two different photos is two jobs, while a retried identical request still dedupes, and the retry's copies of the files are deleted. `runBotTurn` names a caption-less turn `(Attached: names)` — a provider rejects an empty text block — and applies `withAttachments` to the last user message, so a vision model gets image parts and a text-only one gets the existing note.- **Consequence**: A photo can be handed to a bot exactly like a chat turn, from the phone or a script, and the work survives a restart because the files are on disk and the job references them. Stale paths are harmless: `withAttachments` skips a file that no longer exists rather than failing the turn. Not here: files arriving from *other bots* (bot-to-bot mail carries text), transcription, and any retention sweep for uploads no job references — a disk-hygiene follow-up, not a correctness one.++## ADR-032: Bots 2.0 — every run closes itself, results go to an inbox, waste is capped by rule++- **Context**: Measured on a real install (1,580 runs, Sep 24–Oct 27): 787M tokens for about five owner-facing finished files. 43% of recent runs produced nothing; 19% failed (152M tokens); a lead on a 5-minute cron spent 347M writing records about records. Bots had no prompt caching (~25k tokens of fixed prompt re-sent at full price every step), every bot saw ~50 tools including 15 Spotify controls, a stop and the daily budgets reset on restart, a deny list in `bot.yaml` was silently overridden by a `permissions.yaml` without it, and a result produced while nobody was connected lived in an in-memory thread. The owner couldn't tell what a bot had done, or where its results were.+- **Decision**:+ - **Closing a run**: every run ends with exactly one tool call — `bot_report(summary, complete?)`, `bot_no_update(reason?)` or `bot_report_failure(reason)`. Outcomes gain `quiet` (nothing new: recorded, never announced, not a no-outcome strike, no memory-extraction call) and `failed` (the bot said it couldn't, even though the turn finished). The trace-based verdict stays as the fallback, and the no-outcome nudge asks for one of the three.+ - **Inbox**: `~/.mercury/bots/inbox.jsonl` (+ read marks) keeps `result`, `failed` and `needs-you` entries — the bot's own summary and the files it delivered — until the owner reads them, whether or not a client was connected. `GET /api/bots/inbox`, `POST /api/bots/inbox/read`, and a `bot_inbox` event on `/api/bots/events`. Quiet runs, retries, halts and results addressed to another bot stay in the journal only.+ - **Waste capped by rule, not by the model**: the system prompt is split into a stable prefix sent with Anthropic's cache marker and a per-run part after it; the duplicated tool-name list is gone; Spotify, GitHub and git tools are opt-in by group (`allow: [spotify]`); `dispatch_bot` is never a bot tool; every routine waits at least `bots.routineMinGapMinutes` (default 15) between runs, the owner's own too; a routine that fails 5 runs in a row is switched off until Start (one alert on the first failure, one when it switches off).+ - **Durable controls**: a stop survives a restart (`bots/stopped.json`) and stopped bots' routines aren't queued; today's per-bot and fleet spend is rebuilt from the journals at boot; a routine's last run time is kept in its routine state, so the gap survives a restart.+ - **Permissions**: a deny from either `permissions.yaml` or a legacy `bot.yaml` block applies (stricter wins). The roster reports each bot's tier (or `custom`).+ - **Deliveries**: text without an extension becomes `.md`; the same content delivered again is the existing file, not a numbered copy.+- **Consequence**: An unattended run either tells the owner something worth reading, says nothing, or says it failed — and the owner finds all of it in one place. Unchanged: retries still rerun a whole turn, missed cron ticks are still skipped, and bots still fail closed on approvals (asking the owner mid-run is the next step).diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex 5b38c3bb..abbe4fda 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -109,6 +109,11 @@ beforeEach(() => {// afterEach disposes all of them before the tmpdir is deleted.const activeManagers: Array<{ dispose: () => void }> = [];+/** The bot's system prompt as the model sees it: a `system` string, or leading system messages (cached prefix + per-run part). */+function systemText(opts: { system?: string; messages?: Array<{ role?: string; content: unknown }> }): string {+ return opts.system ?? (opts.messages ?? []).filter((m) => m.role === 'system').map((m) => String(m.content)).join('\n');+}+describe('BotManager queue + turn lifecycle', () => {let root: string;let store: BotStore;@@ -338,7 +343,7 @@ describe('BotManager queue + turn lifecycle', () => {seedBot(store, 'pathfinder');let systemPrompt = '';mockedGenerateText.mockImplementation(async (opts: any) => {- systemPrompt = opts.system ?? '';+ systemPrompt = systemText(opts);return { text: 'ok', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;});manager.enqueue('pathfinder', { trigger: 'chat', prompt: 'hi' });@@ -848,7 +853,7 @@ describe('Bot skill access (native + own library)', () => {seedBot(store, 'skilled');let systemPrompt = '';mockedGenerateText.mockImplementation(async (opts: any) => {- systemPrompt = opts.system ?? '';+ systemPrompt = systemText(opts);return { text: 'ok', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;});manager.enqueue('skilled', { trigger: 'chat', prompt: 'hi' });@@ -1165,6 +1170,8 @@ describe('bot governance (ADR-020)', () => {});it('a work routine that produces nothing three runs in a row is paused, told once, and resumed by start', async () => {+ // Back-to-back runs of one routine: lift the 15-minute floor for this test.+ (manager as unknown as { config: { bots: { routineMinGapMinutes?: number } } }).config.bots.routineMinGapMinutes = 0;seedBot(store, 'writer');const alerts: string[] = [];manager.setAlert(async (m) => { alerts.push(m); });diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 68f33729..9902364e 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -1,5 +1,5 @@import { refinePersona } from './persona-template.js';-import { randomUUID } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import { homedir } from 'node:os';import { basename, extname, isAbsolute, relative, resolve, join } from 'node:path';import { writeFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, rmSync } from 'node:fs';@@ -11,6 +11,8 @@ 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 { BotInbox } from './inbox.js';+import { detectTier } from './permission-tiers.js';import { BotStore, deliverableFileName, BOT_JOURNAL_FILENAME, BOT_PERMISSIONS_FILENAME, isValidCronExpression } from './store.js';import { BotJournal, type BotTranscript, type BotUsage } from './journal.js';import { BotQueue, idempotencyKeyFor, LEASE_SECONDS, type DurableBotJob } from './queue.js';@@ -112,6 +114,10 @@ export interface BotManagerDeps {const MAX_TRANSIENT_ATTEMPTS = 3;/** Consecutive no-outcome runs after which a work routine is paused (ADR-020). */export const NO_OUTCOME_PAUSE_AFTER = 3;+/** No routine runs more often than this, whatever its cron says (Bots 2.0). */+export const ROUTINE_MIN_GAP_MINUTES = 15;+/** A routine that fails this many runs in a row is switched off until the owner starts it again. */+export const ROUTINE_FAIL_OFF_AFTER = 5;/** First no-outcome cooldown; doubles per repeat up to NO_OUTCOME_PAUSE_MAX_MS. A pause always ends by itself. */export const NO_OUTCOME_PAUSE_MS = 6 * 60 * 60 * 1000;export const NO_OUTCOME_PAUSE_MAX_MS = 24 * 60 * 60 * 1000;@@ -230,6 +236,8 @@ export class BotManager {private turnLimitAlerted: Map<string, string> = new Map();/** Periodic due-sweep interval — cleared by dispose() (tests, shutdown). */private dueTimer?: ReturnType<typeof setInterval>;+ /** What the bots did for the owner, kept until read (Bots 2.0). */+ readonly inbox: BotInbox;constructor(deps: BotManagerDeps) {this.config = deps.config;@@ -253,6 +261,26 @@ export class BotManager {this.skillsRoot = deps.skillsRoot;this.queue = deps.queue ?? new BotQueue(this.store.botsRoot, this.config.bots?.retention?.dlqCap);this.tasks = new BotTaskStore(this.store.botsRoot);+ this.inbox = new BotInbox(this.store.botsRoot);+ // A stop survives a restart (it used to be in memory only, so a restart+ // quietly undid /bots stop).+ for (const id of this.store.readHeld()) if (this.store.exists(id)) this.held.add(id);+ // Today's spend survives a restart too: rebuilt from the journals, so a+ // restart can't reset a bot's (or the fleet's) daily budget.+ const dayStart = Date.parse(`${new Date().toISOString().slice(0, 10)}T00:00:00Z`);+ const today = new Date().toISOString().slice(0, 10);+ for (const m of this.store.list()) {+ try {+ const u = this.journalFor(m.id).usage(m.id, dayStart);+ const tokens = u.tokensIn + u.tokensOut;+ if (tokens > 0) {+ this.dailyTokens.set(m.id, { day: today, tokens });+ this.fleetDailyTokens = { day: today, tokens: (this.fleetDailyTokens.day === today ? this.fleetDailyTokens.tokens : 0) + tokens };+ const cap = this.dailyCapFor(m);+ if (cap > 0 && tokens >= cap) this.pausedForBudget.add(m.id);+ }+ } catch { /* a journal we can't read starts the day at zero */ }+ }// Resume work a crashed predecessor left behind: pending jobs (and// expired-lease claimed jobs) re-enter the in-memory queues. Durable// enqueue happens before any ack, so nothing was lost (§2.6).@@ -409,6 +437,8 @@ export class BotManager {// routine ran too recently, or when the routine was paused for// producing nothing. The next tick tries again.if (job.trigger === 'cron') {+ // A stopped bot's routines don't queue up behind the stop.+ if (this.held.has(botId)) return { jobId: '', accepted: false, reasonCode: 'stopped' };const key = job.routineId ?? `bot:${botId}:cron`;const routineState = this.store.readRoutineState(botId);const pausedEntry = routineState.paused[key];@@ -422,7 +452,8 @@ export class BotManager {logger.info({ botId, routineKey: key }, 'Bot routine cooldown over — resuming');}if (queue.length > 0 || (this.running.get(botId)?.size ?? 0) > 0) return { jobId: '', accepted: false, reasonCode: 'busy' };- const lastEnd = this.routineLastEnd.get(key);+ const persisted = routineState.lastEnd?.[key] ? Date.parse(routineState.lastEnd[key]) : undefined;+ const lastEnd = this.routineLastEnd.get(key) ?? (Number.isFinite(persisted) ? persisted : undefined);const minGapMs = this.routineConfig(manifest, key).minIntervalMinutes * 60_000;if (lastEnd !== undefined && Date.now() - lastEnd < minGapMs) return { jobId: '', accepted: false, reasonCode: 'too_soon' };}@@ -452,15 +483,22 @@ export class BotManager {return { jobId: id, accepted: true };}+ /** The fleet's floor between two runs of one routine (`bots.routineMinGapMinutes`, default 15). */+ private routineMinGap(): number {+ const v = this.config.bots?.routineMinGapMinutes;+ return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : ROUTINE_MIN_GAP_MINUTES;+ }+/** A routine's declared contract (bot.yaml schedules) or the defaults. */private routineConfig(manifest: BotManifest, routineKey: string): { expects: BotExpectedOutcome; minIntervalMinutes: number } {const declared = (manifest.schedules ?? []).find(r => `bot:${manifest.id}:${r.name}` === routineKey);- // A cadence the owner declared in bot.yaml is honoured as written (the- // busy-skip still applies); routines a bot created for itself are- // rate-limited to 30 minutes unless the owner says otherwise.+ // Every routine waits at least ROUTINE_MIN_GAP_MINUTES between runs, the+ // owner's own too: a 5-minute cron on a lead spent hundreds of millions of+ // tokens writing records about records. Routines a bot created for itself+ // wait 30 minutes unless the owner says otherwise.return {expects: declared?.expects ?? 'work',- minIntervalMinutes: declared?.minIntervalMinutes ?? (declared ? 0 : 30),+ minIntervalMinutes: Math.max(this.routineMinGap(), declared?.minIntervalMinutes ?? (declared ? this.routineMinGap() : 30)),};}@@ -707,6 +745,8 @@ export class BotManager {private pump(botId: string): void {const manifest = this.store.get(botId);if (!manifest?.enabled || this.disabled.has(botId)) return;+ // Stopped by the owner: work waits (durably) until they start it again.+ if (this.held.has(botId)) return;const today = new Date().toISOString().slice(0, 10);const used = this.dailyTokens.get(botId);if (used && used.day !== today) {@@ -846,6 +886,7 @@ export class BotManager {tokensIn: output.tokensIn,tokensOut: output.tokensOut,summary: output.output.slice(0, 300),+ ...(output.report ? { report: output.report.kind, ...(output.report.complete ? { complete: true } : {}) } : {}),error: output.error,reasonCode: output.reasonCode,// A turn cut off by policy is not an escalation (ADR-020).@@ -865,7 +906,29 @@ export class BotManager {this.lastRun.set(botId, { at: Date.now(), state: record.state });this.needsYou.delete(botId);this.recordBotTokens(botId, manifest, output.tokensIn + output.tokensOut);- if (routineKey) this.routineLastEnd.set(routineKey, Date.now());+ // Did this run fail for good (not a retry, not a policy cut-off)? Either the+ // turn died, or the bot itself reported that it couldn't do the job.+ const failedForGood = (output.status === 'failed' && !willRetry && !turnLimited) || output.outcome === 'failed';+ let routineFailStreak = 0;+ if (routineKey) {+ this.routineLastEnd.set(routineKey, Date.now());+ const state = this.store.readRoutineState(botId);+ state.lastEnd = { ...(state.lastEnd ?? {}), [routineKey]: new Date().toISOString() };+ if (failedForGood) {+ routineFailStreak = (state.failStreak?.[routineKey] ?? 0) + 1;+ state.failStreak = { ...(state.failStreak ?? {}), [routineKey]: routineFailStreak };+ if (routineFailStreak >= ROUTINE_FAIL_OFF_AFTER) {+ // Switched off, not cooled down: it would keep burning tokens on the same failure.+ state.paused[routineKey] = { since: new Date().toISOString(), reason: `${routineFailStreak} runs in a row failed` };+ delete state.failStreak![routineKey];+ logger.warn({ botId, routineKey, streak: routineFailStreak }, 'Bot routine switched off — failing every run');+ void this.alertOwner(botId, `⏹ **${manifest.name}**'s routine \`${routineKey.split(':').pop()}\` is switched off: its last ${routineFailStreak} runs failed${output.reasonCode ? ` (${output.reasonCode})` : ''}. Fix the cause, then Start the bot (\`/bots start ${botId}\`) to turn it back on.`);+ }+ } else if (output.status === 'completed' && state.failStreak?.[routineKey]) {+ delete state.failStreak[routineKey];+ }+ this.store.writeRoutineState(botId, state);+ }// No-outcome streak (ADR-020): a work routine that produces nothing// three runs in a row is paused — the owner is told once, and@@ -943,7 +1006,11 @@ export class BotManager {this.queue.settle(job.id, 'dead', output.reasonCode);this.needsYou.add(botId);logger.warn({ botId, jobId: job.id, reasonCode: output.reasonCode }, 'Bot turn failed permanently — moved to DLQ (replayable via /bots dlq)');- await this.alertOwner(botId, `❌ **${manifest.name}** failed permanently [reason: ${output.reasonCode}] — replay with \`/bots replay ${botId} ${job.id}\``);+ // A routine failing again and again tells the owner once, on the first+ // failure; the streak switches it off after ROUTINE_FAIL_OFF_AFTER.+ if (routineFailStreak <= 1) {+ await this.alertOwner(botId, `❌ **${manifest.name}** failed permanently [reason: ${output.reasonCode}] — replay with \`/bots replay ${botId} ${job.id}\``);+ }} else if (output.status === 'paused') {// Step-budget pause: work continues next turn — same job requeues in// place (durable), no attempts bump.@@ -970,7 +1037,9 @@ export class BotManager {// (sendToBot), and its synthesis is the user-facing outcome of the// whole delegation — skipping every mailbox turn left it journaled// but never shown.- if (this.notify && !replyTargetFor(job)) {+ // Quiet runs (bot_no_update) are recorded, never announced: "nothing new"+ // every 15 minutes is exactly the noise the owner stops reading.+ if (this.notify && !replyTargetFor(job) && output.outcome !== 'quiet') {const botThread = `bot:${botId}`;const icon = output.status === 'completed' ? '🤖' : output.status === 'failed' ? '❌' : output.status === 'halted' ? '⏹' : '⏸';// Full result, matched to the channel's per-message cap (64KB) — the@@ -1008,13 +1077,39 @@ export class BotManager {}}+ // The owner's inbox (Bots 2.0): results, reported failures and runs that+ // need them — durable, so they're there when the owner comes back. Not+ // here: quiet runs, retries, halts, and results addressed to another bot.+ if (!replyTargetFor(job) && output.status !== 'halted') {+ const firstLine = (s: string) => s.split('\n').map((l) => l.trim()).find(Boolean) ?? '';+ const base = { botId, botName: manifest.name, runId: job.id, files: output.deliverables };+ if (output.outcome === 'failed') {+ this.inbox.add({ ...base, kind: 'failed', title: `${manifest.name} couldn't do it: ${firstLine(output.report?.summary ?? output.output).slice(0, 100)}`, summary: output.report?.summary ?? output.output });+ } else if (failedForGood) {+ this.inbox.add({ ...base, kind: 'needs-you', title: `${manifest.name} failed (${output.reasonCode ?? 'error'})`, summary: output.error ?? output.output, reasonCode: output.reasonCode });+ } else if (turnLimited) {+ this.inbox.add({ ...base, kind: 'needs-you', title: `${manifest.name} hit its per-run limit`, summary: `The run was stopped at its ${output.reasonCode === 'turn_time' ? 'time' : 'token'} limit before it finished. Split the task, or raise the limit in the bot's settings.`, reasonCode: output.reasonCode });+ } else if (output.status === 'completed' && ['deliverable', 'action', 'message', 'delegated'].includes(output.outcome)) {+ const summary = output.report?.summary ?? output.output;+ const files = output.deliverables.length;+ this.inbox.add({+ ...base,+ kind: 'result',+ title: `${manifest.name}: ${firstLine(summary).slice(0, 110) || (files ? `delivered ${files} file${files === 1 ? '' : 's'}` : 'finished')}`,+ summary,+ ...(output.report?.complete ? { complete: true } : {}),+ });+ }+ }+// Fleet delegation loop: a task dispatched by another bot reports its// result back to the sender's mailbox (attributed, plain mail — never a// task, so results can't ping-pong). Paused runs requeue and report// later; the failure/retry machinery above owns transient states.// Memory (ADR-021): a productive run teaches the bot something.const memoryStore = this.userMemoryFor(botId, manifest);- if (output.status === 'completed' && memoryStore && manifest.memory?.learn !== false) {+ // A quiet run ("nothing new") has nothing to teach: no extra model call for it.+ if (output.status === 'completed' && output.outcome !== 'quiet' && memoryStore && manifest.memory?.learn !== false) {void extractBotMemories({botId, botName: manifest.name, prompt: job.prompt, output: output.output, outcome: output.outcome,deliverables: output.deliverables, provider: resolveProvider(this.providers, manifest, this.config), tokenBudget: this.tokenBudget, memory: memoryStore,@@ -1501,7 +1596,7 @@ export class BotManager {this.lastRun.delete(botId);this.needsYou.delete(botId);this.pausedForBudget.delete(botId);- this.held.delete(botId);+ if (this.held.delete(botId)) this.store.writeHeld(this.held);logger.info({ botId }, 'Bot deleted: queue/mail/DLQ purged, routines removed');}@@ -1629,6 +1724,7 @@ export class BotManager {let heldJobs = (this.queues.get(botId) ?? []).length;let halted = await this.halt(botId);this.held.add(botId);+ this.store.writeHeld(this.held);let crewStopped = 0;if (this.store.isLead(botId)) {for (const crew of this.store.crewOf(botId)) {@@ -1655,11 +1751,12 @@ export class BotManager {const manifest = this.store.get(botId);if (!manifest) throw new Error(`Bot "${botId}" does not exist`);this.held.delete(botId);+ this.store.writeHeld(this.held);// An explicit start is the owner saying "try again": paused routines- // resume with a clean streak.+ // resume with a clean streak (and a routine switched off for failing gets another chance).const routines = this.store.readRoutineState(botId);- if (Object.keys(routines.paused).length > 0 || Object.keys(routines.noOutcomeStreak).length > 0) {- this.store.writeRoutineState(botId, { paused: {}, noOutcomeStreak: {}, pauseCount: {} });+ if (Object.keys(routines.paused).length > 0 || Object.keys(routines.noOutcomeStreak).length > 0 || Object.keys(routines.failStreak ?? {}).length > 0) {+ this.store.writeRoutineState(botId, { paused: {}, noOutcomeStreak: {}, pauseCount: {}, lastEnd: routines.lastEnd ?? {}, failStreak: {} });}let resumed = this.rehydratePending(botId);if (!manifest.enabled || this.disabled.has(botId)) {@@ -1672,6 +1769,7 @@ export class BotManager {const m = this.store.get(crew.id);if (!m?.enabled || this.disabled.has(crew.id)) continue; // explicitly disabled crew stay offthis.held.delete(crew.id);+ this.store.writeHeld(this.held);resumed += this.rehydratePending(crew.id);this.pump(crew.id);resumed += this.start(crew.id).resumed;@@ -1730,6 +1828,7 @@ export class BotManager {// ---- observation ---------------------------------------------------------getStatusSummaries(): BotStatusSummary[] {+ const unread = this.inbox.unreadByBot();return this.store.list().map((m) => {const running = this.running.get(m.id);const queue = this.queues.get(m.id) ?? [];@@ -1749,6 +1848,10 @@ export class BotManager {lastRunState: last?.state,needsYou: this.needsYou.has(m.id),hasAvatar: this.store.hasAvatar(m.id),+ unread: unread.get(m.id) ?? 0,+ tier: detectTier(this.store.readPermissions(m.id)),+ ...(this.held.has(m.id) ? { stopped: true } : {}),+ ...(m.description ? { description: m.description } : {}),fleetRole: m.fleetRole,parent: m.parent,crewWorking: m.fleetRole === 'lead'@@ -1955,8 +2058,17 @@ export class BotManager {const botFolder = this.store.pinDeliverablesFolder(botId);const destDir = isCrew ? botFolder : final ? botFolder : join(botFolder, 'work');mkdirSync(destDir, { recursive: true });+ // The same content delivered again (a retry, a re-run) is the file already+ // there, not "Report (2).md" next to it.+ const same = sameContentIn(destDir, candidate);+ if (same) {+ try { unlinkSync(candidate); } catch { /* the source copy is the bot's; leave it */ }+ logger.info({ botId, dest: same }, 'Bot re-delivered an artifact already in the folder');+ return { accepted: true, path: same, final };+ }const sourceName = options.saveAs || basename(candidate);- const ext = extname(sourceName) || extname(candidate);+ // A file without an extension opens as nothing on the owner's computer: text becomes .md.+ const ext = extname(sourceName) || extname(candidate) || (looksLikeText(candidate) ? '.md' : '');const stem = options.title?.trim() || basename(sourceName, ext);const fileName = deliverableFileName(stem, ext);const finalExt = extname(fileName);@@ -2142,4 +2254,29 @@ function describeJob(job: BotJob): string {}// Re-exported for the /bots storage view.-export { BOT_JOURNAL_FILENAME };\ No newline at end of file+export { BOT_JOURNAL_FILENAME };++/** A file in `dir` with exactly the bytes of `file`, if any (size first, then content). */+function sameContentIn(dir: string, file: string): string | undefined {+ try {+ const size = statSync(file).size;+ const want = createHash('sha256').update(readFileSync(file)).digest('hex');+ for (const name of readdirSync(dir)) {+ const p = join(dir, name);+ const st = statSync(p);+ if (!st.isFile() || st.size !== size || name === 'README.md') continue;+ if (createHash('sha256').update(readFileSync(p)).digest('hex') === want) return p;+ }+ } catch { /* no folder yet, or unreadable: deliver normally */ }+ return undefined;+}++/** No NUL bytes in the first 4 KB: text. */+function looksLikeText(file: string): boolean {+ try {+ const buf = readFileSync(file).subarray(0, 4096);+ return !buf.includes(0);+ } catch {+ return false;+ }+}diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.tsindex 46defeac..ba5d499b 100644--- a/src/bots/bot-turn.ts+++ b/src/bots/bot-turn.ts@@ -1,4 +1,5 @@-import { streamText, stepCountIs } from 'ai';+import { streamText, stepCountIs, tool, zodSchema } from 'ai';+import { z } from 'zod';import { withAttachments } from '../core/attachments.js';import type { ChannelAttachment } from '../types/channel.js';import type { ModelMessage, Tool } from 'ai';@@ -52,8 +53,26 @@ export type BotActivityEvent = {*/export type BotExpectedOutcome = 'work' | 'message' | 'check';-/** What the tool trace proves the run did — the journal's `outcome`. */-export type BotOutcome = 'deliverable' | 'action' | 'delegated' | 'message' | 'none';+/**+ * What the run did — the journal's `outcome`. Evidence from the tool trace+ * (deliverable, action, delegated), the bot's own report (message: a finding+ * or answer for the owner; quiet: nothing new, said with bot_no_update;+ * failed: bot_report_failure), else none.+ */+export type BotOutcome = 'deliverable' | 'action' | 'delegated' | 'message' | 'quiet' | 'failed' | 'none';++/**+ * How the bot itself closed the run (Bots 2.0): every unattended run ends with+ * exactly one of these. A result goes to the owner's inbox; no_update is+ * recorded quietly (no notification); failure is a failed run even when the+ * turn itself finished.+ */+export interface BotRunReport {+ kind: 'result' | 'no_update' | 'failure';+ summary: string;+ /** result: the job is finished (a goal met), not just progress. */+ complete?: boolean;+}/** Hard per-turn limits (ADR-020). Overridable per bot via `autonomy`. */export interface BotTurnLimits {@@ -150,6 +169,8 @@ export interface BotTurnOutput {/** Largest single-step prompt the provider saw — the context-growth meter. */peakInputTokens: number;outcome: BotOutcome;+ /** The bot's own close of the run, when it gave one. */+ report?: BotRunReport;/** Paths of files delivered via bot_deliver this turn. */deliverables: string[];/** The reply claimed delivery/execution but the trace shows none. */@@ -214,8 +235,17 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {const expects: BotExpectedOutcome = input.expects ?? defaultExpectation(input.trigger);const startedAt = Date.now();- const system = buildBotSystemPrompt(input);- const messages: ModelMessage[] = [];+ // Prompt caching: the stable prefix (identity, persona, rules, folders,+ // fleet protocol — ~10-20k tokens) is re-sent on every step. Marked for+ // Anthropic's cache it costs a tenth from the second step on; the per-run+ // parts (memory, recent runs, state, budget) follow the marker so they+ // never invalidate it. Providers that don't know the option ignore it.+ const prompt = buildBotSystemPrompt(input);+ const messages: ModelMessage[] = [+ { role: 'system', content: prompt.stable, providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } } } as ModelMessage,+ ...(prompt.volatile ? [{ role: 'system', content: prompt.volatile } as ModelMessage] : []),+ ];+ const leadingSystem = messages.length;for (const m of input.mail) {messages.push({ role: 'user', content: `Message from 🤖 ${m.from}:\n\n${m.content}` });@@ -225,8 +255,8 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {if (caption) {messages.push({ role: 'user', content: caption });}- if (messages.length === 0) {- messages.push({ role: 'user', content: 'You have no specific task. Check your inbox and report your status.' });+ if (messages.length === leadingSystem) {+ messages.push({ role: 'user', content: 'You have no specific task. Check your inbox; if nothing needs doing, call bot_no_update.' });}if (files.length > 0) {// Same transformation channels get: image/file parts for a model that takes them,@@ -290,16 +320,21 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {deadline.unref?.();const halted = (): boolean => input.abortSignal.aborted;- const tools = wrapBotTools(input.tools, {- sandbox: input.sandbox,- limits,- onDelivered: (path) => deliveries.push(path),- });+ let report: BotRunReport | undefined;+ const tools = {+ ...wrapBotTools(input.tools, {+ sandbox: input.sandbox,+ limits,+ onDelivered: (path) => deliveries.push(path),+ }),+ ...runReportTools((r) => { report = r; }),+ };const baseOutput = () => ({tokensIn, tokensOut, toolsUsed: [...toolsUsed], startedAt, steps: stepIndex, toolCalls: trace.length,- peakInputTokens, deliverables: [...deliveries], outcomeNudged, trace: [...trace],+ peakInputTokens, deliverables: [...deliveries], outcomeNudged, trace: [...trace], ...(report ? { report } : {}),});+ const outcomeNow = (text: string): BotOutcome => computeOutcome({ trace, deliveries, expects, text, sandbox: input.sandbox, report });try {emit({ kind: 'turn-start', stepIndex: 0, label: input.prompt ? input.prompt.slice(0, 80) : 'Checking inbox' });@@ -312,7 +347,6 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {let streamError: unknown = null;const stream = streamText({model: provider.getModelInstance(),- system,messages,tools,stopWhen: stepCountIs(stepsRemaining),@@ -439,7 +473,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {// Consume newly arrived mailbox messages before finishing, so a// handoff delivered mid-turn is not lost to the next scheduling gap.- if (!governor.signal.aborted && stepsRemaining > 0) {+ if (!governor.signal.aborted && stepsRemaining > 0 && !report) {const fresh = input.pollMail();if (fresh.length > 0) {for (const m of fresh) {@@ -453,8 +487,8 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {// A run expected to produce work that only read and wrote notes gets// exactly one nudge — deliver now, or say plainly that nothing was// done. Bounded like the execute guard; never a loop.- if (!governor.signal.aborted && expects === 'work' && !outcomeNudged- && computeOutcome({ trace, deliveries, expects, text: result.text, sandbox: input.sandbox }) === 'none') {+ if (!governor.signal.aborted && expects === 'work' && !outcomeNudged && !report+ && outcomeNow(result.text) === 'none') {outcomeNudged = true;emit({ kind: 'step', stepIndex, label: 'no deliverable yet — asking for one' });messages.push({ role: 'user', content: noOutcomePrompt(input) });@@ -480,14 +514,15 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {status: 'paused',output: 'Step budget reached before the turn completed — remaining work continues next turn.',reasonCode: 'step_budget',- outcome: computeOutcome({ trace, deliveries, expects, text: '', sandbox: input.sandbox }),+ outcome: outcomeNow(''),claimedWithoutAction: false,...baseOutput(),};}- const output = (lastResult?.text || '').trim() || '(no text response)';- const outcome = computeOutcome({ trace, deliveries, expects, text: lastResult?.text ?? '', sandbox: input.sandbox });+ // The bot's own report is what the owner reads; its last words are the fallback.+ const output = (report?.summary || lastResult?.text || '').trim() || '(no text response)';+ const outcome = outcomeNow(lastResult?.text ?? '');const claimedWithoutAction = outcome === 'none' && CLAIM_PATTERN.test(output);tokenBudget.recordUsage({@@ -516,7 +551,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {output: `Turn failed: ${message}`,error: message,reasonCode: classifyFailure(err),- outcome: computeOutcome({ trace, deliveries, expects, text: '', sandbox: input.sandbox }),+ outcome: outcomeNow(''),claimedWithoutAction: false,...baseOutput(),};@@ -679,7 +714,10 @@ export function computeOutcome(input: {expects: BotExpectedOutcome;text: string;sandbox: { workspace: string; shared: string };+ report?: BotRunReport;}): BotOutcome {+ // A reported failure is a failure, whatever else happened on the way.+ if (input.report?.kind === 'failure') return 'failed';if (input.deliveries.length > 0) return 'deliverable';const roots = [input.sandbox.workspace, input.sandbox.shared];for (const t of input.trace) {@@ -689,17 +727,21 @@ export function computeOutcome(input: {if (t.name === 'run_command' && t.arg && !isReadOnlyCommand(t.arg)) return 'action';}if (input.trace.some((t) => t.ok && t.name === 'bot_send' && t.task)) return 'delegated';+ if (input.report?.kind === 'no_update') return 'quiet';+ // A reported finding is a result for the owner, even without a file.+ if (input.report?.kind === 'result' && input.report.summary.trim().length > 0) return 'message';if (input.expects === 'message' && input.text.trim().length > 0) return 'message';return 'none';}function noOutcomePrompt(input: BotTurnInput): string {const where = input.deliverablesDir ? ` into ${input.deliverablesDir}` : '';- return `[outcome check] This run has produced no deliverable and taken no action — only reads and notes in your sandbox. `+ return `[outcome check] This run has not been closed: no deliverable, no action, and no report. `+ `Notes are not work. Do ONE of these now, then stop:\n`- + `1. If you have a finished result, deliver it with bot_deliver${where} and name the file in your reply.\n`- + `2. If the task needs an action (a command, a change outside your sandbox, a delegation), do it.\n`- + `3. If there was genuinely nothing to do, reply with one line starting "Nothing to do:" and the reason. Do not write a record about it.`;+ + `1. A finished file: deliver it with bot_deliver${where}, then call bot_report with what it is.\n`+ + `2. A finding or answer for the owner (no file needed): call bot_report with it.\n`+ + `3. Nothing new or nothing to do: call bot_no_update with one line why. Do not write a record about it.\n`+ + `4. You couldn't do it: call bot_report_failure with the reason.`;}// ---- context compaction ---------------------------------------------------@@ -801,9 +843,66 @@ export function wrapBotTools(return out;}+// ---- closing a run --------------------------------------------------------++/**+ * The three ways a run ends (Bots 2.0). The bot says which — a tool call, not+ * a phrase to match — so "nothing new" is recorded quietly, a finding reaches+ * the owner's inbox, and a run that couldn't do its job is a failure even+ * when the turn itself finished.+ */+export function runReportTools(onReport: (r: BotRunReport) => void): Record<string, Tool> {+ const done = 'Recorded. Stop now: end your turn without further tool calls.';+ return {+ bot_report: tool({+ description:+ 'Close this run with a result for the owner: what you did or found, in a few plain sentences (they read it in their inbox). '+ + 'Deliver any finished files with bot_deliver first; they are attached automatically. complete: true when the job is finished, not just progress.',+ inputSchema: zodSchema(z.object({+ summary: z.string().min(1).max(4000).describe('What you did or found, for the owner. Plain sentences; lead with the answer.'),+ complete: z.boolean().optional().describe('true = the job is done (its goal is met); omit for progress.'),+ })),+ execute: async ({ summary, complete }: { summary: string; complete?: boolean }) => {+ onReport({ kind: 'result', summary: summary.trim(), ...(complete ? { complete: true } : {}) });+ return done;+ },+ }) as Tool,+ bot_no_update: tool({+ description:+ 'Close this run with nothing new to report (nothing changed, nothing to do). It is recorded quietly: the owner is not notified. '+ + 'Use it instead of writing a status note or saying "nothing to do".',+ inputSchema: zodSchema(z.object({+ reason: z.string().max(300).optional().describe('One line: why there is nothing new.'),+ })),+ execute: async ({ reason }: { reason?: string }) => {+ onReport({ kind: 'no_update', summary: (reason ?? '').trim() || 'Nothing new.' });+ return done;+ },+ }) as Tool,+ bot_report_failure: tool({+ description:+ 'Close this run as failed: you could not do the job (missing access, broken input, a service down). Say why, and what would fix it. '+ + 'The owner is told. Do not use it for "nothing to do" (that is bot_no_update).',+ inputSchema: zodSchema(z.object({+ reason: z.string().min(1).max(1000).describe('What stopped you, and what would fix it.'),+ })),+ execute: async ({ reason }: { reason: string }) => {+ onReport({ kind: 'failure', summary: reason.trim() });+ return done;+ },+ }) as Tool,+ };+}+// ---- system prompt ---------------------------------------------------------function buildBotSystemPrompt(input: BotTurnInput): string {+/**+ * The bot's system prompt in two parts. `stable` is the same on every run of+ * this bot (identity, persona, rules, folders, roster, fleet protocol), so a+ * provider can cache it; `volatile` changes per run (memory retrieved for this+ * prompt, recent runs, state note, crew states, budget) and follows it.+ */+export function buildBotSystemPrompt(input: BotTurnInput): { stable: string; volatile: string } {const { manifest } = input;let prompt = `You are "${manifest.name}", a Mercury bot (id: ${manifest.id}).\n`;if (manifest.description) {@@ -812,25 +911,12 @@ function buildBotSystemPrompt(input: BotTurnInput): string {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.-- Work, don't narrate: a run is judged by what it delivered or changed, not by what it wrote about itself. Do not write records, receipts, logs or status files about your own runs — Mercury keeps the journal. If there is nothing to do, say "Nothing to do:" and the reason, and stop.`;+- Work, don't narrate: a run is judged by what it delivered or changed, not by what it wrote about itself. Do not write records, receipts, logs or status files about your own runs — Mercury keeps the journal.+- END EVERY RUN WITH EXACTLY ONE of: bot_report (a result or finding for the owner; deliver files first), bot_no_update (nothing new — recorded quietly, nobody is notified), bot_report_failure (you couldn't do it, and why). Then stop.`;// Sandbox: the bot's always-granted work areas (rw+x, no permission ask).prompt += `\n\nSandbox (always granted — read, write, execute; no permission needed):@@ -842,17 +928,7 @@ Anything outside these two areas and your declared Access grants is denied.`;prompt += `\n\nDeliverables — where the owner finds your results: ${input.deliverablesDir}- When a result is finished, call bot_deliver on the file (give it a human title; mark final: true for the finished piece the owner asked for). Never write there by hand.- Intermediate stages (research, drafts, checks) are delivered as work, not finals; the lead delivers the final.-- Name the delivered file in your reply.`;- }-- // Continuity (ADR-021): what the journal already knows, and the bot's own- // note. Together they replace "records about records" — nothing here- // needs to be written to disk by the bot.- if (input.recentRuns) {- prompt += `\n\nYour recent runs (from the journal — you do not need to record these):\n${input.recentRuns}`;- }- if (input.stateNote) {- prompt += `\n\nYour working state (set with bot_state; replace it when it changes):\n${input.stateNote}`;+- Then close the run with bot_report saying what you delivered.`;}const roster = manifest.comms?.canMessage ?? [];@@ -860,23 +936,15 @@ Anything outside these two areas and your declared Access grants is denied.`;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(', ')}`;- }-if (input.skillsPrompt) {prompt += `\n\n${input.skillsPrompt}`;prompt += `\nSkill scripts are subject to your access grants: a skill whose scripts you cannot run from its own directory can be copied into your sandbox workspace and run from there.`;}- // Fleet hierarchy: the lead orchestrates, the crew executes.+ // Fleet hierarchy: the lead orchestrates, the crew executes. The crew list+ // (with live states) is per-run; the protocol is stable.if (input.fleet?.role === 'lead') {- const roster = input.fleet.crew.length > 0- ? input.fleet.crew.map(c => `- ${c.name} (${c.id})${c.description ? ` — ${c.description}` : ''} [${c.state}]`).join('\n')- : '(EMPTY — build your team first, see below)';- prompt += `\n\nYou lead a fleet of crew bots:-${roster}+ prompt += `\n\nYou lead a fleet of crew bots (the current crew is listed below, under "This run").Fleet protocol:- SELF-ORGANIZE: if your crew is empty or lacks a specialist the task needs, BUILD IT FIRST with bot_spawn — design each sub-bot's role and persona from YOUR persona and the current task (e.g. a product lead spawns research/QA/support specialists). Do not report that you lack a team; hire one. Then delegate.@@ -885,13 +953,42 @@ Fleet protocol:- MONITOR with fleet_status / fleet_tasks only when you need to — results come to you.- You may create specialists with bot_spawn (crew cap: ${input.fleet.maxCrew}) and retire your own crew with bot_retire.- Crew run CONCURRENTLY — dispatch independent work in parallel rather than sequentially.-- You SYNTHESIZE: crew results arrive in your mailbox attributed by bot; combine them and report a single coherent outcome.${input.fleet.leadName ? `\n- You are also crew of **${input.fleet.leadName}** — your task results return to it automatically; treat it as your manager.` : ''}`;+- You SYNTHESIZE: crew results arrive in your mailbox attributed by bot; combine them and report a single coherent outcome with bot_report.${input.fleet.leadName ? `\n- You are also crew of **${input.fleet.leadName}** — your task results return to it automatically; treat it as your manager.` : ''}`;} else if (input.fleet?.role === 'crew') {- prompt += `\n\nYou are crew in **${input.fleet.leadName ?? 'your lead'}'s** fleet. Tasks delegated to you (mailbox messages with a task) return your result to the lead automatically when you finish — make your final output a complete, self-contained report. Use bot_send to ask the lead questions mid-task.`;+ prompt += `\n\nYou are crew in **${input.fleet.leadName ?? 'your lead'}'s** fleet. Tasks delegated to you (mailbox messages with a task) return your result to the lead automatically when you finish — make your bot_report a complete, self-contained report. Use bot_send to ask the lead questions mid-task.`;}- const remaining = input.tokenBudget.getRemaining();- prompt += `\n\nToken budget remaining: ${remaining}`;+ // ---- per run -----------------------------------------------------------+ let volatile = '';+ // 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) {+ volatile += `\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');+ }+ }+ // Continuity (ADR-021): what the journal already knows, and the bot's own+ // note. Together they replace "records about records" — nothing here+ // needs to be written to disk by the bot.+ if (input.recentRuns) {+ volatile += `\n\nYour recent runs (from the journal — you do not need to record these):\n${input.recentRuns}`;+ }+ if (input.stateNote) {+ volatile += `\n\nYour working state (set with bot_state; replace it when it changes):\n${input.stateNote}`;+ }+ if (input.fleet?.role === 'lead') {+ const crew = input.fleet.crew.length > 0+ ? input.fleet.crew.map(c => `- ${c.name} (${c.id})${c.description ? ` — ${c.description}` : ''} [${c.state}]`).join('\n')+ : '(EMPTY — build your team first, see the fleet protocol)';+ volatile += `\n\nYour crew right now:\n${crew}`;+ }+ volatile += `\n\nToken budget remaining: ${input.tokenBudget.getRemaining()}`;- return prompt;+ return { stable: prompt, volatile: `This run:${volatile}` };}diff --git a/src/bots/bots2.test.ts b/src/bots/bots2.test.tsnew file mode 100644index 00000000..152780dc--- /dev/null+++ b/src/bots/bots2.test.ts@@ -0,0 +1,253 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++/**+ * Bots 2.0: every run ends as a result, nothing new, or a failure — said by+ * the bot with a tool call. Results reach a durable inbox; quiet runs are+ * recorded and never announced; a stop, the daily spend and a routine's last+ * run all survive a restart; a routine that keeps failing is switched off.+ */++vi.mock('ai', async (importOriginal) => {+ const actual = await importOriginal<typeof import('ai')>();+ return { ...actual, generateText: vi.fn(), streamText: vi.fn() };+});++import { generateText, streamText } from 'ai';+import { BotManager } from './bot-manager.js';+import { BotStore } from './store.js';+import { buildBotSystemPrompt, computeOutcome } from './bot-turn.js';+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';++const mockedGenerateText = vi.mocked(generateText);+// Bot turns run on streamText: feed the scripted generateText through the stream shape.+type Final = { text: string; finishReason: string; usage: unknown };+vi.mocked(streamText).mockImplementation(((opts: unknown) => {+ let final: Final = { text: '', finishReason: 'stop', usage: {} };+ let failed: unknown = null;+ let settle: () => void = () => {};+ const settled = new Promise<void>((r) => { settle = r; });+ const gen = (generateText as unknown as (o: unknown) => Promise<Final> | undefined)(opts) ?? Promise.resolve(final);+ // eslint-disable-next-line require-yield -- the turn only drains the stream; the scripted call fires the step callbacks+ const fullStream = (async function* () {+ try { final = await gen; } catch (err) { failed = err; }+ settle();+ })();+ const once = async <T,>(pick: () => T): Promise<T> => { await settled; if (failed !== null) throw failed; return pick(); };+ return { fullStream, text: once(() => final.text), finishReason: once(() => final.finishReason), usage: once(() => final.usage).catch(() => ({})) };+}) as unknown as typeof streamText);++const provider = {+ name: 'stub', model: 'stub-model', isAvailable: () => true, getModelInstance: () => ({}), getModel: () => 'stub-model',+ generateText: async () => ({ text: 'ok' }), streamText: async function* () { yield { text: 'ok', done: true }; },+};+type ManagerDeps = ConstructorParameters<typeof BotManager>[0];+const providers = { get: () => provider, getDefault: () => provider } as unknown as ManagerDeps['providers'];+const tokenBudget = { recordUsage: () => {}, getRemaining: () => 100000, getStatusText: () => '', getUsagePercentage: () => 0 } as unknown as ManagerDeps['tokenBudget'];++type Opts = { tools: Record<string, { execute: (input: Record<string, unknown>, ctx: unknown) => Promise<unknown> }>; onStepFinish?: (step: unknown) => void; messages?: Array<{ role?: string; content: unknown; providerOptions?: unknown }> };++/** A bot that closes its run with one report tool, spending `tokens`. */+function closesWith(tool: 'bot_report' | 'bot_no_update' | 'bot_report_failure', input: Record<string, unknown>, tokens = 10) {+ mockedGenerateText.mockImplementation((async (opts: Opts) => {+ const r = await opts.tools[tool].execute(input, {});+ opts.onStepFinish?.({ usage: { inputTokens: tokens, outputTokens: 0 }, toolCalls: [{ toolName: tool, toolCallId: 't', input }], toolResults: [{ toolCallId: 't', output: { type: 'text', value: r } }] });+ return { text: '', finishReason: 'stop', usage: { inputTokens: tokens, outputTokens: 0 } };+ }) as never);+}++let root = '';+const managers: BotManager[] = [];+function makeManager(config: Partial<MercuryConfig['bots']> = {}): { manager: BotManager; store: BotStore; notified: string[] } {+ const c = getDefaultConfig() as MercuryConfig;+ c.bots.maxConcurrent = 4;+ Object.assign(c.bots, config);+ const store = new BotStore(join(root, 'bots'));+ const manager = new BotManager({ config: c, providers, tokenBudget, store, userMemoryFactory: () => null });+ const notified: string[] = [];+ manager['notify'] = async (_t: string, target: string, text: string) => { notified.push(`${target}: ${text}`); };+ managers.push(manager);+ return { manager, store, notified };+}++async function idle(manager: BotManager, id: string) {+ await vi.waitFor(() => {+ const s = manager.getStatusSummaries().find((x) => x.id === id);+ expect(s?.state === 'idle' || s?.state === 'paused').toBe(true);+ });+ await new Promise((r) => setTimeout(r, 20));+}++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bots2-'));+ mockedGenerateText.mockReset();+});++afterEach(() => {+ for (const m of managers.splice(0)) m.dispose();+ rmSync(root, { recursive: true, force: true });+});++describe('closing a run', () => {+ it('a result reaches the inbox and the bot thread, with the bot\'s own words', async () => {+ const { manager, store, notified } = makeManager();+ store.create({ id: 'scout', name: 'Scout' });+ closesWith('bot_report', { summary: 'Oxide raised a Series D.\nDetails follow.', complete: true });+ manager.enqueue('scout', { trigger: 'api', prompt: 'any news?' });+ await idle(manager, 'scout');+ const [entry] = manager.inbox.list();+ expect(entry).toMatchObject({ botId: 'scout', kind: 'result', complete: true, read: false });+ expect(entry.title).toBe('Scout: Oxide raised a Series D.');+ expect(entry.summary).toContain('Details follow.');+ expect(notified.some((n) => n.startsWith('bot:scout') && n.includes('Oxide raised a Series D.'))).toBe(true);+ expect(manager.getJournal('scout', 1)[0]).toMatchObject({ outcome: 'message', report: 'result', complete: true });+ });++ it('nothing new is recorded quietly: no inbox entry, no message, no cooldown strike', async () => {+ const { manager, store, notified } = makeManager({ routineMinGapMinutes: 0 });+ store.create({ id: 'watch', name: 'Watch', manifest: { schedules: [{ name: 'poll', cron: '0 * * * *', prompt: 'check' }] } });+ closesWith('bot_no_update', { reason: 'No new releases.' });+ for (let i = 0; i < 4; i++) {+ expect(manager.enqueue('watch', { trigger: 'cron', prompt: 'check', routineId: 'bot:watch:poll' }).accepted).toBe(true);+ await idle(manager, 'watch');+ }+ expect(manager.inbox.list()).toEqual([]);+ expect(notified.filter((n) => n.startsWith('bot:watch'))).toEqual([]);+ expect(manager.getJournal('watch', 1)[0]).toMatchObject({ outcome: 'quiet', report: 'no_update' });+ // Four quiet runs in a row are not "no outcome": the routine keeps running.+ expect(store.readRoutineState('watch').paused).toEqual({});+ });++ it('a reported failure is a failure, and the owner hears about it', async () => {+ const { manager, store } = makeManager();+ store.create({ id: 'fetcher', name: 'Fetcher' });+ closesWith('bot_report_failure', { reason: 'The API key for the news service was rejected.' });+ manager.enqueue('fetcher', { trigger: 'api', prompt: 'fetch' });+ await idle(manager, 'fetcher');+ expect(manager.getJournal('fetcher', 1)[0]).toMatchObject({ outcome: 'failed', report: 'failure' });+ expect(manager.inbox.list()[0]).toMatchObject({ kind: 'failed', summary: 'The API key for the news service was rejected.' });+ });++ it('read marks: one entry, or everything', async () => {+ const { manager, store } = makeManager();+ store.create({ id: 'scout', name: 'Scout' });+ closesWith('bot_report', { summary: 'one' });+ manager.enqueue('scout', { trigger: 'api', prompt: 'a' });+ await idle(manager, 'scout');+ closesWith('bot_report', { summary: 'two' });+ manager.enqueue('scout', { trigger: 'api', prompt: 'b' });+ await idle(manager, 'scout');+ expect(manager.inbox.unread()).toBe(2);+ manager.inbox.markRead([manager.inbox.list()[0].id]);+ expect(manager.inbox.unread()).toBe(1);+ manager.inbox.markRead();+ expect(manager.inbox.unread()).toBe(0);+ });+});++describe('guards that survive a restart', () => {+ it('a stop stays stopped after a restart, and its routines don\'t queue up', async () => {+ const first = makeManager();+ first.store.create({ id: 'writer', name: 'Writer', manifest: { schedules: [{ name: 'daily', cron: '0 9 * * *', prompt: 'write' }] } });+ await first.manager.stop('writer');+ const second = makeManager();+ expect(second.manager.enqueue('writer', { trigger: 'cron', prompt: 'write', routineId: 'bot:writer:daily' })).toMatchObject({ accepted: false, reasonCode: 'stopped' });+ second.manager.start('writer');+ const third = makeManager();+ expect(third.manager.enqueue('writer', { trigger: 'cron', prompt: 'write', routineId: 'bot:writer:daily' }).accepted).toBe(true);+ });++ it('today\'s spend is rebuilt from the journal, so a restart can\'t reset a daily budget', async () => {+ const first = makeManager();+ first.store.create({ id: 'spender', name: 'Spender' });+ closesWith('bot_report', { summary: 'done' }, 1234);+ first.manager.enqueue('spender', { trigger: 'api', prompt: 'go' });+ await idle(first.manager, 'spender');+ expect(first.manager.dailyUsage('spender').tokens).toBe(1234);+ const second = makeManager();+ expect(second.manager.dailyUsage('spender').tokens).toBe(1234);+ });++ it('the 15-minute gap between routine runs survives a restart', async () => {+ const first = makeManager();+ first.store.create({ id: 'watch', name: 'Watch', manifest: { schedules: [{ name: 'poll', cron: '*/5 * * * *', prompt: 'check' }] } });+ closesWith('bot_no_update', {});+ first.manager.enqueue('watch', { trigger: 'cron', prompt: 'check', routineId: 'bot:watch:poll' });+ await idle(first.manager, 'watch');+ const second = makeManager();+ expect(second.manager.enqueue('watch', { trigger: 'cron', prompt: 'check', routineId: 'bot:watch:poll' })).toMatchObject({ accepted: false, reasonCode: 'too_soon' });+ });++ it('a routine that fails five runs in a row is switched off until the owner starts the bot again', async () => {+ const { manager, store } = makeManager({ routineMinGapMinutes: 0 });+ store.create({ id: 'broken', name: 'Broken', manifest: { schedules: [{ name: 'job', cron: '0 * * * *', prompt: 'do it' }] } });+ closesWith('bot_report_failure', { reason: 'Login page changed.' });+ for (let i = 0; i < 5; i++) {+ expect(manager.enqueue('broken', { trigger: 'cron', prompt: 'do it', routineId: 'bot:broken:job' }).accepted).toBe(true);+ await idle(manager, 'broken');+ }+ expect(manager.enqueue('broken', { trigger: 'cron', prompt: 'do it', routineId: 'bot:broken:job' })).toMatchObject({ accepted: false, reasonCode: 'routine_paused' });+ expect(store.readRoutineState('broken').paused['bot:broken:job']?.until).toBeUndefined();+ manager.start('broken');+ expect(manager.enqueue('broken', { trigger: 'cron', prompt: 'do it', routineId: 'bot:broken:job' }).accepted).toBe(true);+ });+});++describe('prompt', () => {+ it('the stable part is sent once with a cache marker; per-run parts follow it; no duplicate tool list', async () => {+ const { manager, store } = makeManager();+ store.create({ id: 'scout', name: 'Scout' });+ let messages: Opts['messages'] = [];+ mockedGenerateText.mockImplementation((async (opts: Opts) => { messages = opts.messages; return { text: 'x', finishReason: 'stop', usage: {} }; }) as never);+ manager.enqueue('scout', { trigger: 'chat', prompt: 'hi' });+ await idle(manager, 'scout');+ const [stable, volatile] = messages!;+ expect(stable).toMatchObject({ role: 'system', providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } } });+ expect(String(stable.content)).toContain('END EVERY RUN WITH EXACTLY ONE');+ expect(String(stable.content)).not.toContain('Available tools:');+ expect(String(stable.content)).not.toContain('Token budget remaining');+ expect(volatile).toMatchObject({ role: 'system' });+ expect(String(volatile.content)).toContain('Token budget remaining');+ });++ it('two runs of the same bot share an identical stable prefix (so the cache hits)', () => {+ const input = (prompt: string, recent: string) => ({+ manifest: { id: 'b', name: 'B', enabled: true }, persona: 'You write.', prompt, mail: [], tools: {},+ sandbox: { workspace: '/w', shared: '/s' }, tokenBudget: { getRemaining: () => Math.random() }, recentRuns: recent,+ }) as unknown as Parameters<typeof buildBotSystemPrompt>[0];+ const a = buildBotSystemPrompt(input('one', 'run 1'));+ const b = buildBotSystemPrompt(input('two', 'run 1, run 2'));+ expect(a.stable).toBe(b.stable);+ expect(a.volatile).not.toBe(b.volatile);+ });+});++describe('outcome', () => {+ const sandbox = { workspace: '/w', shared: '/s' };+ it('reported failure beats everything; files beat words; nothing new is quiet', () => {+ expect(computeOutcome({ trace: [], deliveries: ['/d.md'], expects: 'work', text: '', sandbox, report: { kind: 'failure', summary: 'x' } })).toBe('failed');+ expect(computeOutcome({ trace: [], deliveries: ['/d.md'], expects: 'work', text: '', sandbox, report: { kind: 'result', summary: 'x' } })).toBe('deliverable');+ expect(computeOutcome({ trace: [], deliveries: [], expects: 'work', text: '', sandbox, report: { kind: 'no_update', summary: '' } })).toBe('quiet');+ expect(computeOutcome({ trace: [], deliveries: [], expects: 'work', text: '', sandbox, report: { kind: 'result', summary: 'A finding.' } })).toBe('message');+ expect(computeOutcome({ trace: [], deliveries: [], expects: 'work', text: 'words only', sandbox })).toBe('none');+ });+});+++describe('deliveries', () => {+ it('a text file without an extension becomes .md, and the same content delivered twice stays one file', () => {+ const { manager, store } = makeManager();+ store.create({ id: 'writer', name: 'Writer' });+ const sandbox = store.sandboxDir('writer');+ mkdirSync(sandbox, { recursive: true });+ writeFileSync(join(sandbox, 'Trend Poll'), '# Poll\nresults');+ const first = manager.deliver('writer', join(sandbox, 'Trend Poll'), { final: true });+ expect(first.accepted).toBe(true);+ expect(first.path).toMatch(/\.md$/);+ writeFileSync(join(sandbox, 'again.md'), '# Poll\nresults');+ const second = manager.deliver('writer', join(sandbox, 'again.md'), { final: true });+ expect(second.path).toBe(first.path);+ });+});diff --git a/src/bots/fleet-tasks.test.ts b/src/bots/fleet-tasks.test.tsindex f089919e..3f7de0a0 100644--- a/src/bots/fleet-tasks.test.ts+++ b/src/bots/fleet-tasks.test.ts@@ -39,6 +39,11 @@ const stubProvider = { name: 'stub', model: 'stub-model', isAvailable: () => truconst providers = { get: (name?: string) => (name === 'cheap' ? { ...stubProvider, name: 'cheap' } : name === 'stub' ? stubProvider : undefined), getDefault: () => stubProvider } as never;const tokenBudget = { recordUsage: () => {}, getRemaining: () => 100000, canAfford: () => true, getStatusText: () => 'ok', getUsagePercentage: () => 0 } as never;+/** The bot's system prompt as the model sees it: a `system` string, or leading system messages (cached prefix + per-run part). */+function systemText(opts: { system?: string; messages?: Array<{ role?: string; content: unknown }> }): string {+ return opts.system ?? (opts.messages ?? []).filter((m) => m.role === 'system').map((m) => String(m.content)).join('\n');+}+describe('fleet tasks (ADR-021)', () => {let root: string;let store: BotStore;@@ -239,7 +244,7 @@ describe('fleet tasks (ADR-021)', () => {it('continuity: the bot sees its recent runs and its own state note instead of writing records', async () => {const prompts: string[] = [];- mockedGenerateText.mockImplementation((async (opts: StepOpts & { system?: string }) => { prompts.push(opts.system ?? ''); return reply('done something'); }) as never);+ mockedGenerateText.mockImplementation((async (opts: StepOpts & { system?: string }) => { prompts.push(systemText(opts)); return reply('done something'); }) as never);store.writeState('alpha', 'Working on: the Oxide dossier. Pending: fact-check.');manager.enqueue('alpha', { trigger: 'chat', prompt: 'first' });await idle('alpha');@@ -409,6 +414,8 @@ describe('liveness contract', () => {});it('a no-outcome cooldown ends by itself, backs off, and resets after a productive run', async () => {+ // Back-to-back runs of one routine: lift the 15-minute floor for this test.+ (manager as unknown as { config: MercuryConfig }).config.bots.routineMinGapMinutes = 0;const alerts: string[] = [];manager.setAlert(async (m) => { alerts.push(m); });store.update('watch', m => { m.schedules = [{ name: 'cycle', cron: '0 * * * *', prompt: 'cycle' }]; });@@ -451,13 +458,15 @@ describe('liveness contract', () => {expect(store.readRoutineState('watch').pauseCount?.['bot:watch:cycle']).toBeUndefined();});- it('a cadence declared in bot.yaml is honoured as written; bot-created routines get the 30-minute floor', async () => {+ it('every routine waits at least 15 minutes between runs, the owner\'s own too; bot-created routines get the 30-minute floor', async () => {mockedGenerateText.mockImplementation((async () => reply('ok')) as never);store.update('watch', m => { m.schedules = [{ name: 'fast', cron: '*/5 * * * *', prompt: 'x' }]; });expect(manager.enqueue('watch', { trigger: 'cron', prompt: 'fast 1', routineId: 'bot:watch:fast' }).accepted).toBe(true);await idle('watch');- expect(manager.enqueue('watch', { trigger: 'cron', prompt: 'fast 2', routineId: 'bot:watch:fast' }).accepted).toBe(true);- await idle('watch');+ // A 5-minute cron on a lead spent hundreds of millions of tokens: the floor applies to it too.+ expect(manager.enqueue('watch', { trigger: 'cron', prompt: 'fast 2', routineId: 'bot:watch:fast' })).toMatchObject({ accepted: false, reasonCode: 'too_soon' });+ // …and survives a restart: the last end is kept with the routine.+ expect(store.readRoutineState('watch').lastEnd?.['bot:watch:fast']).toBeTruthy();expect(manager.enqueue('watch', { trigger: 'cron', prompt: 'self 1', routineId: 'bot:watch:routine-self' }).accepted).toBe(true);await idle('watch');expect(manager.enqueue('watch', { trigger: 'cron', prompt: 'self 2', routineId: 'bot:watch:routine-self' })).toMatchObject({ accepted: false, reasonCode: 'too_soon' });diff --git a/src/bots/inbox.ts b/src/bots/inbox.tsnew file mode 100644index 00000000..f3bb6c71--- /dev/null+++ b/src/bots/inbox.ts@@ -0,0 +1,155 @@+import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { atomicWrite } from './store.js';+import { logger } from '../utils/logger.js';++/**+ * The owner's bot inbox (Bots 2.0): what the bots did for you, kept until you+ * read it, whether or not anything was connected when it happened.+ *+ * One entry per run that matters to the owner:+ * result a finding, an answer or delivered files (the bot's bot_report)+ * failed the bot said it couldn't do the job (bot_report_failure)+ * needs-you the run failed for good (dead-lettered) and waits on you+ * Quiet runs (bot_no_update), crew work handed to a lead, and retries are+ * not here: the journal keeps them.+ */++export type BotInboxKind = 'result' | 'failed' | 'needs-you';++export interface BotInboxEntry {+ id: string;+ botId: string;+ botName: string;+ runId: string;+ kind: BotInboxKind;+ /** Short line for lists and notifications. */+ title: string;+ /** What the bot reported (or why it failed), capped. */+ summary: string;+ /** Delivered files (absolute paths), newest run only. */+ files: string[];+ /** The bot said the job is finished, not just progress. */+ complete?: boolean;+ /** Why it needs you (reason code) for needs-you entries. */+ reasonCode?: string;+ at: number;+ read: boolean;+}++const FILE = 'inbox.jsonl';+const MAX_SUMMARY = 4000;+/** Rotate when the file grows past this; the newest entries are kept. */+const ROTATE_BYTES = 2 * 1024 * 1024;+const KEEP_AFTER_ROTATE = 500;++export class BotInbox {+ private readonly path: string;+ private readonly readPath: string;+ private listeners = new Set<(e: BotInboxEntry) => void>();++ constructor(botsRoot: string) {+ this.path = join(botsRoot, FILE);+ // Read marks live apart from the append-only log, so appends never rewrite it.+ this.readPath = join(botsRoot, 'inbox-read.json');+ mkdirSync(botsRoot, { recursive: true });+ }++ /** A new entry arrives (the web stream turns it into a desktop notification). */+ onEntry(listener: (e: BotInboxEntry) => void): () => void {+ this.listeners.add(listener);+ return () => { this.listeners.delete(listener); };+ }++ add(input: Omit<BotInboxEntry, 'id' | 'at' | 'read' | 'summary'> & { summary: string; at?: number }): BotInboxEntry {+ const entry: BotInboxEntry = {+ ...input,+ id: randomUUID().slice(0, 12),+ summary: input.summary.length > MAX_SUMMARY ? `${input.summary.slice(0, MAX_SUMMARY)}…` : input.summary,+ title: input.title.slice(0, 160),+ at: input.at ?? Date.now(),+ read: false,+ };+ try {+ this.rotateIfBig();+ appendFileSync(this.path, `${JSON.stringify(entry)}\n`, 'utf-8');+ } catch (err) {+ logger.warn({ err: (err as Error)?.message, botId: entry.botId }, 'Could not write the bot inbox');+ }+ for (const l of this.listeners) {+ try { l(entry); } catch { /* a listener's problem */ }+ }+ return entry;+ }++ /** Newest first. */+ list(opts: { limit?: number; botId?: string; unreadOnly?: boolean } = {}): BotInboxEntry[] {+ const read = this.readMarks();+ const out: BotInboxEntry[] = [];+ for (const e of this.all().reverse()) {+ if (opts.botId && e.botId !== opts.botId) continue;+ const isRead = read.all >= e.at || read.ids.has(e.id);+ if (opts.unreadOnly && isRead) continue;+ out.push({ ...e, read: isRead });+ if (out.length >= (opts.limit ?? 100)) break;+ }+ return out;+ }++ unread(botId?: string): number {+ return this.list({ unreadOnly: true, botId, limit: 10_000 }).length;+ }++ /** Unread entries per bot, in one pass (the roster asks for every bot at once). */+ unreadByBot(): Map<string, number> {+ const out = new Map<string, number>();+ for (const e of this.list({ unreadOnly: true, limit: 10_000 })) out.set(e.botId, (out.get(e.botId) ?? 0) + 1);+ return out;+ }++ /** Mark entries read: some ids, or everything up to now. */+ markRead(ids?: string[]): void {+ const read = this.readMarks();+ if (!ids) {+ read.all = Date.now();+ read.ids.clear();+ } else {+ for (const id of ids) read.ids.add(id);+ }+ try {+ atomicWrite(this.readPath, JSON.stringify({ all: read.all, ids: [...read.ids].slice(-2000) }) + '\n');+ } catch (err) {+ logger.warn({ err: (err as Error)?.message }, 'Could not save inbox read marks');+ }+ }++ private all(): BotInboxEntry[] {+ if (!existsSync(this.path)) return [];+ const out: BotInboxEntry[] = [];+ for (const line of readFileSync(this.path, 'utf-8').split('\n')) {+ if (!line.trim()) continue;+ try { out.push(JSON.parse(line) as BotInboxEntry); } catch { /* a torn last line */ }+ }+ return out;+ }++ private readMarks(): { all: number; ids: Set<string> } {+ try {+ const raw = JSON.parse(readFileSync(this.readPath, 'utf-8')) as { all?: number; ids?: string[] };+ return { all: Number(raw.all) || 0, ids: new Set(raw.ids ?? []) };+ } catch {+ return { all: 0, ids: new Set() };+ }+ }++ private rotateIfBig(): void {+ try {+ if (!existsSync(this.path) || statSync(this.path).size < ROTATE_BYTES) return;+ const keep = this.all().slice(-KEEP_AFTER_ROTATE);+ const tmp = `${this.path}.tmp`;+ atomicWrite(tmp, keep.map((e) => JSON.stringify(e)).join('\n') + '\n');+ renameSync(tmp, this.path);+ } catch { /* rotation is housekeeping */ }+ }+}diff --git a/src/bots/permission-tiers.ts b/src/bots/permission-tiers.tsindex 586787aa..683b4f38 100644--- a/src/bots/permission-tiers.ts+++ b/src/bots/permission-tiers.ts@@ -70,4 +70,23 @@ export function tierPermissionsFile(tier: PermissionTier): BotPermissionsFile {*/export function applyPermissionTier(manifest: { tools?: { allow?: string[]; deny?: string[] } }, tier: PermissionTier): void {manifest.tools = { ...(manifest.tools ?? {}), deny: [...PERMISSION_TIERS[tier].deny] };-}\ No newline at end of file+}++/**+ * Which tier a permissions.yaml matches, or 'custom' when it was edited by+ * hand (extra paths, an allow list, a different deny list). The app shows the+ * tier by name, and 'custom' as exactly that.+ */+export function detectTier(perms: BotPermissionsFile | null | undefined): PermissionTier | 'custom' {+ if (!perms) return 'custom';+ const key = (f: BotPermissionsFile) => JSON.stringify({+ deny: [...(f.tools?.deny ?? [])].sort(),+ allow: [...(f.tools?.allow ?? [])].sort(),+ paths: (f.paths ?? []).map((p) => `${p.scope}:${p.read ? 'r' : ''}${p.write ? 'w' : ''}${p.execute ? 'x' : ''}`).sort(),+ });+ const mine = key(perms);+ for (const tier of Object.keys(PERMISSION_TIERS) as PermissionTier[]) {+ if (key(tierPermissionsFile(tier)) === mine) return tier;+ }+ return 'custom';+}diff --git a/src/bots/permissions-single-source.test.ts b/src/bots/permissions-single-source.test.tsindex 8c77816d..b4aa9ac1 100644--- a/src/bots/permissions-single-source.test.ts+++ b/src/bots/permissions-single-source.test.ts@@ -70,12 +70,13 @@ describe('permissions.yaml — single source of truth', () => {expect(readonly.paths).toEqual([{ scope: 'self', read: true, write: true, execute: false }]);});- it('the tool gate comes from permissions.yaml, overriding any legacy manifest block', () => {+ it('the tool gate comes from permissions.yaml, and a deny left in a legacy manifest block still applies', () => {const all = { read_file: {}, run_command: {}, write_file: {} } as any;const manifest = { tools: { deny: ['run_command'] } } as any;- // permissions.yaml is the single source: its deny wins over bot.yaml.+ // Deny wins from either source: a bot.yaml deny the owner wrote is never+ // silently overridden by a permissions.yaml that doesn't repeat it.let out = filterBotTools(all, manifest, { tools: { deny: ['write_file'] } });- expect(Object.keys(out).sort()).toEqual(['read_file', 'run_command']);+ expect(Object.keys(out).sort()).toEqual(['read_file']);// No permissions.tools + explicit legacy manifest block → honored.out = filterBotTools(all, manifest, {});expect(Object.keys(out).sort()).toEqual(['read_file', 'write_file']);@@ -182,6 +183,23 @@ describe('fleet permission inheritance (crew runs on the lead\'s permissions)',});});+describe('bot tool filter', () => {+ const bare = { id: 'x' } as unknown as Parameters<typeof filterBotTools>[1];+ const toolset = (names: string[]) => Object.fromEntries(names.map((n) => [n, {}])) as Parameters<typeof filterBotTools>[0];+ it('Spotify, GitHub and git tools are opt-in by group: off unless the gate names them', () => {+ const all = toolset(['read_file', 'spotify_play', 'spotify_pause', 'github_api', 'create_pr', 'git_status', 'web_search']);+ const deny = { tools: { deny: [] } };+ expect(Object.keys(filterBotTools(all, bare, deny)).sort()).toEqual(['read_file', 'web_search']);+ const withGroups = { tools: { allow: ['read_file', 'web_search', 'spotify', 'git'] } };+ expect(Object.keys(filterBotTools(all, bare, withGroups)).sort()).toEqual(['git_status', 'read_file', 'spotify_pause', 'spotify_play', 'web_search']);+ expect(Object.keys(filterBotTools(all, bare, { tools: { deny: [], allow: [] } }))).not.toContain('create_pr');+ });++ it('a bot never gets dispatch_bot (that is how the owner wakes bots)', () => {+ expect(Object.keys(filterBotTools(toolset(['dispatch_bot', 'read_file']), bare, { tools: { deny: [] } }))).toEqual(['read_file']);+ });+});+function materializedEquals(a: unknown, b: unknown): boolean {return JSON.stringify(a) === JSON.stringify(b);-}\ No newline at end of file+}diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.tsindex 928bf634..adc8f004 100644--- a/src/bots/registry-factory.ts+++ b/src/bots/registry-factory.ts@@ -32,8 +32,25 @@ const ALWAYS_STRIPPED = new Set(['send_message', // channel messaging belongs to the owning surfaces'send_file','bot_send', // replaced by the bot-scoped instance after filtering+ 'dispatch_bot', // the owner's way to wake a bot; a bot uses bot_send]);+/**+ * Tool groups a bot gets only when its gate names them (an allow entry with the+ * group name, e.g. "spotify", or a tool's own name). Every tool schema is re-sent+ * on every step, and a writer bot has no use for 15 Spotify controls: off by+ * default, they cost nothing.+ */+const OPT_IN_GROUPS: Array<{ group: string; match: (name: string) => boolean }> = [+ { group: 'spotify', match: (n) => n.startsWith('spotify_') },+ { group: 'github', match: (n) => ['github_api', 'create_issue', 'list_issues', 'create_pr', 'review_pr'].includes(n) },+ { group: 'git', match: (n) => n.startsWith('git_') },+];++function optInGroup(name: string): string | undefined {+ return OPT_IN_GROUPS.find((g) => g.match(name))?.group;+}+export interface BotRegistryDeps {botId: string;manifest: BotManifest;@@ -150,7 +167,10 @@ export function filterBotTools(all: Record<string, any>, manifest: BotManifest,?? (explicitManifestTools ? manifest.tools : undefined)?? { deny: [...BOT_DANGEROUS_TOOLS] };const allow = gate.allow ?? [];- const deny = new Set(gate.deny ?? []);+ // Deny always wins, from either source: a bot.yaml that still lists denied+ // tools must not be silently overridden by a permissions.yaml without them+ // (both are the owner's word; the stricter one applies).+ const deny = new Set([...(gate.deny ?? []), ...(explicitManifestTools ? manifest.tools?.deny ?? [] : [])]);const out: Record<string, any> = {};for (const [name, tool] of Object.entries(all)) {if (ALWAYS_STRIPPED.has(name) || isMcpToolName(name)) continue;@@ -163,7 +183,9 @@ export function filterBotTools(all: Record<string, any>, manifest: BotManifest,out[name] = tool;continue;}- if (allow.length > 0 && !allow.includes(name)) continue;+ const group = optInGroup(name);+ if (group && !allow.includes(group) && !allow.includes(name)) continue;+ if (allow.length > 0 && !allow.includes(name) && !(group && allow.includes(group))) continue;out[name] = tool;}return out;diff --git a/src/bots/store.ts b/src/bots/store.tsindex 206237d6..e7b9df6e 100644--- a/src/bots/store.ts+++ b/src/bots/store.ts@@ -30,6 +30,8 @@ export const BOT_TRANSCRIPTS_DIRNAME = 'transcripts';export const BOT_STATE_FILENAME = 'state.md';/** Routine state (paused routines, no-outcome streaks) — ADR-020. */export const BOT_ROUTINE_STATE_FILENAME = 'routine-state.json';+/** Fleet-level list of bots the owner stopped. */+export const BOT_HELD_FILENAME = 'stopped.json';/*** Data directories that live INSIDE a bot's profile dir but are never bot* profiles themselves. The roster scan does not descend into them: bots@@ -49,6 +51,10 @@ export interface BotRoutineState {noOutcomeStreak: Record<string, number>;/** Routine key → how many times it has been paused (cooldown backoff); reset by a productive run. */pauseCount?: Record<string, number>;+ /** Routine key → when its last run ended (ISO): the minimum gap survives a restart. */+ lastEnd?: Record<string, string>;+ /** Routine key → consecutive failed runs; at the limit the routine is switched off. */+ failStreak?: Record<string, number>;}/**@@ -200,7 +206,7 @@ falls outside it.- Include the evidence (links, file paths, numbers) behind each claim.`;-function atomicWrite(filePath: string, content: string, mode: number = 0o600): void {+export 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);@@ -312,10 +318,29 @@ export class BotStore {atomicWrite(file, state + '\n');}+ /** Bots the owner stopped (/bots stop, the app's Stop). Durable: a restart must not undo a stop. */+ readHeld(): Set<string> {+ try {+ const raw = JSON.parse(readFileSync(join(this.botsRoot, BOT_HELD_FILENAME), 'utf-8'));+ return new Set(Array.isArray(raw) ? raw.filter((x: unknown): x is string => typeof x === 'string') : []);+ } catch {+ return new Set();+ }+ }++ writeHeld(held: Set<string>): void {+ try {+ mkdirSync(this.botsRoot, { recursive: true });+ atomicWrite(join(this.botsRoot, BOT_HELD_FILENAME), JSON.stringify([...held].sort()) + '\n');+ } catch (err) {+ logger.warn({ err: (err as Error)?.message }, 'Could not persist stopped bots');+ }+ }+readRoutineState(id: string): BotRoutineState {try {const raw = JSON.parse(readFileSync(join(this.botDir(id), BOT_ROUTINE_STATE_FILENAME), 'utf-8'));- return { paused: raw.paused ?? {}, noOutcomeStreak: raw.noOutcomeStreak ?? {}, pauseCount: raw.pauseCount ?? {} };+ return { paused: raw.paused ?? {}, noOutcomeStreak: raw.noOutcomeStreak ?? {}, pauseCount: raw.pauseCount ?? {}, lastEnd: raw.lastEnd ?? {}, failStreak: raw.failStreak ?? {} };} catch {return { paused: {}, noOutcomeStreak: {}, pauseCount: {} };}diff --git a/src/bots/types.ts b/src/bots/types.tsindex b887eb83..61f2a286 100644--- a/src/bots/types.ts+++ b/src/bots/types.ts@@ -225,8 +225,12 @@ export interface BotRunRecord {toolCalls?: number;/** Largest single-step prompt the provider saw. */peakInputTokens?: number;- /** What the tool trace proved: deliverable | action | delegated | message | none. */+ /** What the run did: deliverable | action | delegated | message | quiet | failed | none. */outcome?: string;+ /** How the bot closed the run (Bots 2.0): result | no_update | failure. */+ report?: 'result' | 'no_update' | 'failure';+ /** The bot said the job is finished, not just progress. */+ complete?: boolean;deliverables?: string[];/** The reply claimed delivery/execution with no matching tool call. */claimedWithoutAction?: boolean;@@ -256,4 +260,12 @@ export interface BotStatusSummary {routinePausedUntil?: number;/** The bot has a custom avatar (`GET /api/bots/:id/avatar`); clients draw a monogram otherwise. */hasAvatar?: boolean;+ /** Unread inbox entries from this bot (Bots 2.0). */+ unread?: number;+ /** Its permission tier, or 'custom' for a hand-edited permissions.yaml. */+ tier?: string;+ /** Stopped by the owner (durable until Start). */+ stopped?: boolean;+ /** One-line description, for lists. */+ description?: string;}\ No newline at end of filediff --git a/src/utils/config.ts b/src/utils/config.tsindex aa7f5bf9..b0f5f5e7 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -247,6 +247,8 @@ export interface MercuryConfig {suggestedDailyTokenBudget?: number;/** Fleet-wide daily token cap across all bots (0 = unlimited). ADR-020. */fleetDailyTokenBudget?: number;+ /** Fewest minutes between two runs of any bot routine (default 15). */+ routineMinGapMinutes?: number;/** Owner-visible folder for finished results (default: ~/Documents/Mercury). */deliverablesDir?: string;retention: {diff --git a/src/web/api/bots.ts b/src/web/api/bots.tsindex ff31fae9..b0d7e1b2 100644--- a/src/web/api/bots.ts+++ b/src/web/api/bots.ts@@ -28,7 +28,26 @@ app.get('/api/bots', (c: any) => {if (!botManager) {return c.json({ bots: [], available: false });}- return c.json({ bots: botManager.getStatusSummaries(), queue: botManager.queue.counts(), available: true });+ return c.json({ bots: botManager.getStatusSummaries(), queue: botManager.queue.counts(), available: true, unread: botManager.inbox.unread() });+});++// The owner's inbox (Bots 2.0): results, reported failures and runs that need+// the owner, newest first. `?unread=1` for unread only, `?bot=<id>` for one bot.+app.get('/api/bots/inbox', (c: Context) => {+ if (!botManager) return c.json({ entries: [], unread: 0, available: false });+ const limit = Math.max(1, Math.min(500, Number(c.req.query('limit')) || 100));+ const botId = c.req.query('bot') || undefined;+ const entries = botManager.inbox.list({ limit, botId, unreadOnly: c.req.query('unread') === '1' });+ return c.json({ entries, unread: botManager.inbox.unread(botId), available: true });+});++// Mark read: { ids: [...] } for some entries, {} for everything.+app.post('/api/bots/inbox/read', async (c: Context) => {+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);+ const body = (await c.req.json().catch(() => ({}))) as { ids?: unknown };+ const ids = Array.isArray(body.ids) ? body.ids.filter((x): x is string => typeof x === 'string').slice(0, 1000) : undefined;+ botManager.inbox.markRead(ids);+ return c.json({ ok: true, unread: botManager.inbox.unread() });});// Onboard a bot@@ -112,6 +131,8 @@ app.get('/api/bots/events', (c: any) => {rosterSseClients.add(client);const unsubscribe = bm.onBotActivity((ev) => client.send('bot_activity', ev));+ // A new inbox entry: the desktop turns it into a notification.+ const unsubscribeInbox = bm.inbox.onEntry((entry) => client.send('bot_inbox', entry));const keepalive = setInterval(() => {try { controller.enqueue(encoder.encode(': keepalive\n\n')); } catch { clearInterval(keepalive); }@@ -120,6 +141,7 @@ app.get('/api/bots/events', (c: any) => {c.req.raw.signal?.addEventListener('abort', () => {clearInterval(keepalive);unsubscribe();+ unsubscribeInbox();rosterSseClients.delete(client);});},