Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(plugins): plugin API 1.1, chat channels from out-of-process plugins
Salman Qureshi1c11617c74cd
diff --git a/src/channels/registry.ts b/src/channels/registry.tsindex c277df54..f50b1b73 100644--- a/src/channels/registry.ts+++ b/src/channels/registry.ts@@ -71,6 +71,13 @@ export class ChannelRegistry {logger.info({ channel: type }, 'Channel registered');}+ /** Remove a channel, only if it is still the one registered (plugin channels come and go). */+ unregister(type: ChannelType, channel: Channel): void {+ if (this.channels.get(type) !== channel) return;+ this.channels.delete(type);+ logger.info({ channel: type }, 'Channel unregistered');+ }+get(type: ChannelType): Channel | undefined {return this.channels.get(type);}@@ -112,6 +119,8 @@ export class ChannelRegistry {if (discord?.isReady()) return discord;const slack = this.channels.get('slack');if (slack?.isReady()) return slack;+ const whatsapp = this.channels.get('whatsapp');+ if (whatsapp?.isReady()) return whatsapp;const cli = this.channels.get('cli');if (cli?.isReady()) return cli;return this.channels.values().next().value;diff --git a/src/cli/plugins-cli.ts b/src/cli/plugins-cli.tsindex a0c8cc45..a94c99d0 100644--- a/src/cli/plugins-cli.ts+++ b/src/cli/plugins-cli.ts@@ -63,6 +63,29 @@ export function registerPluginsCli(program: Command): void {.action((id: string, opts: { purge?: boolean; yes?: boolean }) => run(`/plugins uninstall ${id}${opts.purge ? ' --purge' : ''}${opts.yes ? ' --yes' : ''}`));plugins.command('set <id> <key> <value...>').description('Change a plugin setting').action((id: string, key: string, value: string[]) => run(`/plugins set ${id} ${key} ${value.join(' ')}`));+ plugins+ .command('pair <id>')+ .description('Link the account for a channel plugin (e.g. WhatsApp): scan a QR code, or use --code')+ .option('--code <phone>', 'Get an 8-character pairing code for this phone number instead of a QR code')+ .action(async (id: string, opts: { code?: string }) => {+ await pairChannel(id, opts.code);+ setTimeout(() => process.exit(process.exitCode ?? 0), 50).unref();+ });++ plugins+ .command('unlink <id>')+ .description('Log a channel plugin out of its account (you can pair again later)')+ .action(async (id: string) => {+ const { getPluginService } = await import('../plugins/service.js');+ try {+ await getPluginService().unlink(id);+ console.log(chalk.green(` ✓ ${id} unlinked.`));+ } catch (err) {+ console.error(chalk.red(` ✗ ${(err as Error).message}`));+ process.exitCode = 1;+ }+ });+plugins.command('init <id>').description('Start a new plugin in ./<id> (for plugin authors)')@@ -164,3 +187,63 @@ export async function runPluginDoctor(): Promise<void> {console.log('');if (problems) process.exitCode = 1;}++async function pairChannel(id: string, phone?: string): Promise<void> {+ const { getPluginService } = await import('../plugins/service.js');+ const svc = getPluginService();+ if (svc.mode === 'offline') {+ console.error(chalk.red(' ✗ Mercury is not running. Start it (mercury start), then run this again.'));+ process.exitCode = 1;+ return;+ }+ const qrcode = (await import('qrcode-terminal')).default;+ const show = (st: { qr?: string; pairCode?: string }) => {+ if (st.pairCode) {+ console.log('');+ console.log(` Pairing code: ${chalk.bold.cyan(st.pairCode)}`);+ console.log(chalk.dim(' On the phone with the spare number: WhatsApp → Settings → Linked devices → Link a device → Link with phone number instead, then type the code.'));+ } else if (st.qr) {+ console.log('');+ qrcode.generate(st.qr, { small: true }, (q: string) => console.log(q.replace(/^/gm, ' ')));+ console.log(chalk.dim(' On the phone with the spare number: WhatsApp → Settings → Linked devices → Link a device, then scan. The code refreshes every ~20 seconds.'));+ }+ };+ console.log('');+ console.log(chalk.yellow(' ⚠ This uses an unofficial WhatsApp protocol. Link a spare number you can afford to lose, not your main one.'));+ try {+ let st = await svc.pair(id, phone ? { method: 'code', phone } : { method: 'qr' });+ if (st.state === 'connected') {+ console.log(chalk.green(` ✓ Already linked${st.account ? ` as ${st.account}` : ''}.`));+ return;+ }+ show(st);+ let lastShown = st.qr ?? st.pairCode;+ const deadline = Date.now() + 3 * 60_000;+ while (Date.now() < deadline) {+ await new Promise((r) => setTimeout(r, 2000));+ const next = await svc.channelStatus(id);+ if (!next) continue;+ st = next;+ if (st.state === 'connected') {+ console.log('');+ console.log(chalk.green(` ✓ Linked${st.account ? ` as ${st.account}` : ''}. Message this number from your owner number to talk to Mercury.`));+ return;+ }+ if (st.state === 'error' || st.state === 'logged-out') {+ console.error(chalk.red(` ✗ ${st.detail ?? st.state}`));+ process.exitCode = 1;+ return;+ }+ const current = st.qr ?? st.pairCode;+ if (current && current !== lastShown && !phone) {+ lastShown = current;+ show(st);+ }+ }+ console.error(chalk.red(' ✗ Timed out waiting for the link. Run the command again.'));+ process.exitCode = 1;+ } catch (err) {+ console.error(chalk.red(` ✗ ${(err as Error).message}`));+ process.exitCode = 1;+ }+}diff --git a/src/index.ts b/src/index.tsindex 7b47f002..06b277a0 100644--- a/src/index.ts+++ b/src/index.ts@@ -54,6 +54,7 @@ import { buildConversationHistoryPayload, CloudSessionSynchronizer, SessionReposimport { UserMemoryStore } from './memory/user-memory.js';import { BotManager } from './bots/bot-manager.js';import { getPluginManager, peekPluginManager } from './plugins/manager.js';+import { setChannelHost } from './plugins/channel-bridge.js';import { registerPluginsCli } from './cli/plugins-cli.js';import { SECOND_BRAIN_UNAVAILABLE_MESSAGE } from './memory/second-brain-db.js';import { isSqliteAvailable } from './utils/sqlite-driver.js';@@ -2672,6 +2673,11 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {// a broken plugin is disabled, never a reason for Mercury not to start.const pluginManager = daemonOwnsRuntime ? undefined : getPluginManager();if (pluginManager) {+ // Plugin API 1.1: channels provided by plugins (e.g. WhatsApp) join the registry while they run.+ setChannelHost({+ register: (type, channel) => channels.register(type, channel),+ unregister: (type, channel) => channels.unregister(type, channel),+ });pluginManager.setRunsPlugins(true);pluginManager.setNotifier((m) => agent.notifyAllChannels(m));void pluginManager.boot().catch((err) => logger.error({ err }, 'Plugin boot failed'));@@ -3606,6 +3612,11 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {if (channelType === 'web' && webChannel) {return webChannel.askPermission(prompt, channelId);}+ // Any other channel that can ask (plugin channels such as WhatsApp).+ const asking = channels.get(channelType as Parameters<typeof channels.get>[0]) as { askPermission?: (p: string, id?: string) => Promise<string> } | undefined;+ if (channelType !== 'cli' && typeof asking?.askPermission === 'function') {+ return asking.askPermission(prompt, channelId);+ }if (cliChannel) {return cliChannel.askPermission(prompt);}diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.tsnew file mode 100644index 00000000..dc81780c--- /dev/null+++ b/src/plugins/channel-bridge.ts@@ -0,0 +1,361 @@+/**+ * Plugin API 1.1: a chat channel provided by an out-of-process plugin.+ *+ * The plugin owns the connection to the chat service (e.g. WhatsApp as a+ * linked device). Mercury owns everything that decides what reaches the+ * agent: who is allowed to talk to it (the owner's number and listed+ * members, checked here, not in the plugin), approvals, chunking and+ * formatting. A plugin can't widen access by sending messages Mercury+ * didn't ask for.+ *+ * Protocol (JSON-RPC over the plugin's stdio, alongside MCP):+ * plugin → Mercury notifications+ * mercury/channel/status { state, detail?, account?, qr?, pairCode? }+ * mercury/channel/message { id, chatId, senderId, senderPhone?, senderName?,+ * isGroup?, fromMe?, text?, attachments?, timestamp? }+ * Mercury → plugin requests+ * mercury/channel/send { chatId, text }+ * mercury/channel/sendFile { chatId, path, caption? }+ * mercury/channel/typing { chatId, on }+ * mercury/channel/pair { method: 'qr' | 'code', phone? }+ * mercury/channel/unlink {}+ */+import { basename } from 'node:path';+import { existsSync, statSync } from 'node:fs';+import { BaseChannel, type Channel } from '../channels/base.js';+import type { ChannelMessage, ChannelType } from '../types/channel.js';+import { logger } from '../utils/logger.js';+import type { PluginManifest } from './types.js';++export const CHANNEL_STATES = ['starting', 'needs-pairing', 'pairing', 'connected', 'disconnected', 'logged-out', 'error'] as const;+export type ChannelState = (typeof CHANNEL_STATES)[number];++export interface ChannelStatus {+ state: ChannelState;+ detail?: string;+ /** The linked account, e.g. the spare number Mercury runs on. */+ account?: string;+ qr?: string;+ pairCode?: string;+ at: number;+}++export interface ChannelTransport {+ request(method: string, params: unknown, timeoutMs: number): Promise<unknown>;+}++/** Where plugin channels are registered (the runtime's ChannelRegistry). */+export interface ChannelHost {+ register(type: ChannelType, channel: Channel): void;+ unregister(type: ChannelType, channel: Channel): void;+}++let host: ChannelHost | null = null;+const live = new Map<string, PluginChannel>();++export function setChannelHost(h: ChannelHost | null): void {+ host = h;+ if (h) for (const ch of live.values()) h.register(ch.type, ch);+}++export function getPluginChannel(pluginId: string): PluginChannel | undefined {+ return live.get(pluginId);+}++const MAX_MESSAGE_LENGTH = 4000;+const SEND_TIMEOUT_MS = 30_000;+const FILE_TIMEOUT_MS = 5 * 60_000;+const APPROVAL_TIMEOUT_MS = 120_000;+const FILE_LIMIT_BYTES = 100 * 1024 * 1024;++const AFFIRMATIVE = new Set(['yes', 'y', 'ok', 'okay', 'sure', 'allow', 'approve', 'yeah', 'yep', 'yup', '1']);+const NEGATIVE = new Set(['no', 'n', 'nope', 'deny', 'stop', 'cancel', 'never', '2']);+const ALWAYS_WORDS = new Set(['always', 'allow all', 'allow-all', 'forever', '3']);++function normalizeReply(raw: string): 'yes' | 'no' | 'always' | null {+ const t = raw.trim().toLowerCase().replace(/[.!]/g, '');+ if (ALWAYS_WORDS.has(t)) return 'always';+ if (AFFIRMATIVE.has(t)) return 'yes';+ if (NEGATIVE.has(t)) return 'no';+ return null;+}++export function digits(s: string | undefined): string {+ return (s ?? '').split('@')[0].split(':')[0].replace(/\D/g, '');+}++/** Markdown → WhatsApp formatting (*bold*, _italic_, ~strike~, ```mono```). */+export function toWhatsAppText(md: string): string {+ return md+ .replace(/^#{1,6}\s+(.+)$/gm, '*$1*')+ .replace(/\*\*(.+?)\*\*/g, '*$1*')+ .replace(/(?<![*\w])__(.+?)__(?![*\w])/g, '_$1_')+ .replace(/~~(.+?)~~/g, '~$1~')+ .replace(/\[([^\]]+)\]\((https?:[^)]+)\)/g, '$1 ($2)');+}++export function splitMessage(text: string, max = MAX_MESSAGE_LENGTH): string[] {+ const out: string[] = [];+ let rest = text;+ while (rest.length > max) {+ let cut = rest.lastIndexOf('\n', max);+ if (cut < max * 0.5) cut = rest.lastIndexOf(' ', max);+ if (cut < max * 0.5) cut = max;+ out.push(rest.slice(0, cut).trimEnd());+ rest = rest.slice(cut).trimStart();+ }+ if (rest) out.push(rest);+ return out;+}++interface IncomingParams {+ id?: unknown;+ chatId?: unknown;+ senderId?: unknown;+ senderPhone?: unknown;+ senderName?: unknown;+ isGroup?: unknown;+ fromMe?: unknown;+ text?: unknown;+ attachments?: unknown;+ timestamp?: unknown;+}++export class PluginChannel extends BaseChannel {+ readonly type: ChannelType;+ private status: ChannelStatus = { state: 'starting', at: Date.now() };+ private pending = new Map<string, { resolve: (v: string) => void; timer: ReturnType<typeof setTimeout> }>();+ private seen = new Set<string>();+ private statusListeners = new Set<(s: ChannelStatus) => void>();++ constructor(+ private readonly manifest: PluginManifest,+ private readonly transport: ChannelTransport,+ /** The plugin's current settings (owner, members, allowGroups). */+ private readonly settings: () => Record<string, unknown>,+ private readonly notifyOwner: (message: string) => void,+ ) {+ super();+ this.type = manifest.contributes.channel!.type as ChannelType;+ }++ get pluginId(): string {+ return this.manifest.id;+ }++ getStatus(): ChannelStatus {+ return { ...this.status };+ }++ onStatus(fn: (s: ChannelStatus) => void): () => void {+ this.statusListeners.add(fn);+ return () => this.statusListeners.delete(fn);+ }++ // ── lifecycle (driven by the plugin runtime) ──────────────────────────++ attach(): void {+ live.set(this.manifest.id, this);+ host?.register(this.type, this);+ }++ detach(): void {+ if (live.get(this.manifest.id) === this) live.delete(this.manifest.id);+ host?.unregister(this.type, this);+ this.ready = false;+ for (const [, p] of this.pending) {+ clearTimeout(p.timer);+ p.resolve('no');+ }+ this.pending.clear();+ }++ /** The plugin process went away; it will be restarted by the supervisor. */+ down(): void {+ this.setStatus({ state: 'disconnected', detail: 'the plugin process stopped', at: Date.now() });+ }++ handleNotification(method: string, params: unknown): void {+ if (method === 'mercury/channel/status') this.onStatusNotification(params);+ else if (method === 'mercury/channel/message') this.onMessageNotification(params as IncomingParams);+ }++ private onStatusNotification(params: unknown): void {+ const p = (params ?? {}) as Record<string, unknown>;+ const state = CHANNEL_STATES.includes(p.state as ChannelState) ? (p.state as ChannelState) : 'error';+ const str = (v: unknown, max: number) => (typeof v === 'string' && v.length <= max ? v : undefined);+ const prev = this.status.state;+ this.setStatus({+ state,+ detail: str(p.detail, 500),+ account: str(p.account, 100),+ qr: str(p.qr, 4000),+ pairCode: str(p.pairCode, 32),+ at: Date.now(),+ });+ if (state === 'logged-out' && prev !== 'logged-out') {+ this.notifyOwner(`⚠️ ${this.manifest.name} was logged out${this.status.detail ? `: ${this.status.detail}` : ''}. Link it again with /plugins pair ${this.manifest.id}.`);+ }+ }++ private setStatus(s: ChannelStatus): void {+ this.status = s;+ this.ready = s.state === 'connected';+ for (const fn of this.statusListeners) {+ try { fn(this.getStatus()); } catch { /* listener */ }+ }+ }++ /** Who may talk to Mercury here: 'admin' for the owner, 'member' for listed members, null otherwise. */+ roleOf(sender: string): 'admin' | 'member' | null {+ const s = this.settings();+ const d = digits(sender);+ if (!d) return null;+ if (d === digits(String(s.owner ?? ''))) return 'admin';+ const members = String(s.members ?? '').split(/[,\s]+/).map(digits).filter(Boolean);+ return members.includes(d) ? 'member' : null;+ }++ private onMessageNotification(p: IncomingParams): void {+ if (typeof p.chatId !== 'string' || typeof p.senderId !== 'string') return;+ if (p.fromMe === true) return; // never answer ourselves+ const id = typeof p.id === 'string' ? p.id : `${p.chatId}:${Date.now()}`;+ if (this.seen.has(id)) return;+ this.seen.add(id);+ if (this.seen.size > 5000) this.seen.delete(this.seen.values().next().value!);++ const settings = this.settings();+ if (p.isGroup === true && settings.allowGroups !== true) return;+ const sender = typeof p.senderPhone === 'string' && p.senderPhone ? p.senderPhone : p.senderId;+ const role = this.roleOf(sender);+ if (!role) {+ if (!digits(String(settings.owner ?? ''))) {+ logger.warn({ plugin: this.manifest.id }, 'Channel message ignored: no owner number set');+ }+ return; // unknown senders are ignored, silently+ }++ const text = typeof p.text === 'string' ? p.text.slice(0, 20_000) : '';+ const pending = this.pending.get(p.chatId);+ if (pending && text) {+ const answer = normalizeReply(text);+ if (answer) {+ clearTimeout(pending.timer);+ this.pending.delete(p.chatId);+ pending.resolve(answer);+ return;+ }+ }++ const files = Array.isArray(p.attachments)+ ? (p.attachments as Array<Record<string, unknown>>)+ .filter((a) => typeof a?.path === 'string')+ .slice(0, 10)+ .map((a) => ({ path: a.path as string, kind: String(a.kind ?? 'document'), name: typeof a.name === 'string' ? a.name : basename(a.path as string), mime: typeof a.mime === 'string' ? a.mime : undefined }))+ : [];+ let content = text;+ if (files.length) {+ const list = files.map((f) => `${f.kind}: ${f.path}`).join('\n');+ content = `${content}${content ? '\n' : ''}[Attachments]\n${list}`;+ }+ if (!content) return;++ const msg: ChannelMessage = {+ id,+ channelId: `${this.type}:${p.chatId}`,+ channelType: this.type,+ senderId: sender,+ senderName: typeof p.senderName === 'string' ? p.senderName.slice(0, 100) : undefined,+ senderRole: role,+ content,+ timestamp: typeof p.timestamp === 'number' ? p.timestamp : Date.now(),+ metadata: { pluginId: this.manifest.id, chatId: p.chatId, isGroup: p.isGroup === true, attachments: files },+ };+ this.emit(msg);+ }++ // ── Channel ──────────────────────────────────────────────────────────++ async start(): Promise<void> { /* the plugin runtime drives the connection */ }+ async stop(): Promise<void> { /* stopped with the plugin */ }++ private chatOf(targetId?: string): string {+ const t = targetId ?? this.defaultTarget();+ if (!t) throw new Error(`${this.manifest.name}: no chat to send to (set the owner number in the plugin settings)`);+ return t.startsWith(`${this.type}:`) ? t.slice(this.type.length + 1) : t;+ }++ /** Notifications with no chat go to the owner's own chat. */+ private defaultTarget(): string | undefined {+ const owner = digits(String(this.settings().owner ?? ''));+ return owner ? `${owner}@s.whatsapp.net` : undefined;+ }++ async send(content: string, targetId?: string): Promise<void> {+ if (!content.trim()) return;+ const chatId = this.chatOf(targetId);+ for (const chunk of splitMessage(toWhatsAppText(content))) {+ await this.transport.request('mercury/channel/send', { chatId, text: chunk }, SEND_TIMEOUT_MS);+ }+ }++ async sendFile(filePath: string, targetId?: string): Promise<void> {+ if (!existsSync(filePath) || !statSync(filePath).isFile()) throw new Error(`Not a file: ${filePath}`);+ if (statSync(filePath).size > FILE_LIMIT_BYTES) throw new Error('File is larger than 100 MB');+ await this.transport.request('mercury/channel/sendFile', { chatId: this.chatOf(targetId), path: filePath }, FILE_TIMEOUT_MS);+ }++ async stream(content: AsyncIterable<string>, targetId?: string): Promise<string> {+ // WhatsApp can't edit a message as it streams: send the whole reply.+ let full = '';+ for await (const chunk of content) full += chunk;+ await this.send(full, targetId);+ return full;+ }++ async typing(targetId?: string): Promise<void> {+ try {+ await this.transport.request('mercury/channel/typing', { chatId: this.chatOf(targetId), on: true }, 10_000);+ } catch { /* cosmetic */ }+ }++ private ask(prompt: string, targetId: string | undefined): Promise<string> {+ const chatId = this.chatOf(targetId);+ const previous = this.pending.get(chatId);+ if (previous) {+ clearTimeout(previous.timer);+ previous.resolve('no');+ }+ return new Promise((resolve) => {+ const timer = setTimeout(() => {+ this.pending.delete(chatId);+ resolve('no');+ }, APPROVAL_TIMEOUT_MS);+ this.pending.set(chatId, { resolve, timer });+ this.send(prompt, targetId).catch(() => {+ clearTimeout(timer);+ this.pending.delete(chatId);+ resolve('no');+ });+ });+ }++ /** Approval prompt answered by text: 1/yes, 2/no, 3/always. No reply in 2 minutes is no. */+ async askPermission(prompt: string, targetId?: string): Promise<string> {+ return this.ask(`🔐 ${prompt}\n\nReply *1* (yes), *2* (no) or *3* (always for this chat).`, targetId);+ }++ async askToContinue(question: string, targetId?: string): Promise<boolean> {+ return (await this.ask(`${question}\n\nReply *yes* to continue or *no* to stop.`, targetId)) !== 'no';+ }++ // ── owner actions ────────────────────────────────────────────────────++ async pair(method: 'qr' | 'code', phone?: string): Promise<void> {+ await this.transport.request('mercury/channel/pair', { method, ...(phone ? { phone: digits(phone) } : {}) }, 30_000);+ }++ async unlink(): Promise<void> {+ await this.transport.request('mercury/channel/unlink', {}, 30_000);+ }+}diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.tsnew file mode 100644index 00000000..35732041--- /dev/null+++ b/src/plugins/channel.test.ts@@ -0,0 +1,202 @@+import { mkdirSync, readFileSync, existsSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { Tool } from 'ai';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { PermissionManager } from '../capabilities/permissions.js';+import type { Channel } from '../channels/base.js';+import type { ChannelMessage } from '../types/channel.js';+import { PluginManager } from './manager.js';+import { getPluginChannel, setChannelHost, splitMessage, toWhatsAppText, type PluginChannel } from './channel-bridge.js';+import { getPluginTools, resetToolBridge } from './tool-bridge.js';+import { pluginDataDir } from './store.js';+import { manifestSchema } from './types.js';+import { sleep, tempHome, waitFor } from './test-fixtures.js';++/** A fake WhatsApp plugin speaking the Plugin API 1.1 channel extension. */+const CHANNEL_SERVER = `+const fs = require('node:fs');+const path = require('node:path');+const data = process.env.MERCURY_PLUGIN_DATA_DIR;+const rl = require('node:readline').createInterface({ input: process.stdin });+const send = (m) => process.stdout.write(JSON.stringify(m) + '\\n');+const notify = (method, params) => send({ jsonrpc: '2.0', method, params });+const log = (name, v) => fs.appendFileSync(path.join(data, name), JSON.stringify(v) + '\\n');+rl.on('line', (line) => {+ const msg = JSON.parse(line);+ const ok = (result) => send({ jsonrpc: '2.0', id: msg.id, result });+ switch (msg.method) {+ case 'initialize':+ log('init.jsonl', msg.params.capabilities);+ return ok({ protocolVersion: '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'wa', version: '1' } });+ case 'notifications/initialized':+ return notify('mercury/channel/status', { state: 'needs-pairing' });+ case 'tools/list':+ return ok({ tools: [{ name: 'inject', description: 'test', inputSchema: { type: 'object' } }] });+ case 'tools/call': {+ const a = msg.params.arguments;+ notify('mercury/channel/message', { id: a.id, chatId: a.chatId || '[email protected]', senderId: a.senderId || 'x@lid', senderPhone: a.senderPhone, isGroup: !!a.isGroup, fromMe: !!a.fromMe, text: a.text });+ return ok({ content: [{ type: 'text', text: 'injected' }] });+ }+ case 'mercury/channel/pair':+ ok({});+ notify('mercury/channel/status', { state: 'pairing', qr: 'QR-1' });+ return setTimeout(() => notify('mercury/channel/status', { state: 'connected', account: '15550001' }), 50);+ case 'mercury/channel/send':+ case 'mercury/channel/sendFile':+ case 'mercury/channel/typing':+ log('out.jsonl', { method: msg.method, ...msg.params });+ return ok({});+ case 'mercury/channel/unlink':+ ok({});+ return notify('mercury/channel/status', { state: 'logged-out', detail: 'unlinked by owner' });+ }+});+`;++function channelPlugin(root: string, id = 'whatsapp', extra: Record<string, unknown> = {}): string {+ const dir = join(root, `${id}-1.0.0`);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'mercury-plugin.json'), JSON.stringify({+ manifestVersion: 1, id, name: 'WhatsApp', version: '1.0.0', description: 'test channel', kind: 'out-of-process',+ engines: { mercury: '>=1.0.0', pluginApi: '^1.1.0' },+ server: { command: 'node', args: ['server.cjs'] },+ contributes: { tools: [{ name: 'inject', description: 'Inject a message for tests.', readOnly: true }], channel: { type: 'whatsapp' } },+ settings: { version: 1, fields: { owner: { type: 'string', default: '' }, members: { type: 'string', default: '' }, allowGroups: { type: 'boolean', default: false } } },+ ...extra,+ }));+ writeFileSync(join(dir, 'server.cjs'), CHANNEL_SERVER);+ return dir;+}++let env: ReturnType<typeof tempHome>;+let src: string;+let mgr: PluginManager;+let registered: Array<{ type: string; channel: Channel }>;+let received: ChannelMessage[];+let notices: string[];++beforeEach(() => {+ env = tempHome();+ src = join(env.home, 'src');+ mkdirSync(src, { recursive: true });+ resetToolBridge();+ registered = [];+ received = [];+ notices = [];+ setChannelHost({+ register: (type, channel) => { registered.push({ type, channel }); channel.onMessage((m) => received.push(m)); },+ unregister: (type, channel) => { registered = registered.filter((r) => r.channel !== channel); },+ });+ mgr = new PluginManager({ safeMode: false, notify: (m) => { notices.push(m); } });+});++afterEach(async () => {+ await mgr.shutdown();+ setChannelHost(null);+ resetToolBridge();+ env.restore();+});++async function inject(args: Record<string, unknown>): Promise<void> {+ const t = getPluginTools(new PermissionManager())['whatsapp__inject'] as Tool & { execute: (a: unknown, o: unknown) => Promise<unknown> };+ await t.execute(args, { toolCallId: 't', messages: [] });+ await sleep(40);+}++async function installChannel(owner = '+1 555 0002', members = ''): Promise<PluginChannel> {+ await mgr.install(channelPlugin(src));+ await mgr.setSetting('whatsapp', 'owner', owner);+ if (members) await mgr.setSetting('whatsapp', 'members', members);+ await waitFor(() => !!getPluginChannel('whatsapp') && registered.length === 1);+ return getPluginChannel('whatsapp')!;+}++describe('plugin channels (plugin API 1.1)', () => {+ it('registers with the runtime, negotiates the extension and goes away on disable', async () => {+ const ch = await installChannel();+ expect(registered[0].type).toBe('whatsapp');+ const init = readFileSync(join(pluginDataDir('whatsapp'), 'init.jsonl'), 'utf8');+ expect(init).toContain('mercury/channel');+ expect(ch.getStatus().state).toBe('needs-pairing');+ expect(ch.isReady()).toBe(false);+ await mgr.disable('whatsapp');+ expect(registered).toEqual([]);+ expect(getPluginChannel('whatsapp')).toBeUndefined();+ });++ it('pairs with a QR code and becomes ready', async () => {+ await installChannel();+ const st = await mgr.pair('whatsapp', { method: 'qr' });+ expect(st.qr).toBe('QR-1');+ await waitFor(() => mgr.channelStatus('whatsapp')?.state === 'connected');+ expect(getPluginChannel('whatsapp')!.isReady()).toBe(true);+ expect((await mgr.info('whatsapp'))?.channel).toMatchObject({ type: 'whatsapp', state: 'connected', account: '15550001' });+ });++ it('only the owner and listed members reach the agent; groups and our own messages never do', async () => {+ await installChannel('+1 (555) 0002', '15550003');+ await inject({ id: 'm1', senderPhone: '15550002', text: 'hi from owner' });+ await inject({ id: 'm2', senderPhone: '15550003', text: 'hi from member' });+ await inject({ id: 'm3', senderPhone: '19998887777', text: 'stranger' });+ await inject({ id: 'm4', senderPhone: '15550002', text: 'group', isGroup: true });+ await inject({ id: 'm5', senderPhone: '15550002', text: 'mine', fromMe: true });+ await inject({ id: 'm1', senderPhone: '15550002', text: 'duplicate' });+ expect(received.map((m) => [m.content, m.senderRole, m.channelId])).toEqual([+ ['hi from owner', 'admin', 'whatsapp:[email protected]'],+ ['hi from member', 'member', 'whatsapp:[email protected]'],+ ]);+ });++ it('no owner set means nobody gets through', async () => {+ await installChannel('');+ await inject({ id: 'n1', senderPhone: '15550002', text: 'hello' });+ expect(received).toEqual([]);+ });++ it('sends formatted, chunked text to the plugin', async () => {+ const ch = await installChannel();+ await ch.send('# Title\n**bold** and ~~gone~~ [link](https://x.y)', 'whatsapp:[email protected]');+ await ch.send('x'.repeat(9000), 'whatsapp:[email protected]');+ const out = readFileSync(join(pluginDataDir('whatsapp'), 'out.jsonl'), 'utf8').trim().split('\n').map((l) => JSON.parse(l));+ expect(out[0]).toMatchObject({ method: 'mercury/channel/send', chatId: '[email protected]', text: '*Title*\n*bold* and ~gone~ link (https://x.y)' });+ expect(out.slice(1).every((o) => o.text.length <= 4000)).toBe(true);+ expect(out.slice(1).map((o) => o.text).join('')).toBe('x'.repeat(9000));+ });++ it('approvals are answered by a text reply that never reaches the agent', async () => {+ const ch = await installChannel();+ const answer = ch.askPermission('Run git push?', 'whatsapp:[email protected]');+ await sleep(40);+ await inject({ id: 'a1', senderPhone: '15550002', text: '3' });+ expect(await answer).toBe('always');+ expect(received).toEqual([]);+ });++ it('logged out: tells the owner how to relink', async () => {+ await installChannel();+ await mgr.unlinkChannel('whatsapp');+ await waitFor(() => notices.length > 0);+ expect(notices[0]).toMatch(/logged out.*\/plugins pair whatsapp/);+ });++ it('only one plugin can provide a channel type', async () => {+ await installChannel();+ await expect(mgr.install(channelPlugin(src, 'whatsapp-two'))).rejects.toThrow(/already provided by "whatsapp"/);+ const other = await mgr.info('whatsapp-two');+ expect(other?.disabled?.message).toMatch(/already provided by "whatsapp"/);+ });++ it('manifest rules: out-of-process only, plugin API 1.1+', () => {+ const base = JSON.parse(readFileSync(join(channelPlugin(src, 'rules'), 'mercury-plugin.json'), 'utf8'));+ expect(manifestSchema.safeParse(base).success).toBe(true);+ expect(manifestSchema.safeParse({ ...base, engines: { mercury: '>=1.0.0', pluginApi: '^1.0.0' } }).success).toBe(true); // ^1.0.0 includes 1.1+ expect(manifestSchema.safeParse({ ...base, engines: { mercury: '>=1.0.0', pluginApi: '~1.0.0' } }).success).toBe(false);+ expect(manifestSchema.safeParse({ ...base, contributes: { ...base.contributes, channel: { type: 'telegram' } } }).success).toBe(false);+ expect(existsSync(src)).toBe(true);+ });++ it('formatting helpers', () => {+ expect(toWhatsAppText('## Hi\n__x__')).toBe('*Hi*\n_x_');+ expect(splitMessage('a\nb', 2)).toEqual(['a', 'b']);+ });+});diff --git a/src/plugins/commands.ts b/src/plugins/commands.tsindex 98429377..430d8d92 100644--- a/src/plugins/commands.ts+++ b/src/plugins/commands.ts@@ -77,6 +77,7 @@ function describe(i: PluginListItem): string {];if (i.tools.length) lines.push(`Tools: ${i.tools.join(', ')}`);if (i.commands.length) lines.push(`Commands: ${i.commands.join(', ')}`);+ if (i.channel) lines.push(`Channel: ${i.channel.type}${i.channel.state ? ` · ${i.channel.state}` : ''}${i.channel.account ? ` · ${i.channel.account}` : ''}${i.channel.detail ? ` (${i.channel.detail})` : ''}`);const p = i.permissions;lines.push(`Network: ${p?.network.length ? p.network.join(', ') : 'none'}`);lines.push(`Secrets it can read: ${p?.secrets.length ? p.secrets.join(', ') : 'none'}`);@@ -107,6 +108,8 @@ const HELP = [' /plugins rollback <id> go back to the previous version',' /plugins uninstall <id> [--purge] remove (keeps data unless --purge)',' /plugins set <id> <key> <value> change a plugin setting',+ ' /plugins pair <id> <phone> link a channel plugin\'s account (pairing code)',+ ' /plugins unlink <id> log a channel plugin out',].join('\n');function isMember(msg: ChannelMessage): boolean {@@ -122,7 +125,7 @@ export async function handlePluginsCommand(trimmed: string, msg: ChannelMessage,const args = tokens.filter((t) => !t.startsWith('--') && t !== '-y');const [sub = 'list', target, ...rest] = args;const mgr = getPluginService();- const mutating = ['install', 'enable', 'disable', 'update', 'rollback', 'uninstall', 'remove', 'set'].includes(sub);+ const mutating = ['install', 'enable', 'disable', 'update', 'rollback', 'uninstall', 'remove', 'set', 'pair', 'unlink'].includes(sub);if (mutating && isMember(msg)) {await reply('Only the owner or an admin can change plugins.');return;@@ -242,6 +245,26 @@ export async function handlePluginsCommand(trimmed: string, msg: ChannelMessage,await reply(`⚙ ${target}.${key} updated.`);return;}+ case 'pair': {+ if (!target) { await reply('Usage: /plugins pair <id> <phone number of the account to link>'); return; }+ const phone = rest.join('');+ if (!phone) {+ await reply(`In chat, pairing uses a code: /plugins pair ${target} <phone number of the spare account>.\nFor a QR code, run \`mercury plugins pair ${target}\` in a terminal or use the dashboard.`);+ return;+ }+ const st = await mgr.pair(target, { method: 'code', phone });+ if (st.state === 'connected') { await reply(`✅ Already linked${st.account ? ` as ${st.account}` : ''}.`); return; }+ await reply(st.pairCode+ ? `🔗 Pairing code: *${st.pairCode}*\nOn the phone with that number: WhatsApp → Settings → Linked devices → Link a device → Link with phone number instead, then type the code.\n⚠️ Unofficial protocol: use a spare number, not your main one.`+ : `Couldn't get a pairing code${st.detail ? `: ${st.detail}` : ''}.`);+ return;+ }+ case 'unlink': {+ if (!target) { await reply('Usage: /plugins unlink <id>'); return; }+ await mgr.unlink(target);+ await reply(`🔌 ${target} unlinked.`);+ return;+ }default:await reply(`Unknown /plugins command "${sub}".\n\n${HELP}`);}diff --git a/src/plugins/manager.ts b/src/plugins/manager.tsindex 4cb41b2c..43fb6c10 100644--- a/src/plugins/manager.ts+++ b/src/plugins/manager.ts@@ -32,6 +32,7 @@ import {import { setToolOutcomeSink, unpublishPlugin, listLiveTools, listPluginCommands } from './tool-bridge.js';import { InProcessRuntime, inProcessLogger } from './runtime/in-process.js';import { OutOfProcessRuntime } from './runtime/out-of-process.js';+import { PluginChannel, type ChannelStatus } from './channel-bridge.js';import type { PluginRuntime } from './runtime/types.js';import type { CatalogEntry, DisabledCode, PluginListItem, PluginManifest, PluginsState } from './types.js';@@ -46,6 +47,8 @@ interface Running {startedAt: number;consecutiveFailures: number;lastError?: string;+ /** Plugin API 1.1: the chat channel this plugin provides. */+ channel?: PluginChannel;}export interface PluginManagerOptions {@@ -228,7 +231,27 @@ export class PluginManager {// Never fatal: the plugin starts with defaults for anything unreadable.logger.warn({ plugin: id, err }, 'Plugin settings migration failed');}+ // Plugin API 1.1: a channel plugin. One provider per channel type.+ let channel: PluginChannel | undefined;+ let runtimeRef: OutOfProcessRuntime | undefined;+ const channelType = manifest.contributes.channel?.type;+ if (channelType) {+ const other = [...this.running.entries()].find(([oid, r]) => oid !== id && r.manifest.contributes.channel?.type === channelType);+ if (other) {+ await this.disableWith(id, 'activation', `The ${channelType} channel is already provided by "${other[0]}". Disable that plugin first.`);+ return;+ }+ channel = new PluginChannel(+ manifest,+ { request: (method, params, timeoutMs) => runtimeRef ? runtimeRef.channelRequest(method, params, timeoutMs) : Promise.reject(new Error('not running')) },+ () => resolvedSettings(manifest),+ (m) => { void this.notifyFn(m); },+ );+ }const deps = {+ onNotification: channel ? (method: string, params: unknown) => channel!.handleNotification(method, params) : undefined,+ onReady: channel ? () => channel!.attach() : undefined,+ onDown: channel ? () => channel!.down() : undefined,mercuryVersion: mercuryVersion(),dataDir: pluginDataDir(id),settings: resolvedSettings(manifest),@@ -241,15 +264,16 @@ export class PluginManager {};const runtime: PluginRuntime = manifest.kind === 'in-process'? new InProcessRuntime(manifest, dir, deps)- : new OutOfProcessRuntime(manifest, dir, deps);+ : (runtimeRef = new OutOfProcessRuntime(manifest, dir, deps));try {await runtime.start();} catch (err) {try { await runtime.stop(); } catch { /* already down */ }+ channel?.detach();await this.disableWith(id, 'activation', `Couldn't start: ${(err as Error).message}`);return;}- this.running.set(id, { runtime, manifest, version, startedAt: Date.now(), consecutiveFailures: 0 });+ this.running.set(id, { runtime, manifest, version, startedAt: Date.now(), consecutiveFailures: 0, channel });this.lastErrors.delete(id);logger.info({ plugin: id, version, kind: manifest.kind }, 'Plugin started');} finally {@@ -270,6 +294,7 @@ export class PluginManager {logger.warn({ err, plugin: id }, 'Plugin did not stop cleanly');} finally {unpublishPlugin(id);+ run.channel?.detach();}}@@ -432,6 +457,49 @@ export class PluginManager {}}+ // ── channels (plugin API 1.1) ────────────────────────────────────────++ private liveChannel(id: string): PluginChannel {+ const run = this.running.get(id);+ if (!run) {+ if (!readState().plugins[id]) throw new Error(`Plugin "${id}" is not installed.`);+ throw new Error(this.runs ? `"${id}" is not running. Enable it first: /plugins enable ${id}` : 'Mercury is not running. Start it (mercury start), then pair.');+ }+ if (!run.channel) throw new Error(`"${id}" doesn't provide a chat channel.`);+ return run.channel;+ }++ channelStatus(id: string): ChannelStatus | null {+ return this.running.get(id)?.channel?.getStatus() ?? null;+ }++ /**+ * Start linking: QR (scan in the app) or a pairing code for a phone+ * number (type it in the app). Resolves with the first status that has+ * something to show, or the current one after 25 seconds.+ */+ async pair(id: string, opts: { method: 'qr' | 'code'; phone?: string }): Promise<ChannelStatus> {+ const channel = this.liveChannel(id);+ if (opts.method === 'code' && !opts.phone) throw new Error('A pairing code needs the phone number of the WhatsApp account being linked (the spare number).');+ if (channel.getStatus().state === 'connected') return channel.getStatus();+ const ready = new Promise<ChannelStatus>((resolve) => {+ const timer = setTimeout(() => { off(); resolve(channel.getStatus()); }, 25_000);+ const off = channel.onStatus((st) => {+ if (st.qr || st.pairCode || st.state === 'connected' || st.state === 'error') {+ clearTimeout(timer);+ off();+ resolve(st);+ }+ });+ });+ await channel.pair(opts.method, opts.phone);+ return ready;+ }++ async unlinkChannel(id: string): Promise<void> {+ await this.liveChannel(id).unlink();+ }+// ── views ────────────────────────────────────────────────────────────/** Catalog + installed plugins, merged into one list for every surface. */@@ -492,6 +560,12 @@ export class PluginManager {verified: inst?.verified ?? false,tools: manifest ? manifest.contributes.tools.map((t) => `${id}__${t.name}`) : (cat?.tools ?? []),commands: manifest ? manifest.contributes.commands.map((c) => `/${c.name}`) : [],+ channel: manifest?.contributes.channel+ ? (() => {+ const st = run?.channel?.getStatus();+ return { type: manifest.contributes.channel!.type, state: st?.state, detail: st?.detail, account: st?.account };+ })()+ : undefined,permissions: manifest?.permissions ?? (cat ? { network: cat.permissions.network, secrets: cat.permissions.secrets } : undefined),disabled: inst?.disabled,lastError: run?.lastError ?? this.lastErrors.get(id),diff --git a/src/plugins/runtime/out-of-process.ts b/src/plugins/runtime/out-of-process.tsindex 23f5707f..17f78b80 100644--- a/src/plugins/runtime/out-of-process.ts+++ b/src/plugins/runtime/out-of-process.ts@@ -139,13 +139,15 @@ export class OutOfProcessRuntime implements PluginRuntime {try {await this.request('initialize', {protocolVersion: MCP_PROTOCOL_VERSION,- capabilities: {},+ // Plugin API 1.1: tell a channel plugin Mercury speaks the channel extension.+ capabilities: this.manifest.contributes.channel ? { experimental: { 'mercury/channel': { version: 1 } } } : {},clientInfo: { name: 'mercury', version: this.deps.mercuryVersion },}, OUT_OF_PROCESS.initTimeoutMs);this.notify('notifications/initialized', {});await this.refreshTools();this.ready = true;this.backoff = OUT_OF_PROCESS.backoffStartMs;+ try { this.deps.onReady?.(); } catch (err) { this.deps.log.warn(`onReady: ${(err as Error).message}`); }} catch (err) {const tail = this.stderrTail.slice(-3).join(' | ');await this.kill();@@ -194,7 +196,18 @@ export class OutOfProcessRuntime implements PluginRuntime {return text || (res?.structuredContent !== undefined ? res.structuredContent : 'Done.');}- private request(method: string, params: unknown, timeoutMs: number, signal?: AbortSignal): Promise<unknown> {+ /**+ * Plugin API 1.1 channel calls (`mercury/channel/*`). A slow send (a large+ * upload) times out for that call only; it never recycles the process,+ * which would drop the plugin's connection to the chat service.+ */+ channelRequest(method: string, params: unknown, timeoutMs: number): Promise<unknown> {+ if (!method.startsWith('mercury/channel/')) return Promise.reject(new Error(`not a channel method: ${method}`));+ if (!this.ready) return Promise.reject(new Error('the plugin process is not running'));+ return this.request(method, params, timeoutMs, undefined, false);+ }++ private request(method: string, params: unknown, timeoutMs: number, signal?: AbortSignal, recycleOnTimeout = true): Promise<unknown> {const child = this.child;if (!child || child.exitCode !== null || !child.stdin?.writable) return Promise.reject(new Error('the plugin process is not running'));const id = this.nextId++;@@ -203,7 +216,7 @@ export class OutOfProcessRuntime implements PluginRuntime {this.pending.delete(id);rejectPromise(new Error(`${method} timed out after ${Math.round(timeoutMs / 1000)}s`));// A server that stops answering is treated as hung: restart it.- if (method !== 'initialize') void this.recycle(`${method} timed out`);+ if (method !== 'initialize' && recycleOnTimeout) void this.recycle(`${method} timed out`);}, timeoutMs);this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });if (signal) {@@ -253,6 +266,12 @@ export class OutOfProcessRuntime implements PluginRuntime {if (msg.method) {if (msg.method === 'notifications/tools/list_changed' && this.ready) {this.refreshTools().catch((err) => this.deps.onError(`tools/list after change: ${(err as Error).message}`));+ } else if (msg.method.startsWith('mercury/') && this.manifest.contributes.channel) {+ try {+ this.deps.onNotification?.(msg.method, msg.params);+ } catch (err) {+ this.deps.onError(`${msg.method}: ${(err as Error).message}`);+ }}return;}@@ -288,6 +307,9 @@ export class OutOfProcessRuntime implements PluginRuntime {this.ready = false;this.failPending('the plugin process exited');unpublishPlugin(this.manifest.id);+ if (wasReady) {+ try { this.deps.onDown?.(); } catch { /* best effort */ }+ }if (!this.wanted) return;const tail = this.stderrTail.slice(-3).join(' | ');const why = `exited (${sig ?? `code ${code}`})${tail ? `: ${tail}` : ''}`;diff --git a/src/plugins/runtime/types.ts b/src/plugins/runtime/types.tsindex a23cceec..6ef4023a 100644--- a/src/plugins/runtime/types.ts+++ b/src/plugins/runtime/types.ts@@ -17,6 +17,12 @@ export interface RuntimeDeps {onError(message: string): void;/** The runtime gave up (e.g. crashed too often). The manager disables the plugin. */onFatal?(code: 'crashed' | 'activation', message: string): void;+ /** Plugin API 1.1 channels: a `mercury/…` notification from the plugin. */+ onNotification?(method: string, params: unknown): void;+ /** The plugin finished its handshake (first start and every restart). */+ onReady?(): void;+ /** The plugin process went away (crash, recycle or stop). */+ onDown?(): void;}export interface PluginRuntime {diff --git a/src/plugins/service.ts b/src/plugins/service.tsindex 136f9fce..f5d9a631 100644--- a/src/plugins/service.ts+++ b/src/plugins/service.ts@@ -13,6 +13,7 @@ import { getWebPort, readAttachToken } from '../web/auth.js';import { getDaemonStatus, getForegroundRuntimeStatus } from '../cli/daemon.js';import { getPluginManager, type PluginManager } from './manager.js';import type { PluginListItem } from './types.js';+import type { ChannelStatus } from './channel-bridge.js';export interface ListResult {items: PluginListItem[];@@ -43,6 +44,10 @@ export interface PluginService {rollback(id: string): Promise<{ from: string; to: string }>;uninstall(id: string, purge?: boolean): Promise<void>;setSetting(id: string, key: string, value: unknown): Promise<void>;+ /** Plugin API 1.1 channels. */+ pair(id: string, opts: { method: 'qr' | 'code'; phone?: string }): Promise<ChannelStatus>;+ channelStatus(id: string): Promise<ChannelStatus | null>;+ unlink(id: string): Promise<void>;}export function localService(mgr: PluginManager, mode: 'local' | 'offline' = 'local'): PluginService {@@ -60,6 +65,9 @@ export function localService(mgr: PluginManager, mode: 'local' | 'offline' = 'lorollback: (id) => mgr.rollback(id),uninstall: (id, purge) => mgr.uninstall(id, { purge }),setSetting: (id, key, value) => mgr.setSetting(id, key, value),+ pair: (id, opts) => mgr.pair(id, opts),+ channelStatus: async (id) => mgr.channelStatus(id),+ unlink: (id) => mgr.unlinkChannel(id),};}@@ -95,6 +103,9 @@ export function daemonService(): PluginService {rollback: (id) => call<{ from: string; to: string }>('POST', `/api/plugins/${enc(id)}/rollback`),uninstall: async (id, purge) => { await call('DELETE', `/api/plugins/${enc(id)}${purge ? '?purge=1' : ''}`); },setSetting: async (id, key, value) => { await call('POST', `/api/plugins/${enc(id)}/settings`, { key, value }); },+ pair: async (id, opts) => (await call<{ status: ChannelStatus }>('POST', `/api/plugins/${enc(id)}/pair`, opts, 60_000)).status,+ channelStatus: async (id) => (await call<{ status: ChannelStatus | null }>('GET', `/api/plugins/${enc(id)}/channel`)).status,+ unlink: async (id) => { await call('POST', `/api/plugins/${enc(id)}/unlink`, {}); },};}diff --git a/src/plugins/types.ts b/src/plugins/types.tsindex 3c27a8c4..da879428 100644--- a/src/plugins/types.ts+++ b/src/plugins/types.ts@@ -24,7 +24,7 @@ export const MANIFEST_VERSION = 1 as const;* Minor bumps only add; a major bump is a breaking change and the previous* major stays supported for at least two Mercury minor releases.*/-export const PLUGIN_API_VERSION = '1.0.0';+export const PLUGIN_API_VERSION = '1.1.0';export const PLUGIN_ID_RE = /^[a-z][a-z0-9-]{1,30}[a-z0-9]$/;/** Tool and command names a plugin declares (before namespacing). */@@ -41,6 +41,10 @@ export const RESERVED_COMMANDS: ReadonlySet<string> = new Set(['usage', 'cost', 'doctor', 'settings', 'config', 'login', 'logout', 'upgrade', 'version', 'about',]);+/** Channel types a plugin may provide (Plugin API 1.1). */+export const PLUGIN_CHANNEL_TYPES = ['whatsapp'] as const;+export type PluginChannelType = (typeof PLUGIN_CHANNEL_TYPES)[number];+export const SECRET_NAME_RE = /^[A-Z][A-Z0-9_]{1,63}$/;export const PLATFORM_KEYS = ['darwin-arm64', 'darwin-x64', 'linux-x64', 'linux-arm64', 'win32-x64', 'win32-arm64', 'android-arm64',@@ -121,6 +125,12 @@ export const manifestSchema = z.object({contributes: z.object({tools: z.array(toolDecl).max(64).default([]),commands: z.array(commandDecl).max(32).default([]),+ /**+ * Plugin API 1.1: an out-of-process plugin can be a chat channel. Only+ * channel types Mercury knows (sessions, approvals and the work ledger+ * are keyed by them) can be provided by a plugin.+ */+ channel: z.object({ type: z.enum(PLUGIN_CHANNEL_TYPES) }).strict().optional(),}).strict().default({ tools: [], commands: [] }),/** What the plugin needs. Shown to the owner before install. */permissions: z.object({@@ -149,6 +159,12 @@ export const manifestSchema = z.object({if (m.kind === 'out-of-process' && m.contributes.commands.length > 0) {ctx.addIssue({ code: 'custom', path: ['contributes', 'commands'], message: 'slash commands are only supported for in-process plugins in plugin API 1.0' });}+ if (m.contributes.channel && m.kind !== 'out-of-process') {+ ctx.addIssue({ code: 'custom', path: ['contributes', 'channel'], message: 'only out-of-process plugins can provide a channel' });+ }+ if (m.contributes.channel && !semver.intersects(m.engines.pluginApi, '>=1.1.0', { includePrerelease: true })) {+ ctx.addIssue({ code: 'custom', path: ['engines', 'pluginApi'], message: 'channels need plugin API 1.1 or later (e.g. "^1.1.0")' });+ }for (const c of m.contributes.commands) {if (RESERVED_COMMANDS.has(c.name)) ctx.addIssue({ code: 'custom', path: ['contributes', 'commands'], message: `/${c.name} is a built-in Mercury command and can't be used by a plugin` });}@@ -225,6 +241,8 @@ export interface PluginListItem {verified: boolean;tools: string[];commands: string[];+ /** Plugin API 1.1: the chat channel this plugin provides, and its live state. */+ channel?: { type: string; state?: string; detail?: string; account?: string };permissions?: PluginManifest['permissions'];disabled?: PluginStateEntry['disabled'];lastError?: string;diff --git a/src/ui/input-composer.tsx b/src/ui/input-composer.tsxindex 3ac091d0..15b9a35d 100644--- a/src/ui/input-composer.tsx+++ b/src/ui/input-composer.tsx@@ -135,6 +135,8 @@ export const SLASH_COMMANDS: readonly string[] = ['/plugins rollback ','/plugins uninstall ','/plugins set ',+ '/plugins pair ',+ '/plugins unlink ','/plugins help','/stream','/saver',diff --git a/src/utils/manual.ts b/src/utils/manual.tsindex a46b7a2f..7b705267 100644--- a/src/utils/manual.ts+++ b/src/utils/manual.ts@@ -157,6 +157,7 @@ export function getManual(): string {['/plugins update [id]', 'Update plugins from the catalog'],['/plugins rollback <id>', 'Go back to the previous version'],['/plugins uninstall <id> [--purge]', 'Remove a plugin (keeps data unless --purge)'],+ ['/plugins pair <id> <phone>', 'Link a channel plugin (e.g. WhatsApp) with a pairing code'],['/permissions', 'Change permission mode (Ask Me / Allow All)'],['/models', 'List configured providers and their models'],['/models use <provider>', 'Switch the default model (saved across restarts)'],diff --git a/src/web/api/plugins.ts b/src/web/api/plugins.tsindex 06cd7aeb..c36c5109 100644--- a/src/web/api/plugins.ts+++ b/src/web/api/plugins.ts@@ -109,6 +109,38 @@ plugins.post('/api/plugins/:id/settings', async (c) => {}});+// Plugin API 1.1 channels. The status includes a live QR code, and linking+// gives an account to Mercury, so all of these are loopback-only.+plugins.get('/api/plugins/:id/channel', (c) => {+ const denied = localOnly(c);+ if (denied) return denied;+ return c.json({ status: getPluginManager().channelStatus(c.req.param('id')) });+});++plugins.post('/api/plugins/:id/pair', async (c) => {+ const denied = localOnly(c);+ if (denied) return denied;+ const body = (await c.req.json().catch(() => ({}))) as { method?: unknown; phone?: unknown };+ const method = body.method === 'code' ? 'code' : 'qr';+ const phone = typeof body.phone === 'string' && /^\+?[\d\s-]{6,20}$/.test(body.phone) ? body.phone : undefined;+ try {+ return c.json({ status: await svc().pair(c.req.param('id'), { method, phone }) });+ } catch (err) {+ return fail(c, err);+ }+});++plugins.post('/api/plugins/:id/unlink', async (c) => {+ const denied = localOnly(c);+ if (denied) return denied;+ try {+ await svc().unlink(c.req.param('id'));+ return c.json({ ok: true });+ } catch (err) {+ return fail(c, err);+ }+});+plugins.delete('/api/plugins/:id', async (c) => {const denied = localOnly(c);if (denied) return denied;diff --git a/website/docs/reference/plugins.mdx b/website/docs/reference/plugins.mdxindex e3c26050..0758bd4c 100644--- a/website/docs/reference/plugins.mdx+++ b/website/docs/reference/plugins.mdx@@ -143,6 +143,47 @@ What your server receives:Write logs to stderr. Stdout is the protocol channel.+## Chat channels (plugin API 1.1)++An out-of-process plugin can provide a chat channel (today: `whatsapp`).+Declare it and require API 1.1:++```json+"engines": { "mercury": ">=1.4.0 <2.0.0", "pluginApi": "^1.1.0" },+"contributes": { "channel": { "type": "whatsapp" } },+"settings": { "version": 1, "fields": {+ "owner": { "type": "string", "description": "The owner's phone number" },+ "members": { "type": "string", "description": "Other numbers allowed to chat, comma separated" },+ "allowGroups": { "type": "boolean", "default": false }+} }+```++Mercury sends `capabilities.experimental["mercury/channel"]` in+`initialize`. After that, the same stdio connection carries the following+messages.++| Direction | Message | Params |+|---|---|---|+| plugin → Mercury (notification) | `mercury/channel/status` | `state` (`starting`, `needs-pairing`, `pairing`, `connected`, `disconnected`, `logged-out`, `error`), `detail?`, `account?`, `qr?`, `pairCode?` |+| plugin → Mercury (notification) | `mercury/channel/message` | `id`, `chatId`, `senderId`, `senderPhone?`, `senderName?`, `isGroup?`, `fromMe?`, `text?`, `attachments?` (each with `kind`, `path`, `mime?`, `name?`), `timestamp?` |+| Mercury → plugin (request) | `mercury/channel/send` | `chatId`, `text` |+| Mercury → plugin (request) | `mercury/channel/sendFile` | `chatId`, `path`, `caption?` |+| Mercury → plugin (request) | `mercury/channel/typing` | `chatId`, `on` |+| Mercury → plugin (request) | `mercury/channel/pair` | `method` (`qr` or `code`), `phone?` |+| Mercury → plugin (request) | `mercury/channel/unlink` | none |++Mercury, not the plugin, decides who can talk to the agent:++- **Access:** only the `owner` number and listed `members` get through.+ Unknown senders are dropped, groups are ignored unless `allowGroups` is+ on, and your own messages are never answered.+- **Formatting:** Mercury converts Markdown to the channel's formatting and+ splits long replies.+- **Approvals:** prompts are answered by a text reply: 1 for yes, 2 for no,+ 3 for always.+- **Linking:** owners link the account with `mercury plugins pair ID` (QR+ code) or `/plugins pair ID PHONE` (pairing code).+## Publishing`mercury plugins pack .` writes `ID-VERSION.tgz` and prints its SHA-256 and