Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(bots): bots ask the owner mid-run instead of failing outright

Salman Qureshi12ed8a9fda97
diff --git a/DECISIONS.md b/DECISIONS.md
index e7dd1e05..2848fcd2 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -323,6 +323,6 @@
- **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`).
+ - **Permissions**: the roster reports each bot's tier (or `custom`), so a bot on Full access is visible as such. (`permissions.yaml` stays the single source: the deny list on every loaded `bot.yaml` is the materialized default, not an owner choice.)
- **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/approvals.ts b/src/bots/approvals.ts
new file mode 100644
index 00000000..26562fd1
--- /dev/null
+++ b/src/bots/approvals.ts
@@ -0,0 +1,101 @@
+import { randomUUID } from 'node:crypto';
+
+/**
+ * Bots asking the owner mid-run (Bots 2.0). A bot that needs something
+ * outside its grants — a command, a file outside its folders — waits here
+ * for the owner's answer, for a while: nobody answering in time is a "no",
+ * the same as a bot that never asked. Pending questions live only as long as
+ * the run that asked; a restart ends the run and so the question.
+ */
+
+export type BotApprovalAnswer = 'yes' | 'always' | 'no';
+
+export interface BotApproval {
+ id: string;
+ botId: string;
+ botName: string;
+ /** The job (run) that asked. */
+ runId: string;
+ /** What it wants to do, as the permission layer said it ("Run command: …", "Write to file: …"). */
+ prompt: string;
+ at: number;
+ expiresAt: number;
+}
+
+type Event = { type: 'new' | 'settled'; approval: BotApproval; answer?: BotApprovalAnswer; by?: 'owner' | 'timeout' };
+
+export class BotApprovals {
+ private pending = new Map<string, { approval: BotApproval; resolve: (a: BotApprovalAnswer) => void; timer: ReturnType<typeof setTimeout> }>();
+ private listeners = new Set<(e: Event) => void>();
+
+ onChange(listener: (e: Event) => void): () => void {
+ this.listeners.add(listener);
+ return () => { this.listeners.delete(listener); };
+ }
+
+ /** Ask and wait. Resolves the owner's answer, or "no" after `waitMs`. */
+ ask(input: Omit<BotApproval, 'id' | 'at' | 'expiresAt'>, waitMs: number): { approval: BotApproval; answer: Promise<BotApprovalAnswer> } {
+ const at = Date.now();
+ const approval: BotApproval = { ...input, id: randomUUID().slice(0, 12), at, expiresAt: at + waitMs };
+ const answer = new Promise<BotApprovalAnswer>((resolve) => {
+ const timer = setTimeout(() => this.settle(approval.id, 'no', 'timeout'), waitMs);
+ timer.unref?.();
+ this.pending.set(approval.id, { approval, resolve, timer });
+ });
+ this.emit({ type: 'new', approval });
+ return { approval, answer };
+ }
+
+ /** The owner's answer. False when the question is gone (answered, timed out, run ended). */
+ answer(id: string, answer: BotApprovalAnswer): boolean {
+ return this.settle(id, answer, 'owner');
+ }
+
+ /** A run ended (finished, halted, crashed): its open questions are moot. */
+ cancelRun(runId: string): void {
+ for (const [id, p] of this.pending) if (p.approval.runId === runId) this.settle(id, 'no', 'timeout');
+ }
+
+ list(botId?: string): BotApproval[] {
+ return [...this.pending.values()].map((p) => p.approval).filter((a) => !botId || a.botId === botId).sort((a, b) => a.at - b.at);
+ }
+
+ private settle(id: string, answer: BotApprovalAnswer, by: 'owner' | 'timeout'): boolean {
+ const p = this.pending.get(id);
+ if (!p) return false;
+ this.pending.delete(id);
+ clearTimeout(p.timer);
+ p.resolve(answer);
+ this.emit({ type: 'settled', approval: p.approval, answer, by });
+ return true;
+ }
+
+ private emit(e: Event): void {
+ for (const l of this.listeners) {
+ try { l(e); } catch { /* a listener's problem */ }
+ }
+ }
+}
+
+/** Commands whose "always" must never widen to the whole family: they can run anything. */
+const NEVER_GENERALISE = new Set(['sudo', 'su', 'sh', 'bash', 'zsh', 'fish', 'dash', 'env', 'xargs', 'eval', 'exec', 'nohup', 'time', 'nice', 'doas', 'pwsh', 'powershell', 'cmd', 'node', 'python', 'python3', 'ruby', 'perl', 'deno', 'bun']);
+
+/**
+ * What "always" adds to the bot's own permissions for this question: a command
+ * pattern for its allow list, or a path grant. Null when it can't be made
+ * durable (the owner's yes still applies to this run).
+ */
+export function durableGrant(prompt: string): { command: string } | { path: string; write: boolean } | null {
+ const cmd = /^Run command: ([\s\S]+)$/.exec(prompt);
+ if (cmd) {
+ const command = cmd[1].trim();
+ // A chain or pipeline is approved exactly as written, never as a family.
+ if (/[;&|`$<>]/.test(command)) return { command };
+ const base = command.split(/\s+/)[0] ?? '';
+ if (!base || NEVER_GENERALISE.has(base.replace(/^.*\//, ''))) return { command };
+ return { command: `${base} *` };
+ }
+ const file = /^(Write to file|Read file): (.+)$/.exec(prompt);
+ if (file) return { path: file[2].trim(), write: file[1] === 'Write to file' };
+ return null;
+}
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index b618f0c0..bff34ae6 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -12,6 +12,7 @@ import type { CapabilityRegistry } from '../capabilities/registry.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
import { UserMemoryStore as UserMemoryStoreImpl } from '../memory/user-memory.js';
import { BotInbox } from './inbox.js';
+import { BotApprovals, durableGrant } from './approvals.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';
@@ -242,6 +243,8 @@ export class BotManager {
private dueTimer?: ReturnType<typeof setInterval>;
/** What the bots did for the owner, kept until read (Bots 2.0). */
readonly inbox: BotInbox;
+ /** Bots asking the owner mid-run, waiting for an answer (Bots 2.0). */
+ readonly approvals = new BotApprovals();
/** job id → how many hand-offs deep it is (owner-started work is 0). */
private jobDepth = new Map<string, number>();
/** running job id → tasks it has handed off so far. */
@@ -566,6 +569,50 @@ export class BotManager {
return { ok: true, batchId: batch.id, tasks: out };
}
+ /**
+ * A bot wants something outside its grants. The question goes to the
+ * owner's inbox (and their phone, if an alert channel is set up) and the run
+ * waits for the answer; no answer in `bots.approvalWaitMinutes` (default 10)
+ * is a no. "Always" goes into this bot's own permissions file, never the
+ * global one.
+ */
+ private async askOwner(botId: string, prompt: string): Promise<string> {
+ const manifest = this.store.get(botId);
+ const runId = [...(this.running.get(botId) ?? [])][0];
+ if (!manifest || !runId) return 'no';
+ const minutes = Math.max(1, Math.min(60, this.config.bots?.approvalWaitMinutes ?? 10));
+ const { approval, answer } = this.approvals.ask({ botId, botName: manifest.name, runId, prompt }, minutes * 60_000);
+ const what = prompt.split('\n')[0];
+ this.emitBotActivity({ botId, jobId: runId, kind: 'step', label: 'Waiting for your approval', stepIndex: 0, elapsedMs: 0 });
+ const entry = this.inbox.add({
+ botId, botName: manifest.name, runId, kind: 'needs-you', approvalId: approval.id, files: [],
+ title: `${manifest.name} asks: ${what.slice(0, 120)}`,
+ summary: `${prompt}\n\nThe run is waiting for your answer. Without one in ${minutes} minute${minutes === 1 ? '' : 's'}, it's refused.`,
+ });
+ if (this.alert) {
+ void this.alert(`🔐 **${manifest.name}** asks: ${what}. Answer in Mercury Desktop (Bots → Inbox) within ${minutes} min, or it's refused.`).catch(() => {});
+ }
+ const result = await answer;
+ this.inbox.markRead([entry.id]);
+ if (result === 'always') this.persistGrant(botId, prompt);
+ logger.info({ botId, runId, answer: result, what: what.slice(0, 80) }, 'Bot approval answered');
+ return result;
+ }
+
+ /** "Always": make the owner's yes part of this bot's permissions.yaml. */
+ private persistGrant(botId: string, prompt: string): void {
+ const grant = durableGrant(prompt);
+ if (!grant) return;
+ const perms = this.store.readPermissions(botId);
+ if ('command' in grant) {
+ perms.autoApproveCommands = [...new Set([...(perms.autoApproveCommands ?? []), grant.command])];
+ } else {
+ perms.paths = mergePathScopes(perms.paths, [{ scope: grant.path, read: true, write: grant.write }]);
+ }
+ this.store.writePermissions(botId, perms);
+ logger.info({ botId, grant }, 'Owner granted a bot permission permanently');
+ }
+
/**
* May `requester` hand off `count` more tasks now? Work nests at most
* MAX_HANDOFF_DEPTH deep (a lead's crew can't keep delegating downwards
@@ -1204,6 +1251,7 @@ export class BotManager {
if (heartbeat) clearInterval(heartbeat);
running.delete(job.id);
this.jobFanout.delete(job.id);
+ this.approvals.cancelRun(job.id);
this.aborts.delete(`${botId}:${job.id}`);
if (running.size === 0) this.activity.delete(botId);
// Mail-arrival race: a reply (e.g. a crew's task result) delivered
@@ -1360,6 +1408,8 @@ export class BotManager {
sandbox: { workspace: this.store.sandboxDir(botId), shared: this.store.sharedSandboxDir() },
userMemory: this.userMemoryFor(botId, manifest),
config: this.config,
+ // Outside its grants the bot asks the owner (and waits a while) instead of failing outright.
+ ask: (prompt) => this.askOwner(botId, prompt),
});
// Filter FIRST (strips interactive/global-mutation tools and applies the
// permissions.yaml tool gate), THEN add the bot-specific tools —
@@ -1762,6 +1812,7 @@ export class BotManager {
const hadRunning = !!running && running.size > 0;
for (const id of running ?? []) {
if (jobId && id !== jobId) continue;
+ this.approvals.cancelRun(id);
this.aborts.get(`${botId}:${id}`)?.abort();
}
// Queued-but-not-started jobs leave the in-memory lane; their durable rows
diff --git a/src/bots/bots2.test.ts b/src/bots/bots2.test.ts
index 6bf6c4d9..7aa1df1b 100644
--- a/src/bots/bots2.test.ts
+++ b/src/bots/bots2.test.ts
@@ -309,3 +309,73 @@ describe('hand-off limits', () => {
expect((more as { error: string }).error).toMatch(/at most 12 tasks/);
});
});
+
+describe('asking the owner', () => {
+ it('a command outside its grants waits for the owner; "always" goes into the bot\'s own permissions', async () => {
+ const { manager, store } = makeManager();
+ store.create({ id: 'ops', name: 'Ops' });
+ store.writePermissions('ops', { paths: [{ scope: 'self', read: true, write: true, execute: true }], tools: { deny: [] } });
+ const asked: string[] = [];
+ manager.approvals.onChange((e) => {
+ if (e.type !== 'new') return;
+ asked.push(e.approval.prompt);
+ // The owner answers from the app.
+ setTimeout(() => manager.approvals.answer(e.approval.id, 'always'), 10);
+ });
+ let commandResult = '';
+ mockedGenerateText.mockImplementation((async (opts: Opts) => {
+ commandResult = String(await opts.tools.run_command.execute({ command: 'echo approved | cat' }, {}));
+ const r = await opts.tools.bot_report.execute({ summary: 'Ran it.' }, {});
+ opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [{ toolName: 'bot_report', toolCallId: 'r' }], toolResults: [{ toolCallId: 'r', output: { type: 'text', value: r } }] });
+ return { text: '', finishReason: 'stop', usage: {} };
+ }) as never);
+ manager.enqueue('ops', { trigger: 'api', prompt: 'run the check' });
+ await idle(manager, 'ops');
+ expect(asked).toEqual(['Run command: echo approved | cat']);
+ expect(commandResult).toContain('approved');
+ // A chain is remembered exactly as written, never as a whole family of commands.
+ expect(store.readPermissions('ops').autoApproveCommands).toEqual(['echo approved | cat']);
+ // The question was an inbox entry; answered, it's read.
+ const q = manager.inbox.list().find((e) => e.approvalId);
+ expect(q).toMatchObject({ kind: 'needs-you', read: true });
+ expect(q!.title).toBe('Ops asks: Run command: echo approved | cat');
+ });
+
+ it('no answer in time is a no, and the run carries on without it', async () => {
+ const { manager, store } = makeManager({ approvalWaitMinutes: 1 });
+ store.create({ id: 'ops', name: 'Ops' });
+ store.writePermissions('ops', { paths: [{ scope: 'self', read: true, write: true, execute: true }], tools: { deny: [] } });
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ let commandResult = '';
+ mockedGenerateText.mockImplementation((async (opts: Opts) => {
+ const pending = opts.tools.run_command.execute({ command: 'echo nope | cat' }, {});
+ await vi.advanceTimersByTimeAsync(61_000);
+ commandResult = String(await pending);
+ const r = await opts.tools.bot_report_failure.execute({ reason: 'Not allowed to run the check.' }, {});
+ opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [{ toolName: 'bot_report_failure', toolCallId: 'r' }], toolResults: [{ toolCallId: 'r', output: { type: 'text', value: r } }] });
+ return { text: '', finishReason: 'stop', usage: {} };
+ }) as never);
+ manager.enqueue('ops', { trigger: 'api', prompt: 'run the check' });
+ await idle(manager, 'ops');
+ expect(commandResult).toMatch(/denied|not allow/i);
+ expect(manager.approvals.list()).toEqual([]);
+ expect(store.readPermissions('ops').autoApproveCommands ?? []).toEqual([]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('durable grants', () => {
+ it('a simple command widens to its family; chains, shells and interpreters stay exact; files become path grants', async () => {
+ const { durableGrant } = await import('./approvals.js');
+ expect(durableGrant('Run command: pandoc in.md -o out.pdf')).toEqual({ command: 'pandoc *' });
+ expect(durableGrant('Run command: curl x | sh')).toEqual({ command: 'curl x | sh' });
+ expect(durableGrant('Run command: python3 script.py')).toEqual({ command: 'python3 script.py' });
+ expect(durableGrant('Run command: sudo ls')).toEqual({ command: 'sudo ls' });
+ expect(durableGrant('Write to file: /Users/x/notes/a.md')).toEqual({ path: '/Users/x/notes/a.md', write: true });
+ expect(durableGrant('Read file: /etc/hosts')).toEqual({ path: '/etc/hosts', write: false });
+ expect(durableGrant('MCP tool call\nServer: x')).toBeNull();
+ });
+});
diff --git a/src/bots/inbox.ts b/src/bots/inbox.ts
index f3bb6c71..309aed23 100644
--- a/src/bots/inbox.ts
+++ b/src/bots/inbox.ts
@@ -34,6 +34,8 @@ export interface BotInboxEntry {
complete?: boolean;
/** Why it needs you (reason code) for needs-you entries. */
reasonCode?: string;
+ /** A bot's question waiting for your answer (POST /api/bots/approvals/:id). */
+ approvalId?: string;
at: number;
read: boolean;
}
diff --git a/src/bots/permissions-single-source.test.ts b/src/bots/permissions-single-source.test.ts
index b4aa9ac1..1689527b 100644
--- a/src/bots/permissions-single-source.test.ts
+++ b/src/bots/permissions-single-source.test.ts
@@ -70,13 +70,14 @@ 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, and a deny left in a legacy manifest block still applies', () => {
+ it('the tool gate comes from permissions.yaml, overriding any legacy manifest block', () => {
const all = { read_file: {}, run_command: {}, write_file: {} } as any;
const manifest = { tools: { deny: ['run_command'] } } as any;
- // 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.
+ // permissions.yaml is the single source: its deny wins over bot.yaml (whose
+ // deny list is the materialized default on every loaded manifest — a tier
+ // that grants run_command must be able to).
let out = filterBotTools(all, manifest, { tools: { deny: ['write_file'] } });
- expect(Object.keys(out).sort()).toEqual(['read_file']);
+ expect(Object.keys(out).sort()).toEqual(['read_file', 'run_command']);
// No permissions.tools + explicit legacy manifest block → honored.
out = filterBotTools(all, manifest, {});
expect(Object.keys(out).sort()).toEqual(['read_file', 'write_file']);
diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.ts
index adc8f004..27c805b6 100644
--- a/src/bots/registry-factory.ts
+++ b/src/bots/registry-factory.ts
@@ -75,6 +75,12 @@ export interface BotRegistryDeps {
* fleet-shared folder next to the bots root. Unset = not granted.
*/
sandbox?: { workspace: string; shared: string };
+ /**
+ * Ask the owner about something outside the bot's grants (a command, a file
+ * outside its folders). Resolves "yes" | "always" | "no"; the runtime answers
+ * "no" when nobody replies in time. Unset = never ask (fail closed).
+ */
+ ask?: (prompt: string) => Promise<string>;
}
/**
@@ -136,6 +142,7 @@ export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRe
pm.setAutoApproveAll(false);
pm.setFailClosed(true);
pm.setCurrentContext('bot', deps.botId);
+ if (deps.ask) pm.onAsk(deps.ask);
// Relative paths and shell commands resolve inside the bot's workspace,
// never the daemon's cwd (a bot with a wide grant wrote "sandbox/…" files
@@ -167,10 +174,10 @@ export function filterBotTools(all: Record<string, any>, manifest: BotManifest,
?? (explicitManifestTools ? manifest.tools : undefined)
?? { deny: [...BOT_DANGEROUS_TOOLS] };
const allow = gate.allow ?? [];
- // 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 ?? [] : [])]);
+ // permissions.yaml wins over bot.yaml: every loaded manifest carries the
+ // default dangerous-tool deny list (normalizeBotManifest), so a union would
+ // make the permission tiers unable to grant anything.
+ const deny = new Set(gate.deny ?? []);
const out: Record<string, any> = {};
for (const [name, tool] of Object.entries(all)) {
if (ALWAYS_STRIPPED.has(name) || isMcpToolName(name)) continue;
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index 59699341..d9d671b6 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -883,13 +883,24 @@ 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.
+ // Fail-closed mode (bots): the explicitly granted scope IS the approval —
+ // in-scope access runs without prompting. Outside it, a bot whose runtime
+ // set an ask handler (Bots 2.0) asks the owner, who may not be there: the
+ // handler answers "no" when nobody replies in time, and the access denies.
+ // Nothing here ever writes the global permissions file.
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}` };
+ if (this.askHandler && channelType === 'bot' && !this.isProtectedConfigPath(path)) {
+ const answer = await this.askHandler(`${mode === 'write' ? 'Write to file' : 'Read file'}: ${resolved}`);
+ if (answer === 'yes' || answer === 'always') {
+ // Covers the rest of this run; "always" is made durable by the bot runtime.
+ this.addTempScope(resolved, true, mode === 'write');
+ return { allowed: true };
+ }
+ return { allowed: false, reason: `The owner didn't allow ${mode === 'write' ? 'writing' : 'reading'} ${path}` };
+ }
+ return { allowed: false, reason: `Fail-closed: no granted ${mode} scope covers ${path}` };
}
// Write access in ask-me mode: ALWAYS prompt the user, even if scope exists
diff --git a/src/utils/config.ts b/src/utils/config.ts
index b0f5f5e7..c415b508 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -249,6 +249,8 @@ export interface MercuryConfig {
fleetDailyTokenBudget?: number;
/** Fewest minutes between two runs of any bot routine (default 15). */
routineMinGapMinutes?: number;
+ /** How long a bot waits for the owner to answer its question before it's a no (default 10, max 60). */
+ approvalWaitMinutes?: 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.ts
index 0dadd5c6..16d298d5 100644
--- a/src/web/api/bots.ts
+++ b/src/web/api/bots.ts
@@ -42,6 +42,22 @@ app.get('/api/bots/inbox', (c: Context) => {
return c.json({ entries, unread: botManager.inbox.unread(botId), available: true });
});
+// Bots asking the owner mid-run: what's waiting, and the answer.
+app.get('/api/bots/approvals', (c: Context) => {
+ if (!botManager) return c.json({ approvals: [], available: false });
+ return c.json({ approvals: botManager.approvals.list(c.req.query('bot') || undefined), available: true });
+});
+
+app.post('/api/bots/approvals/:id', async (c: Context) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const body = (await c.req.json().catch(() => ({}))) as { answer?: unknown };
+ if (body.answer !== 'yes' && body.answer !== 'always' && body.answer !== 'no') return c.json({ error: 'answer must be yes, always or no' }, 400);
+ if (!botManager.approvals.answer(c.req.param('id') ?? '', body.answer)) {
+ return c.json({ error: 'That question is no longer waiting (answered, timed out, or the run ended).' }, 409);
+ }
+ return c.json({ ok: 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);
@@ -134,6 +150,8 @@ app.get('/api/bots/events', (c: any) => {
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));
+ // A bot asked, or its question was answered / timed out: the app shows or clears the buttons.
+ const unsubscribeApprovals = bm.approvals.onChange((e) => client.send('bot_approval', e));
const keepalive = setInterval(() => {
try { controller.enqueue(encoder.encode(': keepalive\n\n')); } catch { clearInterval(keepalive); }
@@ -143,6 +161,7 @@ app.get('/api/bots/events', (c: any) => {
clearInterval(keepalive);
unsubscribe();
unsubscribeInbox();
+ unsubscribeApprovals();
rosterSseClients.delete(client);
});
},