Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: the plan checklist reaches the apps, kept per conversation
Salman Qureshif05ca808bd27
diff --git a/src/channels/web.test.ts b/src/channels/web.test.tsindex 81853618..a8bde99a 100644--- a/src/channels/web.test.ts+++ b/src/channels/web.test.ts@@ -156,3 +156,25 @@ describe('WebChannel durable streaming', () => {await expect(channel.askPermission('Write file?', 'request-allowed')).resolves.toBe('yes');});});++describe('WebChannel plan checklist', () => {+ it('sends the plan only to that conversation and keeps it for reopening', async () => {+ const { mkdtempSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const { PlanStore } = await import('../core/plan.js');+ const channel = new WebChannel('Mercury');+ channel.plans = new PlanStore(join(mkdtempSync(join(tmpdir(), 'mercury-webplan-')), 'plans.json'));+ const seen: Record<string, string[]> = { a: [], b: [] };+ for (const id of ['a', 'b']) {+ channel.addSSEClient({ enqueue: (v: Uint8Array) => seen[id].push(new TextDecoder().decode(v)), close() {} } as unknown as ReadableStreamDefaultController, id);+ }+ channel.sendPlan([{ label: 'Research', status: 'active' }, { label: 'Write', status: 'pending' }], 'a');+ expect(seen.a.join('')).toContain('event: plan');+ expect(seen.a.join('')).toContain('"label":"Research"');+ expect(seen.b.join('')).not.toContain('event: plan');+ expect(channel.plans.get('a')?.steps).toHaveLength(2);+ channel.sendPlan([{ label: 'x', status: 'nonsense' }], 'a');+ expect(channel.plans.get('a')?.steps[0].label).toBe('Research');+ });+});diff --git a/src/channels/web.ts b/src/channels/web.tsindex b91c19bf..cded1bf8 100644--- a/src/channels/web.ts+++ b/src/channels/web.ts@@ -1,4 +1,5 @@import { BaseChannel } from './base.js';+import { normalizePlan, PlanStore } from '../core/plan.js';import type { ChannelMessage, ChannelAttachment } from '../types/channel.js';import { logger } from '../utils/logger.js';import { randomUUID } from 'node:crypto';@@ -17,7 +18,7 @@ interface PendingInteraction {}export interface ChatEvent {- type: 'thinking' | 'reasoning' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched';+ type: 'thinking' | 'reasoning' | 'plan' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched';data?: Record<string, unknown>;}@@ -327,6 +328,17 @@ export class WebChannel extends BaseChannel {if (!entry.timer) entry.timer = setTimeout(flush, 125);}+ /** The latest plan per conversation (see core/plan.ts). */+ plans = new PlanStore();++ /** The model updated its plan checklist: keep it with the conversation and show it live. */+ sendPlan(steps: unknown, targetId?: string): void {+ const normalized = normalizePlan(steps);+ if (normalized.length === 0) return;+ const plan = targetId ? this.plans.set(targetId, normalized) : { steps: normalized, updatedAt: Date.now() };+ this.broadcast({ type: 'plan', data: { steps: plan.steps, updatedAt: plan.updatedAt, targetId } });+ }+sendStepDone(toolName: string, result: unknown, targetId?: string): void {const summary = typeof result === 'string'? result.slice(0, 200)diff --git a/src/core/agent.ts b/src/core/agent.tsindex 7ff3ad95..36c75719 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1992,11 +1992,12 @@ export class Agent {* Record the model's plan checklist (update_plan tool) into the TUI so the* user sees which step is being implemented. Never throws.*/- private maybeRecordPlanProgress(channel: any, toolName: string, input: unknown): void {+ private maybeRecordPlanProgress(channel: any, toolName: string, input: unknown, targetId?: string): void {try {if (toolName !== 'update_plan') return;- if (!(channel instanceof CLIChannel)) return;- channel.setPlanProgress((input as any)?.steps);+ if (channel instanceof CLIChannel) channel.setPlanProgress((input as any)?.steps);+ // The apps (Chat, Code): a card above the composer, kept with the conversation.+ else if (typeof channel?.sendPlan === 'function') channel.sendPlan((input as any)?.steps, targetId);} catch { /* checklist must never break the tool loop */ }}@@ -3057,7 +3058,7 @@ export class Agent {const trValue = toolResultValue(toolResults[i]);recordExecuteToolResult(tc.toolName, trValue);this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, trValue);- this.maybeRecordPlanProgress(channel, tc.toolName, tc.input);+ this.maybeRecordPlanProgress(channel, tc.toolName, tc.input, msg.channelId);const resultStr = typeof trValue === 'string' ? trValue : JSON.stringify(trValue ?? '');const failed = resultStr.length < 5000 && (resultStr.startsWith('Error:') ||@@ -3311,7 +3312,7 @@ export class Agent {}recordExecuteToolResult(tc.toolName, toolResultValue(toolResults[i]));this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, toolResultValue(toolResults[i]));- this.maybeRecordPlanProgress(channel, tc.toolName, tc.input);+ this.maybeRecordPlanProgress(channel, tc.toolName, tc.input, msg.channelId);loopDetector.record(tc.toolName, tc.input as Record<string, any>, false);}}@@ -3915,7 +3916,7 @@ export class Agent {lastGuardToolFailure = `${tc.toolName}: ${guardResultText.slice(0, 120)}`;}this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, guardToolResult);- this.maybeRecordPlanProgress(channel, tc.toolName, tc.input);+ this.maybeRecordPlanProgress(channel, tc.toolName, tc.input, msg.channelId);loopDetector.record(tc.toolName, tc.input as Record<string, any>, false);}}diff --git a/src/core/plan.test.ts b/src/core/plan.test.tsnew file mode 100644index 00000000..21b3c9ca--- /dev/null+++ b/src/core/plan.test.ts@@ -0,0 +1,33 @@+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { normalizePlan, PlanStore } from './plan.js';++describe('plan checklist', () => {+ it('cleans what the model sends: unknown statuses and duplicates dropped, one active step', () => {+ expect(normalizePlan([+ { label: ' Research sources ', status: 'done' },+ { label: 'Compare', status: 'active' },+ { label: 'Compare', status: 'pending' },+ { label: 'Write up', status: 'active' },+ { label: 'Huh', status: 'maybe' },+ { label: '', status: 'pending' },+ ])).toEqual([+ { label: 'Research sources', status: 'done' },+ { label: 'Compare', status: 'active' },+ { label: 'Write up', status: 'pending' },+ ]);+ expect(normalizePlan('nope')).toEqual([]);+ });++ it('keeps the latest plan per conversation across restarts', () => {+ const file = join(mkdtempSync(join(tmpdir(), 'mercury-plans-')), 'plans.json');+ const a = new PlanStore(file);+ a.set('thread-1', [{ label: 'One', status: 'active' }], 5);+ a.set('thread-1', [{ label: 'One', status: 'done' }], 6);+ const b = new PlanStore(file);+ expect(b.get('thread-1')).toEqual({ steps: [{ label: 'One', status: 'done' }], updatedAt: 6 });+ expect(b.get('other')).toBeNull();+ });+});diff --git a/src/core/plan.ts b/src/core/plan.tsnew file mode 100644index 00000000..10501be3--- /dev/null+++ b/src/core/plan.ts@@ -0,0 +1,72 @@+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';++/**+ * The model's plan checklist (update_plan), as clients show it: the terminal+ * pins it in the TUI, the apps show a card above the composer. The latest+ * plan per conversation is kept on disk so reopening a chat (or restarting+ * Mercury) shows where the work stands.+ */++export type PlanStatus = 'pending' | 'active' | 'done';+export interface PlanStep { label: string; status: PlanStatus }+export interface Plan { steps: PlanStep[]; updatedAt: number }++/** Clean up what the model sent: labels trimmed and unique, known statuses, at most one active step. */+export function normalizePlan(steps: unknown): PlanStep[] {+ if (!Array.isArray(steps)) return [];+ const out: PlanStep[] = [];+ for (const raw of steps.slice(0, 20)) {+ const label = typeof (raw as { label?: unknown })?.label === 'string' ? (raw as { label: string }).label.trim() : '';+ const status = (raw as { status?: unknown })?.status;+ if (!label || (status !== 'pending' && status !== 'active' && status !== 'done')) continue;+ if (out.some((s) => s.label === label)) continue;+ out.push({ label: label.slice(0, 160), status });+ }+ const active = out.findIndex((s) => s.status === 'active');+ out.forEach((s, i) => { if (s.status === 'active' && i !== active) s.status = 'pending'; });+ return out;+}++const MAX_KEPT = 200;++export class PlanStore {+ private plans = new Map<string, Plan>();+ private loaded = false;+ constructor(private readonly file = join(getMercuryHome(), 'memory', 'plans.json')) {}++ private load(): void {+ if (this.loaded) return;+ this.loaded = true;+ try {+ if (!existsSync(this.file)) return;+ const raw = JSON.parse(readFileSync(this.file, 'utf-8')) as Record<string, Plan>;+ for (const [k, v] of Object.entries(raw)) if (Array.isArray(v?.steps)) this.plans.set(k, { steps: normalizePlan(v.steps), updatedAt: Number(v.updatedAt) || 0 });+ } catch { /* a broken file starts fresh */ }+ }++ get(id: string): Plan | null {+ this.load();+ return this.plans.get(id) ?? null;+ }++ set(id: string, steps: PlanStep[], now = Date.now()): Plan {+ this.load();+ const plan = { steps, updatedAt: now };+ this.plans.delete(id);+ this.plans.set(id, plan);+ while (this.plans.size > MAX_KEPT) this.plans.delete(this.plans.keys().next().value as string);+ this.save();+ return plan;+ }++ private save(): void {+ try {+ mkdirSync(join(this.file, '..'), { recursive: true });+ const tmp = `${this.file}.tmp`;+ writeFileSync(tmp, JSON.stringify(Object.fromEntries(this.plans)), { encoding: 'utf-8', mode: 0o600 });+ renameSync(tmp, this.file);+ } catch { /* the live card still works; only the reopen view would be stale */ }+ }+}diff --git a/src/core/system-prompt.ts b/src/core/system-prompt.tsindex 6daaee2f..922f1723 100644--- a/src/core/system-prompt.ts+++ b/src/core/system-prompt.ts@@ -54,7 +54,7 @@ export const TOOL_USAGE_GUIDELINES = `**Tool Usage Guidelines:**export const CHAT_WORK_CONTRACT = `**How you work:**- When the user asks for something to be done, do it with your tools; don't describe how they could do it.- First work out the end result they want, then the fastest reliable way to get there (an existing command, library or service beats manual steps).-- For tasks with several steps, keep a short plan with update_plan and work through it.+- For real multi-step work (three or more distinct steps: research across sources, building or changing several things), keep a short plan with update_plan and work through it, marking each step as you go. Never make a plan for a question, a chat, or a quick single action.- Report what you did and what you checked, briefly. If something failed or you could not confirm it, say so plainly.- Need the user to decide before you go on — yes or no, or which of a few options? Ask with ask_user, so they pick with the arrow keys instead of typing an answer. Only a question that needs free text (a name, a path, a date) is asked in words.- Plain questions and conversation don't need tools: just answer.`;diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex 4e11d535..8c13a61d 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -40,6 +40,7 @@ export const API_FEATURES: readonly string[] = Object.freeze(['chat.stop', // POST /api/chat/stop — interrupt the running turn (same as /stop)'providers.manage', // GET /api/providers/settings, POST /api/providers/:id/check (live, unsaved), PUT /api/providers/roles; saves apply live; health.setupRequired'voice.check',+ 'chat.plan', // SSE 'plan' { steps, updatedAt } + GET /api/chat/plan?sessionId= (the plan checklist)'channels', // GET /api/channels, POST :type/check, PUT :type, POST :type/access, POST/GET signal/link'transcribe', // GET/POST /api/transcribe — dictation: raw audio in, text out'cloud.signin', // GET /api/cloud/status, POST/GET/DELETE /api/cloud/signin (browser pairing from any client) // POST /api/voice/check { vendor, key?, endpoint? }diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex f793a2f9..9f25de89 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -122,6 +122,13 @@ const chat = new Hono();// ─── SSE Events ──────────────────────────────────────────────+/** The conversation's latest plan checklist (update_plan), for a client opening the thread. */+chat.get('/api/chat/plan', (c) => {+ if (!webChannel) return c.json({ plan: null });+ const id = c.req.query('sessionId');+ return c.json({ plan: id ? webChannel.plans.get(id) : null });+});+chat.get('/api/chat/events', (c) => {if (!webChannel) {return c.json({ error: 'Web channel not initialized' }, 503);