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(plugins): guided setup on install and a /plugins <id> menu for every plugin

Salman Qureshiff364ab0fb38
diff --git a/plugins/whatsapp/README.md b/plugins/whatsapp/README.md
index ac448abb..5c8d47ae 100644
--- a/plugins/whatsapp/README.md
+++ b/plugins/whatsapp/README.md
@@ -11,32 +11,24 @@ account is needed.
## Set up
-1. Install it and set your own number as the owner:
-
- ```sh
- mercury plugins install whatsapp
- mercury plugins set whatsapp owner +15551234567
- ```
-
- The owner is the number you'll chat *from*. Only the owner, and any
- numbers you add to `members`, can talk to Mercury.
-
-2. Link the spare number. Either scan a QR code in the terminal:
-
- ```sh
- mercury plugins pair whatsapp
- ```
-
- Then, on the phone with the spare number, go to WhatsApp → Settings →
- Linked devices → Link a device.
+```sh
+mercury plugins install whatsapp
+```
- Or get a pairing code, which also works from chat:
+Mercury then walks you through setup, one question at a time. It works the
+same in a chat (`/plugins install whatsapp`) or in the dashboard:
- ```sh
- mercury plugins pair whatsapp --code +15550001111
- ```
+1. **Which number will you chat from?** This is your own number, and only
+ it can talk to Mercury.
+2. **What can Mercury do in your chat?** General (chat only) or Extended
+ (memory, files, tools).
+3. **Answer your voice calls?**
+4. **Link the spare number:** a pairing code you type on the spare phone,
+ or a QR code to scan.
-3. Message the spare number from your own number. Mercury answers there.
+Change anything later with `/plugins whatsapp` (or `mercury plugins open
+whatsapp`): pick a setting from the list, link or unlink, send a test
+message, turn it off, or uninstall.
## What works
diff --git a/plugins/whatsapp/mercury-plugin.template.json b/plugins/whatsapp/mercury-plugin.template.json
index 5cce9d3b..a86daa46 100644
--- a/plugins/whatsapp/mercury-plugin.template.json
+++ b/plugins/whatsapp/mercury-plugin.template.json
@@ -52,23 +52,34 @@
"fields": {
"owner": {
"type": "string",
- "description": "Your own WhatsApp number (with country code). Only this number can talk to Mercury.",
- "default": ""
+ "description": "Your own WhatsApp number. Only this number can talk to Mercury.",
+ "default": "",
+ "label": "Which number will you chat from?",
+ "setup": true,
+ "required": true,
+ "format": "phone"
},
"access": {
"type": "enum",
- "description": "What Mercury may do in your chat: general (chat only) or extended (memory, files, tools). 'ask' asks you after linking.",
+ "label": "What can Mercury do in your chat?",
+ "description": "You can change this anytime in /plugins whatsapp.",
"options": [
- "ask",
"general",
"extended"
],
- "default": "ask"
+ "default": "general",
+ "setup": true,
+ "optionLabels": {
+ "general": "General: chat and general knowledge only. No tools, files or personal memory.",
+ "extended": "Extended: memory, files, tools and actions. Anything risky still asks you first."
+ }
},
"members": {
"type": "string",
"description": "Other numbers allowed to chat with Mercury, comma separated (they can't run admin commands).",
- "default": ""
+ "default": "",
+ "label": "Other numbers allowed to chat",
+ "format": "text"
},
"memberAccess": {
"type": "enum",
@@ -77,27 +88,37 @@
"general",
"extended"
],
- "default": "general"
+ "default": "general",
+ "label": "What can those numbers do?",
+ "optionLabels": {
+ "general": "General: chat only",
+ "extended": "Extended (never more than you)"
+ }
},
"allowGroups": {
"type": "boolean",
"description": "Answer in WhatsApp groups (owner and members only).",
- "default": false
+ "default": false,
+ "label": "Answer in WhatsApp groups"
},
"answerCalls": {
"type": "boolean",
"description": "Answer voice calls from the owner.",
- "default": true
+ "default": true,
+ "label": "Answer your voice calls",
+ "setup": true
},
"maxCallsPerHour": {
"type": "number",
"description": "Most times Mercury may call you in an hour.",
- "default": 4
+ "default": 4,
+ "label": "Most calls from Mercury per hour"
},
"maxCallMinutes": {
"type": "number",
"description": "Longest a call can last, in minutes.",
- "default": 15
+ "default": 15,
+ "label": "Longest call, in minutes"
},
"voice": {
"type": "enum",
@@ -114,12 +135,14 @@
"shimmer",
"verse"
],
- "default": "marin"
+ "default": "marin",
+ "label": "Mercury's voice on calls"
},
"voiceModel": {
"type": "string",
"description": "OpenAI realtime model for calls.",
- "default": "gpt-realtime"
+ "default": "gpt-realtime",
+ "label": "Voice model (OpenAI)"
}
}
}
diff --git a/src/cli/plugins-cli.ts b/src/cli/plugins-cli.ts
index c33e605c..a4576634 100644
--- a/src/cli/plugins-cli.ts
+++ b/src/cli/plugins-cli.ts
@@ -21,7 +21,8 @@ async function run(line: string): Promise<void> {
};
let failed = false;
await handlePluginsCommand(line, msg, {
- type: 'cli',
+ // 'cli-batch': a one-shot shell command; guided setup runs interactively below instead.
+ type: 'cli-batch',
send: async (text) => {
if (text.startsWith('✗')) failed = true;
// Chat wording says "/plugins x"; in a shell it's "mercury plugins x".
@@ -49,7 +50,25 @@ export function registerPluginsCli(program: Command): void {
.alias('add')
.description('Install from the catalog (id), a folder, a .tgz, an https URL or github:owner/repo')
.option('-y, --yes', 'Skip the confirmation')
- .action((source: string, opts: { yes?: boolean }) => run(`/plugins install ${source}${opts.yes ? ' --yes' : ''}`));
+ .option('--no-setup', 'Don\'t walk through the plugin\'s setup afterwards')
+ .action(async (source: string, opts: { yes?: boolean; setup?: boolean }) => {
+ const before = process.exitCode;
+ await run(`/plugins install ${source}${opts.yes ? ' --yes' : ''}`);
+ if (!opts.yes || process.exitCode !== before || opts.setup === false || !process.stdin.isTTY) return;
+ const id = await installedIdFor(source);
+ if (id) await interactive('setup', id);
+ });
+
+ plugins
+ .command('setup <id>')
+ .description('Walk through a plugin\'s setup (settings, and linking for channels like WhatsApp)')
+ .action((id: string) => interactive('setup', id));
+
+ plugins
+ .command('open <id>')
+ .alias('menu')
+ .description('A plugin\'s menu: settings, link, turn off, uninstall')
+ .action((id: string) => interactive('menu', id));
plugins.command('enable <id>').description('Turn a plugin on').action((id: string) => run(`/plugins enable ${id}`));
plugins.command('disable <id>').description('Turn a plugin off (keeps its data and settings)').action((id: string) => run(`/plugins disable ${id}`));
plugins.command('update [id]').description('Update one plugin, or all from the catalog').action((id?: string) => run(`/plugins update ${id ?? 'all'}`));
@@ -260,3 +279,53 @@ async function pairChannel(id: string, phone?: string): Promise<void> {
process.exitCode = 1;
}
}
+
+/** The plugin id a just-installed source refers to (catalog id, or read from the package). */
+async function installedIdFor(source: string): Promise<string | null> {
+ const { getPluginService } = await import('../plugins/service.js');
+ const { items } = await getPluginService().list();
+ const installed = items.filter((i) => i.installedVersion);
+ const direct = installed.find((i) => i.id === source);
+ if (direct) return direct.id;
+ // A path or URL: the most recently installed one is the best guess; ask the state file.
+ const { readState } = await import('../plugins/store.js');
+ const state = readState();
+ const latest = Object.entries(state.plugins).sort((a, b) => Date.parse(b[1].updatedAt) - Date.parse(a[1].updatedAt))[0];
+ return latest?.[0] ?? null;
+}
+
+/** Run a guided dialog in the terminal. */
+async function interactive(kind: 'setup' | 'menu', id: string): Promise<void> {
+ const { getPluginService } = await import('../plugins/service.js');
+ const { PluginDialog, renderPrompt } = await import('../plugins/dialog.js');
+ const svc = getPluginService();
+ const dialog = kind === 'setup' ? await PluginDialog.setup(svc, id) : await PluginDialog.menu(svc, id, true);
+ if (!dialog) {
+ console.log(kind === 'setup' ? ` ${id} has nothing to set up (or isn't installed).` : ` No plugin called "${id}".`);
+ return;
+ }
+ if (!process.stdin.isTTY) {
+ console.log(' This needs an interactive terminal. In chat, use /plugins ' + (kind === 'setup' ? `setup ${id}` : id) + '.');
+ process.exitCode = 1;
+ return;
+ }
+ const { createInterface } = await import('node:readline/promises');
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
+ const clean = (t: string) => t.replace(/\*([^*\n]+)\*/g, (_m, x) => chalk.bold(x));
+ try {
+ for (;;) {
+ const prompt = await dialog.current();
+ if (!prompt) break;
+ console.log('');
+ console.log(clean(renderPrompt(prompt, false)).replace(/^/gm, ' '));
+ const answer = await rl.question(chalk.cyan(' › '));
+ const r = await dialog.answer(answer);
+ if (r.message) console.log(clean(r.message).replace(/^/gm, ' '));
+ if (r.finished) break;
+ }
+ } finally {
+ rl.close();
+ }
+ console.log('');
+ setTimeout(() => process.exit(process.exitCode ?? 0), 50).unref();
+}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 8f44a7dc..e44a0472 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -96,7 +96,7 @@ import { createTaskSurface } from './task-surface.js';
import { buildFileChangePreview } from '../utils/file-preview.js';
import { whatsNewText } from '../utils/whats-new.js';
import { handleBotsCommand as handleBotsCommandImpl } from './commands/bots-command.js';
-import { handlePluginsCommand, tryPluginCommand, pluginCommandHelp } from '../plugins/commands.js';
+import { handlePluginsCommand, tryPluginCommand, pluginCommandHelp, hasPluginDialog, answerPluginDialog } from '../plugins/commands.js';
import { handleChatCommand as handleChatCommandImpl } from './commands/chat-command.js';
import { handleBgCommand as handleBgCommandImpl } from './commands/bg-command.js';
import { handleSaverCommand as handleSaverCommandImpl } from './commands/saver-command.js';
@@ -750,6 +750,17 @@ export class Agent {
return;
}
+ // A plugin setup or menu waiting for an answer in this chat ("2", "+91…").
+ if (!trimmed.startsWith('/') && hasPluginDialog(msg.channelId)) {
+ const channel = this.channels.getChannelForMessage(msg);
+ if (channel) {
+ answerPluginDialog(trimmed, msg, channel).catch((err) => {
+ logger.error({ err: (err as any)?.message ?? err }, 'plugin dialog failed');
+ });
+ return;
+ }
+ }
+
// /plugins is fast-path like /bots: installing or toggling a plugin must
// work while a turn is running (that's often when you notice you need it).
if (/^\/plugins?(\s|$)/.test(trimmed)) {
diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.ts
index 71521154..e1b75d9e 100644
--- a/src/plugins/channel-bridge.ts
+++ b/src/plugins/channel-bridge.ts
@@ -158,8 +158,6 @@ export class PluginChannel extends BaseChannel {
/** Phone chats: no per-step messages or "Working…" heartbeats; keep "typing…" alive instead. */
readonly quietProgress = true;
- /** Owner chats waiting for the one-time "how much can Mercury do here?" answer. */
- private awaitingAccessChoice = new Set<string>();
get pluginId(): string {
return this.manifest.id;
@@ -307,9 +305,9 @@ export class PluginChannel extends BaseChannel {
pairCode: str(p.pairCode, 32),
at: Date.now(),
});
- if (state === 'connected' && prev !== 'connected' && this.ownerAccess() === 'ask') {
- // Linked: ask the owner once how much Mercury may do here.
- setTimeout(() => this.askAccessChoice(), 3000).unref?.();
+ if (state === 'connected' && prev === 'pairing') {
+ // A fresh link (not a reconnect): confirm it where the owner set it up.
+ this.notifyOwner(`✅ ${this.manifest.name} linked${this.status.account ? ` as +${this.status.account}` : ''}. Message that number from your own to talk to me. Settings: /plugins ${this.manifest.id}`);
}
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}.`);
@@ -354,7 +352,6 @@ export class PluginChannel extends BaseChannel {
}
const text = typeof p.text === 'string' ? p.text.slice(0, 20_000) : '';
- if (role === 'admin' && text && this.handleAccessReply(p.chatId, text)) return;
const pending = this.pending.get(p.chatId);
if (pending && text) {
const answer = normalizeReply(text);
@@ -397,19 +394,14 @@ export class PluginChannel extends BaseChannel {
channelGuidance: this.guidance(role, p.isGroup === true),
},
};
- if (role === 'admin' && this.ownerAccess() === 'ask' && !this.awaitingAccessChoice.has(p.chatId)) {
- // Not chosen yet: answer at General, and ask (once) after this reply.
- setTimeout(() => this.askAccessChoice(), 1500).unref?.();
- }
this.emit(msg);
}
// ── access levels ────────────────────────────────────────────────────
- /** The owner's chosen level: 'ask' until they pick one after linking. */
- ownerAccess(): 'ask' | 'general' | 'extended' {
- const v = String(this.settings().access ?? 'ask');
- return v === 'general' || v === 'extended' ? v : 'ask';
+ /** The owner's level (chosen during setup; General until they pick Extended). */
+ ownerAccess(): 'general' | 'extended' {
+ return String(this.settings().access ?? 'general') === 'extended' ? 'extended' : 'general';
}
/** What a sender may do here. Members never exceed the owner's level. */
@@ -437,55 +429,12 @@ export class PluginChannel extends BaseChannel {
: 'Access: Extended for members. You may use tools, but never share the owner\'s private details (memory, files, contacts, accounts) with this member unless the owner told you to.');
} else {
lines.push(role === 'admin'
- ? 'Access: General. In this chat you have no tools, files or personal memory. Help with conversation and general knowledge. If something needs tools or personal context, say so in one line and that they can switch this chat to Extended by sending: /access extended'
+ ? `Access: General. In this chat you have no tools, files or personal memory. Help with conversation and general knowledge. If something needs tools or personal context, say so in one line, and that they can switch this chat to Extended in /plugins ${this.manifest.id}.`
: 'Access: General. You have no tools, files or memory here, and must not share anything personal about the owner. Help with general questions only. If they ask for more, say only the owner can allow it.');
}
return lines.join('\n');
}
- private askAccessChoice(): void {
- const chat = this.defaultTarget();
- if (!chat || this.ownerAccess() !== 'ask' || this.awaitingAccessChoice.has(chat)) return;
- this.awaitingAccessChoice.add(chat);
- void this.send([
- `☿ How much should I do for you on ${this.manifest.name}?`,
- '',
- '*1 · General*: chat and general knowledge only. No tools, files or personal memory.',
- '*2 · Extended*: everything I can do elsewhere (memory, files, tools, actions). Anything risky still asks you first.',
- '',
- 'Reply *1* or *2*. You can change it anytime with /access general or /access extended.',
- ].join('\n')).catch(() => this.awaitingAccessChoice.delete(chat));
- }
-
- /** Owner messages that set the access level. Returns true when handled (not passed to the agent). */
- private handleAccessReply(chatId: string, text: string): boolean {
- const t = text.trim().toLowerCase().replace(/[.!]/g, '');
- let choice: 'general' | 'extended' | null = null;
- const cmd = /^\/access(?:\s+(\S+))?$/.exec(t);
- if (cmd) {
- if (!cmd[1]) {
- void this.send(`Access here is *${this.ownerAccess() === 'extended' ? 'Extended' : 'General'}*. Change it with /access general or /access extended.`, `${this.type}:${chatId}`).catch(() => {});
- return true;
- }
- choice = cmd[1] === 'extended' || cmd[1] === 'full' || cmd[1] === '2' ? 'extended' : cmd[1] === 'general' || cmd[1] === '1' ? 'general' : null;
- if (!choice) {
- void this.send('Use /access general or /access extended.', `${this.type}:${chatId}`).catch(() => {});
- return true;
- }
- } else if (this.awaitingAccessChoice.size && (t === '1' || t === '2' || t === 'general' || t === 'extended')) {
- choice = t === '2' || t === 'extended' ? 'extended' : 'general';
- } else {
- return false;
- }
- this.awaitingAccessChoice.clear();
- void this.saveSetting('access', choice)
- .then(() => this.send(choice === 'extended'
- ? '✅ *Extended*: I can use my memory, files and tools here. I\'ll still ask before anything risky. Switch back anytime with /access general.'
- : '✅ *General*: chat and general knowledge only here. Switch anytime with /access extended.', `${this.type}:${chatId}`))
- .catch((err) => this.send(`Couldn't change access: ${(err as Error).message}`, `${this.type}:${chatId}`).catch(() => {}));
- return true;
- }
-
// ── Channel ──────────────────────────────────────────────────────────
async start(): Promise<void> { /* the plugin runtime drives the connection */ }
diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.ts
index f207e3f9..89b32eb5 100644
--- a/src/plugins/channel.test.ts
+++ b/src/plugins/channel.test.ts
@@ -277,45 +277,31 @@ describe('plugin channels (plugin API 1.1)', () => {
return existsSync(f) ? readFileSync(f, 'utf8').trim().split('\n').map((l) => JSON.parse(l).text as string) : [];
};
- it('before the owner chooses: General, told it is on WhatsApp, and asked once', async () => {
+ it('General by default, and Mercury is told it is on WhatsApp and where to change it', async () => {
await installChannel();
await inject({ id: 'g1', senderPhone: '15550002', text: 'hello' });
- await inject({ id: 'g2', senderPhone: '15550002', text: 'and again' });
expect(received[0].metadata?.channelAccess).toBe('general');
const g = String(received[0].metadata?.channelGuidance);
expect(g).toMatch(/talking with the owner \(the person you work for\) on WhatsApp, a phone chat app/);
expect(g).toMatch(/No code blocks/);
- expect(g).toMatch(/Access: General[\s\S]*\/access extended/);
- await waitFor(() => sentTexts().some((t) => /How much should I do/.test(t)), 4000);
- await sleep(1600);
- expect(sentTexts().filter((t) => /How much should I do/.test(t))).toHaveLength(1);
+ expect(g).toMatch(/Access: General[\s\S]*\/plugins whatsapp/);
+ expect(sentTexts()).toEqual([]); // no unsolicited prompts in the chat
});
- it('replying 2 switches to Extended live, without restarting the plugin', async () => {
+ it('switching to Extended applies live, without restarting the plugin', async () => {
await installChannel();
- const before = (await mgr.info('whatsapp'))?.running;
- await inject({ id: 'e1', senderPhone: '15550002', text: 'hi' });
- await waitFor(() => sentTexts().some((t) => /How much should I do/.test(t)), 4000);
- await inject({ id: 'e2', senderPhone: '15550002', text: '2' });
- await waitFor(() => sentTexts().some((t) => /Extended/.test(t) && /✅/.test(t)));
- await inject({ id: 'e3', senderPhone: '15550002', text: 'what is on my calendar' });
- expect(received.map((m) => m.content)).toEqual(['hi', 'what is on my calendar']); // "2" never reached the agent
- expect(received[1].metadata?.channelAccess).toBe('extended');
- expect(String(received[1].metadata?.channelGuidance)).toMatch(/Access: Extended/);
- expect(before).toBe(true);
- expect(getPluginChannel('whatsapp')?.isReady() !== undefined).toBe(true);
+ await mgr.setSetting('whatsapp', 'access', 'extended');
+ await inject({ id: 'e1', senderPhone: '15550002', text: 'what is on my calendar' });
+ expect(received[0].metadata?.channelAccess).toBe('extended');
+ expect(String(received[0].metadata?.channelGuidance)).toMatch(/Access: Extended/);
expect(registered).toHaveLength(1); // same channel instance: no restart happened
});
- it('/access general goes back; /access shows the level', async () => {
+ it('a fresh link (not a reconnect) is confirmed to the owner', async () => {
await installChannel();
- await mgr.setSetting('whatsapp', 'access', 'extended');
- await inject({ id: 'a1', senderPhone: '15550002', text: '/access' });
- await inject({ id: 'a2', senderPhone: '15550002', text: '/access general' });
- await waitFor(() => sentTexts().some((t) => /✅ \*General\*/.test(t)));
- await inject({ id: 'a3', senderPhone: '15550002', text: 'hello' });
- expect(sentTexts().some((t) => /Access here is \*Extended\*/.test(t))).toBe(true);
- expect(received.map((m) => [m.content, m.metadata?.channelAccess])).toEqual([['hello', 'general']]);
+ await mgr.pair('whatsapp', { method: 'qr' });
+ await waitFor(() => notices.some((n) => /WhatsApp linked as \+15550001/.test(n)));
+ expect(notices.find((n) => /linked/.test(n))).toMatch(/\/plugins whatsapp/);
});
it('members never exceed the owner, and default to General', async () => {
diff --git a/src/plugins/commands.test.ts b/src/plugins/commands.test.ts
index b4987009..e3b174ed 100644
--- a/src/plugins/commands.test.ts
+++ b/src/plugins/commands.test.ts
@@ -26,3 +26,44 @@ describe('reserved command names', () => {
expect(JSON.stringify(r.error?.issues)).toMatch(/\/help is a built-in Mercury command/);
});
});
+
+describe('guided setup from chat', () => {
+ it('install starts setup; numbered replies answer it; /plugins <id> opens the menu', async () => {
+ const { tempHome, inProcessPlugin } = await import('./test-fixtures.js');
+ const { handlePluginsCommand, answerPluginDialog, hasPluginDialog } = await import('./commands.js');
+ const { resetPluginManager } = await import('./manager.js');
+ const { readSettings } = await import('./store.js');
+ const env = tempHome();
+ resetPluginManager();
+ try {
+ const dir = inProcessPlugin(env.home, {
+ id: 'greeter',
+ manifest: { settings: { version: 1, fields: {
+ greeting: { type: 'string', label: 'How should I greet people?', setup: true, required: true },
+ tone: { type: 'enum', options: ['warm', 'formal'], default: 'warm', label: 'Tone', setup: true, optionLabels: { warm: 'Warm and friendly', formal: 'Formal' } },
+ } } },
+ });
+ const sent: string[] = [];
+ const channel = { type: 'cli', send: async (t: string) => { sent.push(t); } };
+ const msg = { id: '1', channelId: 'cli:test', channelType: 'cli' as const, senderId: 'owner', content: '', timestamp: Date.now() };
+
+ await handlePluginsCommand(`/plugins install ${dir} --yes`, msg, channel);
+ expect(sent.at(-1)).toMatch(/Installed[\s\S]*greeter setup \(1\/2\)[\s\S]*How should I greet people\?/);
+ expect(hasPluginDialog('cli:test')).toBe(true);
+ await answerPluginDialog('Salaam', msg, channel);
+ expect(sent.at(-1)).toMatch(/✅ How should I greet people\?: Salaam[\s\S]*Tone[\s\S]*1\* · Warm and friendly[\s\S]*2\* · Formal/);
+ await answerPluginDialog('2', msg, channel);
+ await answerPluginDialog('1', msg, channel); // "Done"
+ expect(hasPluginDialog('cli:test')).toBe(false);
+ expect(readSettings('greeter')).toMatchObject({ greeting: 'Salaam', tone: 'formal' });
+
+ await handlePluginsCommand('/plugins greeter', msg, channel);
+ expect(sent.at(-1)).toMatch(/How should I greet people\?: Salaam[\s\S]*Tone: Formal[\s\S]*Change a setting/);
+ await answerPluginDialog('cancel', msg, channel);
+ expect(hasPluginDialog('cli:test')).toBe(false);
+ } finally {
+ resetPluginManager();
+ env.restore();
+ }
+ });
+});
diff --git a/src/plugins/commands.ts b/src/plugins/commands.ts
index 3a41e72a..0247849a 100644
--- a/src/plugins/commands.ts
+++ b/src/plugins/commands.ts
@@ -21,6 +21,7 @@ import { getPluginService } from './service.js';
import { getCatalog } from './catalog.js';
import { getPluginCommand, listPluginCommands } from './tool-bridge.js';
import { RESERVED_COMMANDS, type PluginListItem } from './types.js';
+import { PluginDialog, renderPrompt } from './dialog.js';
export { RESERVED_COMMANDS };
@@ -103,6 +104,8 @@ function actionsFor(i: PluginListItem): Array<{ label: string; command: string }
const HELP = [
'Usage:',
' /plugins list installed and available plugins',
+ ' /plugins <id> that plugin\'s menu: settings, link, turn off, uninstall',
+ ' /plugins setup <id> walk through its setup again',
' /plugins search <text> find plugins',
' /plugins info <id> details, tools and permissions',
' /plugins install <id|path|url> install (asks to confirm)',
@@ -119,6 +122,67 @@ function isMember(msg: ChannelMessage): boolean {
return msg.senderRole === 'member';
}
+// ── guided dialogs (setup, /plugins <id> menu) ───────────────────────────
+
+const DIALOG_TTL_MS = 15 * 60_000;
+const dialogs = new Map<string, { dialog: PluginDialog; at: number }>();
+
+function hasButtons(channel: ChannelLike): boolean {
+ return typeof channel.sendWithActions === 'function' && channel.type === 'telegram';
+}
+
+/** A dialog is waiting for an answer in this chat. */
+export function hasPluginDialog(chatId: string): boolean {
+ const d = dialogs.get(chatId);
+ if (d && Date.now() - d.at > DIALOG_TTL_MS) dialogs.delete(chatId);
+ return dialogs.has(chatId);
+}
+
+async function showDialog(dialog: PluginDialog, msg: ChannelMessage, channel: ChannelLike, lead?: string): Promise<void> {
+ const to = msg.channelId;
+ const prompt = await dialog.current();
+ if (!prompt) {
+ dialogs.delete(to);
+ if (lead) await channel.send(lead, to);
+ return;
+ }
+ dialogs.set(to, { dialog, at: Date.now() });
+ const text = [lead, renderPrompt(prompt, hasButtons(channel))].filter(Boolean).join('\n\n');
+ if (hasButtons(channel) && prompt.options?.length) {
+ const rows = prompt.options.map((o, i) => [{ label: o.label.slice(0, 40), command: `/plugins pick ${i + 1}` }]);
+ await channel.sendWithActions!(text, rows, to);
+ } else {
+ await channel.send(text, to);
+ }
+}
+
+/** Answer the dialog open in this chat (a number, an option's words, or free text). */
+export async function answerPluginDialog(text: string, msg: ChannelMessage, channel: ChannelLike): Promise<void> {
+ const entry = dialogs.get(msg.channelId);
+ if (!entry) return;
+ try {
+ const r = await entry.dialog.answer(text);
+ if (r.finished) {
+ dialogs.delete(msg.channelId);
+ if (r.message) await channel.send(r.message, msg.channelId);
+ return;
+ }
+ await showDialog(entry.dialog, msg, channel, r.message);
+ } catch (err) {
+ await channel.send(`✗ ${(err as Error).message}`, msg.channelId);
+ }
+}
+
+async function openDialog(dialog: PluginDialog | null, msg: ChannelMessage, channel: ChannelLike, fallback: string, lead?: string): Promise<void> {
+ if (!dialog) {
+ await channel.send([lead, fallback].filter(Boolean).join('\n\n'), msg.channelId);
+ return;
+ }
+ await showDialog(dialog, msg, channel, lead);
+}
+
+const SUBCOMMANDS = new Set(['list', 'ls', 'help', 'search', 'info', 'install', 'add', 'enable', 'disable', 'update', 'upgrade', 'rollback', 'uninstall', 'remove', 'set', 'pair', 'unlink', 'setup', 'pick', 'cancel', 'test']);
+
export async function handlePluginsCommand(trimmed: string, msg: ChannelMessage, channel: ChannelLike): Promise<void> {
const to = msg.channelId;
const reply = (text: string) => channel.send(text, to);
@@ -126,9 +190,15 @@ export async function handlePluginsCommand(trimmed: string, msg: ChannelMessage,
const yes = tokens.includes('--yes') || tokens.includes('-y');
const purge = tokens.includes('--purge');
const args = tokens.filter((t) => !t.startsWith('--') && t !== '-y');
- const [sub = 'list', target, ...rest] = args;
+ let [sub = 'list', target, ...rest] = args;
const mgr = getPluginService();
- const mutating = ['install', 'enable', 'disable', 'update', 'rollback', 'uninstall', 'remove', 'set', 'pair', 'unlink'].includes(sub);
+ // `/plugins whatsapp` opens that plugin's menu.
+ if (sub && !SUBCOMMANDS.has(sub)) {
+ rest = [];
+ target = sub;
+ sub = 'menu';
+ }
+ const mutating = ['install', 'enable', 'disable', 'update', 'rollback', 'uninstall', 'remove', 'set', 'pair', 'unlink', 'setup', 'test'].includes(sub);
if (mutating && isMember(msg)) {
await reply('Only the owner or an admin can change plugins.');
return;
@@ -159,6 +229,27 @@ export async function handlePluginsCommand(trimmed: string, msg: ChannelMessage,
case 'help':
await reply(HELP);
return;
+ case 'menu': {
+ const d = await PluginDialog.menu(mgr, target!, !isMember(msg));
+ await openDialog(d, msg, channel, `No plugin called "${target}". Try /plugins.`);
+ return;
+ }
+ case 'setup': {
+ if (!target) { await reply('Usage: /plugins setup <id>'); return; }
+ await openDialog(await PluginDialog.setup(mgr, target), msg, channel, `"${target}" has nothing to set up (or isn't installed).`);
+ return;
+ }
+ case 'pick':
+ if (!hasPluginDialog(msg.channelId)) { await reply('That menu has expired. Open it again with /plugins <id>.'); return; }
+ await answerPluginDialog(target ?? '', msg, channel);
+ return;
+ case 'cancel':
+ if (hasPluginDialog(msg.channelId)) await answerPluginDialog('cancel', msg, channel);
+ return;
+ case 'test':
+ if (!target) { await reply('Usage: /plugins test <id>'); return; }
+ await reply(`✅ ${await mgr.testChannel(target)}`);
+ return;
case 'search': {
const q = [target, ...rest].join(' ').toLowerCase();
if (!q) { await reply('Usage: /plugins search <text>'); return; }
@@ -191,9 +282,13 @@ export async function handlePluginsCommand(trimmed: string, msg: ChannelMessage,
const r = await mgr.install(target);
const info = await mgr.info(r.id);
const verifiedNote = r.verified ? 'checksum verified' : (r.tier === 'local' ? 'unverified source' : 'not verified');
- await reply(r.unchanged
+ const done = r.unchanged
? `${r.name} ${r.version} is already installed${info?.enabled ? ' and enabled' : ''}.`
- : `✅ Installed ${r.name} ${r.version} (${verifiedNote})${info?.status === 'enabled' ? ' and enabled' : ''}.${info?.tools.length ? `\nTools: ${info.tools.join(', ')}` : ''}${r.previousVersion ? `\nPrevious version ${r.previousVersion} kept for /plugins rollback ${r.id}.` : ''}`);
+ : `✅ Installed ${r.name} ${r.version} (${verifiedNote})${info?.status === 'enabled' ? ' and enabled' : ''}.${info?.tools.length ? `\nTools: ${info.tools.join(', ')}` : ''}${r.previousVersion ? `\nPrevious version ${r.previousVersion} kept for /plugins rollback ${r.id}.` : ''}`;
+ // Walk the owner through the plugin's setup right away (CLI runs its own interactive setup).
+ const setup = channel.type === 'cli-batch' || r.unchanged ? null : await PluginDialog.setup(mgr, r.id);
+ if (setup) await showDialog(setup, msg, channel, done);
+ else await reply(done);
return;
}
case 'enable':
diff --git a/src/plugins/dialog.test.ts b/src/plugins/dialog.test.ts
new file mode 100644
index 00000000..9a40d151
--- /dev/null
+++ b/src/plugins/dialog.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from 'vitest';
+import { PluginDialog, renderPrompt } from './dialog.js';
+import type { PluginService } from './service.js';
+import type { PluginListItem } from './types.js';
+
+function fakeService(overrides: Partial<PluginListItem> = {}) {
+ const values: Record<string, unknown> = { owner: '', access: 'general', answerCalls: true, members: '' };
+ const calls: string[] = [];
+ let linked = false;
+ const item = (): PluginListItem => ({
+ id: 'whatsapp', name: 'WhatsApp', description: 'Chat with Mercury.', kind: 'out-of-process', tier: 'official',
+ status: 'enabled', installedVersion: '0.1.0', enabled: true, running: true, verified: true, tools: [], commands: [],
+ channel: { type: 'whatsapp', state: linked ? 'connected' : 'needs-pairing', account: linked ? '639759021037' : undefined },
+ settings: [
+ { key: 'owner', type: 'string', description: '', value: values.owner, label: 'Which number will you chat from?', setup: true, required: true, format: 'phone' },
+ { key: 'access', type: 'enum', description: '', options: ['general', 'extended'], value: values.access, label: 'What can Mercury do in your chat?', setup: true, optionLabels: { general: 'General: chat only', extended: 'Extended: memory, files, tools' } },
+ { key: 'answerCalls', type: 'boolean', description: '', value: values.answerCalls, label: 'Answer your voice calls', setup: true },
+ { key: 'members', type: 'string', description: '', value: values.members, label: 'Other numbers allowed to chat' },
+ ],
+ ...overrides,
+ });
+ const svc = {
+ mode: 'local',
+ info: async () => item(),
+ setSetting: async (_id: string, key: string, value: unknown) => {
+ if (key === 'owner' && String(value).replace(/\D/g, '').length < 7) throw new Error('Expected a phone number with country code, like +15551234567.');
+ values[key] = key === 'owner' ? `+${String(value).replace(/\D/g, '')}` : value;
+ calls.push(`set ${key}=${String(values[key])}`);
+ },
+ channelStatus: async () => ({ state: linked ? 'connected' : 'needs-pairing', at: Date.now() }),
+ pair: async (_id: string, opts: { method: string; phone?: string }) => { calls.push(`pair ${opts.method} ${opts.phone}`); return { state: 'pairing', pairCode: 'ABCD1234', at: Date.now() }; },
+ testChannel: async () => { calls.push('test'); return 'Sent a test message.'; },
+ unlink: async () => { calls.push('unlink'); linked = false; },
+ disable: async () => { calls.push('disable'); },
+ enable: async () => { calls.push('enable'); },
+ uninstall: async (_id: string, purge?: boolean) => { calls.push(`uninstall ${purge ? 'purge' : 'keep'}`); },
+ update: async () => [],
+ } as unknown as PluginService;
+ return { svc, calls, values, link: () => { linked = true; } };
+}
+
+async function say(d: PluginDialog, ...answers: string[]): Promise<string[]> {
+ const out: string[] = [];
+ for (const a of answers) {
+ const r = await d.answer(a);
+ if (r.message) out.push(r.message);
+ const p = await d.current();
+ if (p) out.push(renderPrompt(p, false));
+ }
+ return out;
+}
+
+describe('setup dialog', () => {
+ it('asks each setup setting in order, validates, then offers linking', async () => {
+ const { svc, calls, values } = fakeService();
+ const d = (await PluginDialog.setup(svc, 'whatsapp'))!;
+ const first = renderPrompt((await d.current())!, false);
+ expect(first).toMatch(/WhatsApp setup \(1\/4\)[\s\S]*Which number will you chat from\?[\s\S]*country code/);
+
+ const out = await say(d, 'abc', '+91 700 680 4336', '2', '1', '1', '+63 975 902 1037', 'ok');
+ expect(out[0]).toMatch(/phone number/); // "abc" rejected, same question again
+ expect(values.owner).toBe('+917006804336');
+ expect(out.join('\n')).toMatch(/Extended: memory, files, tools/);
+ expect(values.access).toBe('extended');
+ expect(values.answerCalls).toBe(true);
+ expect(calls).toContain('pair code 639759021037');
+ expect(out.join('\n')).toMatch(/Pairing code: \*ABCD1234\*/);
+ expect(out.join('\n')).toMatch(/is set up[\s\S]*\/plugins whatsapp/);
+ expect(await d.current()).toBeNull();
+ });
+
+ it('options can be picked by number, button command or their words; cancel stops', async () => {
+ const { svc, values } = fakeService();
+ const d = (await PluginDialog.setup(svc, 'whatsapp'))!;
+ await say(d, '+917006804336', '/plugins pick 2');
+ expect(values.access).toBe('extended');
+ await say(d, 'no');
+ expect(values.answerCalls).toBe(false);
+ const r = await d.answer('cancel');
+ expect(r).toEqual({ message: 'Closed.', finished: true });
+ });
+
+ it('a plugin with nothing to set up has no setup dialog', async () => {
+ const { svc } = fakeService({ settings: [], channel: undefined });
+ expect(await PluginDialog.setup(svc, 'whatsapp')).toBeNull();
+ });
+});
+
+describe('/plugins <id> menu', () => {
+ it('shows status and settings, and its actions work', async () => {
+ const { svc, calls, values, link } = fakeService();
+ link();
+ const d = (await PluginDialog.menu(svc, 'whatsapp', true))!;
+ const menu = renderPrompt((await d.current())!, false);
+ expect(menu).toMatch(/WhatsApp[\s\S]*Account: linked as \+639759021037[\s\S]*What can Mercury do in your chat\?: General/);
+ expect(menu).toMatch(/Change a setting[\s\S]*Send me a test message[\s\S]*Unlink the account[\s\S]*Turn off[\s\S]*Uninstall[\s\S]*Close/);
+
+ await say(d, 'Send me a test message');
+ expect(calls).toContain('test');
+ await say(d, '1', '2', '2'); // Change a setting → access → Extended
+ expect(values.access).toBe('extended');
+ await say(d, 'unlink', 'yes');
+ expect(calls).toContain('unlink');
+ const r = await d.answer('close');
+ expect(r.finished).toBe(true);
+ });
+
+ it('members see status only, with no actions', async () => {
+ const { svc } = fakeService();
+ const d = (await PluginDialog.menu(svc, 'whatsapp', false))!;
+ expect((await d.current())!.options).toBeUndefined();
+ });
+});
diff --git a/src/plugins/dialog.ts b/src/plugins/dialog.ts
new file mode 100644
index 00000000..1612de92
--- /dev/null
+++ b/src/plugins/dialog.ts
@@ -0,0 +1,346 @@
+/**
+ * Guided plugin dialogs: setup right after install, and the `/plugins <id>`
+ * menu. One engine for every plugin and every surface. The plugin's
+ * manifest says which settings to ask about (`setup: true`), in what words
+ * (`label`, `optionLabels`), and whether a channel needs linking; nobody has
+ * to remember per-plugin commands.
+ *
+ * A dialog is a stack of steps. Each step renders a prompt (text plus
+ * numbered options, or free text) and handles one answer. Chats render the
+ * options as buttons where they can (Telegram) and as a numbered list
+ * elsewhere (WhatsApp, terminal); a reply of "2", the option's words, or a
+ * button tap all work.
+ */
+import type { PluginService } from './service.js';
+import type { PluginListItem } from './types.js';
+
+export interface DialogOption {
+ label: string;
+ value: string;
+}
+
+export interface DialogPrompt {
+ text: string;
+ options?: DialogOption[];
+ /** Free-text answer expected (a number, a name); options may still be offered. */
+ freeText?: string;
+}
+
+interface Step {
+ prompt(): Promise<DialogPrompt>;
+ /** Handle an answer. Return a message to show before the next prompt, if any. */
+ answer(input: string, option: DialogOption | undefined): Promise<StepOutcome>;
+}
+
+type StepOutcome =
+ | { kind: 'next'; message?: string }
+ | { kind: 'retry'; message: string }
+ | { kind: 'push'; steps: Step[]; message?: string }
+ | { kind: 'done'; message?: string };
+
+type Setting = NonNullable<PluginListItem['settings']>[number];
+
+const CANCEL = new Set(['cancel', 'stop', 'exit', 'quit', 'close', 'done', '0']);
+
+export class PluginDialog {
+ private steps: Step[] = [];
+ private lastPrompt: DialogPrompt | null = null;
+ readonly startedAt = Date.now();
+
+ private constructor(readonly pluginId: string, readonly title: string, private readonly svc: PluginService, private readonly admin: boolean) {}
+
+ /** Setup: each `setup: true` setting in order, then linking for channel plugins. */
+ static async setup(svc: PluginService, id: string): Promise<PluginDialog | null> {
+ const info = await svc.info(id);
+ if (!info?.installedVersion) return null;
+ const d = new PluginDialog(id, `${info.name} setup`, svc, true);
+ const fields = (info.settings ?? []).filter((s) => s.setup);
+ fields.forEach((f, i) => d.steps.push(d.settingStep(f, { index: i + 1, total: fields.length + (info.channel ? 1 : 0), setup: true })));
+ if (info.channel) d.steps.push(d.linkStep(info, true));
+ d.steps.push(d.finishStep(info));
+ if (d.steps.length === 1 && !info.channel && !fields.length) return null;
+ return d;
+ }
+
+ /** The `/plugins <id>` menu. Members see status only. */
+ static async menu(svc: PluginService, id: string, admin: boolean): Promise<PluginDialog | null> {
+ const info = await svc.info(id);
+ if (!info) return null;
+ const d = new PluginDialog(id, info.name, svc, admin);
+ d.steps.push(d.menuStep());
+ return d;
+ }
+
+ // ── engine ───────────────────────────────────────────────────────────
+
+ /** The prompt to show now, or null when the dialog has finished. */
+ async current(): Promise<DialogPrompt | null> {
+ const step = this.steps[0];
+ if (!step) return null;
+ this.lastPrompt = await step.prompt();
+ return this.lastPrompt;
+ }
+
+ /** Feed one answer. Returns text to show (outcome message, then the next prompt is fetched by the caller). */
+ async answer(raw: string): Promise<{ message?: string; finished: boolean }> {
+ const input = raw.trim();
+ if (CANCEL.has(input.toLowerCase())) {
+ this.steps = [];
+ return { message: 'Closed.', finished: true };
+ }
+ const step = this.steps[0];
+ if (!step) return { finished: true };
+ const option = this.match(input);
+ let outcome: StepOutcome;
+ try {
+ outcome = await step.answer(input, option);
+ } catch (err) {
+ outcome = { kind: 'retry', message: `✗ ${(err as Error).message}` };
+ }
+ switch (outcome.kind) {
+ case 'retry':
+ return { message: outcome.message, finished: false };
+ case 'next':
+ this.steps.shift();
+ return { message: outcome.message, finished: this.steps.length === 0 };
+ case 'push':
+ this.steps.shift();
+ this.steps.unshift(...outcome.steps);
+ return { message: outcome.message, finished: this.steps.length === 0 };
+ case 'done':
+ this.steps = [];
+ return { message: outcome.message, finished: true };
+ }
+ }
+
+ private match(input: string): DialogOption | undefined {
+ const opts = this.lastPrompt?.options ?? [];
+ const t = input.toLowerCase().replace(/^\/plugins\s+pick\s+/, '');
+ const n = Number(t);
+ if (Number.isInteger(n) && n >= 1 && n <= opts.length) return opts[n - 1];
+ return opts.find((o) => o.value.toLowerCase() === t || o.label.toLowerCase() === t || o.label.toLowerCase().split(/[:·(]/)[0].trim() === t);
+ }
+
+ // ── steps ────────────────────────────────────────────────────────────
+
+ private settingStep(s: Setting, ctx: { index?: number; total?: number; setup?: boolean } = {}): Step {
+ const title = s.label ?? s.key;
+ const counter = ctx.index ? ` (${ctx.index}/${ctx.total})` : '';
+ const current = s.value === undefined || s.value === '' ? 'not set' : String(s.optionLabels?.[String(s.value)] ?? s.value);
+ const keep = ctx.setup && !s.required && s.value !== undefined && s.value !== '' ? [{ label: `Keep: ${current}`, value: '__keep' }] : [];
+ return {
+ prompt: async () => {
+ const head = `${ctx.setup ? `⚙️ ${this.title}${counter}\n` : ''}*${title}*${s.description ? `\n${s.description}` : ''}`;
+ if (s.type === 'enum') {
+ return { text: `${head}\nNow: ${current}`, options: (s.options ?? []).map((o) => ({ label: s.optionLabels?.[o] ?? o, value: o })) };
+ }
+ if (s.type === 'boolean') {
+ return { text: `${head}\nNow: ${s.value === true ? 'yes' : 'no'}`, options: [{ label: 'Yes', value: 'true' }, { label: 'No', value: 'false' }] };
+ }
+ const hint = s.format === 'phone' ? 'Reply with the number, including the country code (e.g. +15551234567).' : `Reply with the new value${s.type === 'number' ? ' (a number)' : ''}.`;
+ return { text: `${head}\nNow: ${current}`, freeText: hint, options: keep.length ? keep : (ctx.setup && !s.required ? [{ label: 'Skip', value: '__keep' }] : undefined) };
+ },
+ answer: async (input, option) => {
+ if (option?.value === '__keep') return { kind: 'next' };
+ let value: string;
+ if (s.type === 'enum' || s.type === 'boolean') {
+ if (!option) return { kind: 'retry', message: 'Reply with one of the numbers.' };
+ value = option.value;
+ } else {
+ if (!input) return { kind: 'retry', message: 'Reply with a value.' };
+ value = input;
+ }
+ await this.svc.setSetting(this.pluginId, s.key, s.type === 'boolean' ? value === 'true' : s.type === 'number' ? Number(value) : value);
+ const shown = s.type === 'enum' ? (s.optionLabels?.[value] ?? value).split(':')[0] : s.type === 'boolean' ? (value === 'true' ? 'yes' : 'no') : value;
+ return { kind: 'next', message: `✅ ${title}: ${shown}` };
+ },
+ };
+ }
+
+ private linkStep(info: PluginListItem, setup: boolean): Step {
+ return {
+ prompt: async () => {
+ const st = await this.svc.channelStatus(this.pluginId).catch(() => null);
+ if (st?.state === 'connected') {
+ return { text: `*Link account*\nAlready linked${st.account ? ` as +${st.account}` : ''}.`, options: [{ label: 'Continue', value: 'skip' }] };
+ }
+ return {
+ text: `${setup ? `⚙️ ${this.title}\n` : ''}*Link the ${info.name} account Mercury runs on*\nUse a spare number, not your main one: the protocol is unofficial.`,
+ options: [
+ { label: 'Pairing code: type it on the spare phone', value: 'code' },
+ { label: 'QR code: scan it (dashboard or `mercury plugins pair`)', value: 'qr' },
+ { label: 'Later', value: 'skip' },
+ ],
+ };
+ },
+ answer: async (_input, option) => {
+ if (!option) return { kind: 'retry', message: 'Reply 1, 2 or 3.' };
+ if (option.value === 'skip') return { kind: 'next' };
+ if (option.value === 'qr') {
+ return { kind: 'next', message: `Open the dashboard → Plugins → ${info.name} → Link with QR code, or run \`mercury plugins pair ${this.pluginId}\` in a terminal.` };
+ }
+ return { kind: 'push', steps: [this.pairCodeStep(info)] };
+ },
+ };
+ }
+
+ private pairCodeStep(info: PluginListItem): Step {
+ return {
+ prompt: async () => ({ text: `*Which number will Mercury run on?*`, freeText: 'Reply with the spare number, including the country code.' }),
+ answer: async (input) => {
+ const digits = input.replace(/[^\d]/g, '');
+ if (digits.length < 7) return { kind: 'retry', message: 'That doesn\'t look like a phone number. Include the country code, e.g. +639171234567.' };
+ const st = await this.svc.pair(this.pluginId, { method: 'code', phone: digits });
+ if (st.state === 'connected') return { kind: 'next', message: `Already linked${st.account ? ` as +${st.account}` : ''}.` };
+ if (!st.pairCode) return { kind: 'retry', message: `Couldn't get a code${st.detail ? `: ${st.detail}` : ''}. Try again, or reply "later".` };
+ return {
+ kind: 'next',
+ message: `🔗 Pairing code: *${st.pairCode}*\nOn the spare phone: ${info.name} → Settings → Linked devices → Link a device → Link with phone number instead, then type the code. It's valid for about 3 minutes; I'll confirm when it's linked.`,
+ };
+ },
+ };
+ }
+
+ private finishStep(info: PluginListItem): Step {
+ return {
+ prompt: async () => ({
+ text: `✅ ${info.name} is set up.\nOpen its menu anytime with /plugins ${this.pluginId} to change settings, link or unlink, or turn it off.`,
+ options: [{ label: 'Done', value: 'done' }],
+ }),
+ answer: async () => ({ kind: 'done' }),
+ };
+ }
+
+ private menuStep(): Step {
+ return {
+ prompt: async () => {
+ const i = (await this.svc.info(this.pluginId))!;
+ const lines = [`🧩 *${i.name}* ${i.installedVersion ?? i.latestVersion ?? ''}`, i.description];
+ const status = i.installedVersion ? (i.enabled ? (i.status === 'enabled' ? 'on' : i.status) : 'off') : 'not installed';
+ lines.push('', `Status: ${status}`);
+ if (i.channel) lines.push(`Account: ${i.channel.state === 'connected' ? `linked${i.channel.account ? ` as +${i.channel.account}` : ''}` : (i.channel.state ?? 'not linked')}`);
+ for (const s of (i.settings ?? []).filter((x) => x.setup || x.label)) {
+ const v = s.value === undefined || s.value === '' ? 'not set' : s.type === 'boolean' ? (s.value ? 'yes' : 'no') : String(s.optionLabels?.[String(s.value)]?.split(':')[0] ?? s.value);
+ lines.push(`${s.label ?? s.key}: ${v}`);
+ }
+ for (const m of i.missing ?? []) lines.push(`⚠️ ${m.unlocks} is off: needs ${m.needs}.`);
+ const options: DialogOption[] = [];
+ if (!this.admin) return { text: lines.join('\n') };
+ if (!i.installedVersion) {
+ options.push({ label: 'Install', value: 'install' });
+ } else {
+ if (i.settings?.length) options.push({ label: 'Change a setting', value: 'settings' });
+ if (i.channel && i.enabled) {
+ if (i.channel.state === 'connected') {
+ options.push({ label: 'Send me a test message', value: 'test' });
+ options.push({ label: 'Unlink the account', value: 'unlink' });
+ } else {
+ options.push({ label: 'Link the account', value: 'link' });
+ }
+ }
+ if (i.settings?.some((s) => s.setup)) options.push({ label: 'Run setup again', value: 'setup' });
+ if (i.status === 'update-available') options.push({ label: `Update to ${i.latestVersion}`, value: 'update' });
+ options.push(i.enabled ? { label: 'Turn off', value: 'disable' } : { label: 'Turn on', value: 'enable' });
+ options.push({ label: 'Uninstall', value: 'uninstall' });
+ }
+ options.push({ label: 'Close', value: 'close' });
+ return { text: lines.join('\n'), options };
+ },
+ answer: async (_input, option) => {
+ if (!this.admin) return { kind: 'done' };
+ if (!option) return { kind: 'retry', message: 'Reply with one of the numbers, or "cancel".' };
+ const i = (await this.svc.info(this.pluginId))!;
+ switch (option.value) {
+ case 'close':
+ return { kind: 'done', message: 'Closed.' };
+ case 'settings':
+ return { kind: 'push', steps: [this.pickSettingStep(i), this.menuStep()] };
+ case 'link':
+ return { kind: 'push', steps: [this.linkStep(i, false), this.menuStep()] };
+ case 'setup': {
+ const d = await PluginDialog.setup(this.svc, this.pluginId);
+ return d ? { kind: 'push', steps: d.steps } : { kind: 'retry', message: 'Nothing to set up.' };
+ }
+ case 'test':
+ return { kind: 'push', steps: [this.menuStep()], message: `✅ ${await this.svc.testChannel(this.pluginId)}` };
+ case 'unlink':
+ return { kind: 'push', steps: [this.confirmStep(`Log Mercury out of this ${i.name} account? You can link it again later.`, async () => { await this.svc.unlink(this.pluginId); return '🔌 Unlinked.'; }), this.menuStep()] };
+ case 'update': {
+ const changed = await this.svc.update(this.pluginId);
+ return { kind: 'push', steps: [this.menuStep()], message: changed.length ? `⬆️ Updated to ${changed[0].to}.` : 'Already up to date.' };
+ }
+ case 'enable':
+ await this.svc.enable(this.pluginId);
+ return { kind: 'push', steps: [this.menuStep()], message: '▶️ Turned on.' };
+ case 'disable':
+ await this.svc.disable(this.pluginId);
+ return { kind: 'push', steps: [this.menuStep()], message: '⏸ Turned off. Its data and settings are kept.' };
+ case 'uninstall':
+ return { kind: 'push', steps: [this.uninstallStep(i)] };
+ case 'install': {
+ const r = await this.svc.install(this.pluginId);
+ const setup = await PluginDialog.setup(this.svc, r.id);
+ return setup ? { kind: 'push', steps: setup.steps, message: `✅ Installed ${r.name} ${r.version}.` } : { kind: 'push', steps: [this.menuStep()], message: `✅ Installed ${r.name} ${r.version}.` };
+ }
+ default:
+ return { kind: 'retry', message: 'Reply with one of the numbers.' };
+ }
+ },
+ };
+ }
+
+ private pickSettingStep(i: PluginListItem): Step {
+ const settings = i.settings ?? [];
+ return {
+ prompt: async () => ({
+ text: '*Which setting?*',
+ options: [...settings.map((s) => ({ label: s.label ?? s.key, value: s.key })), { label: 'Back', value: '__back' }],
+ }),
+ answer: async (_input, option) => {
+ if (!option) return { kind: 'retry', message: 'Reply with one of the numbers.' };
+ if (option.value === '__back') return { kind: 'next' };
+ const fresh = (await this.svc.info(this.pluginId))?.settings?.find((s) => s.key === option.value);
+ return fresh ? { kind: 'push', steps: [this.settingStep(fresh)] } : { kind: 'retry', message: 'That setting is gone.' };
+ },
+ };
+ }
+
+ private confirmStep(question: string, run: () => Promise<string>): Step {
+ return {
+ prompt: async () => ({ text: question, options: [{ label: 'Yes', value: 'yes' }, { label: 'No', value: 'no' }] }),
+ answer: async (_input, option) => {
+ if (!option) return { kind: 'retry', message: 'Reply 1 (yes) or 2 (no).' };
+ return option.value === 'yes' ? { kind: 'next', message: await run() } : { kind: 'next' };
+ },
+ };
+ }
+
+ private uninstallStep(i: PluginListItem): Step {
+ return {
+ prompt: async () => ({
+ text: `Uninstall ${i.name}?`,
+ options: [
+ { label: 'Uninstall, keep its data and settings', value: 'keep' },
+ { label: 'Uninstall and delete its data', value: 'purge' },
+ { label: 'Cancel', value: 'cancel' },
+ ],
+ }),
+ answer: async (_input, option) => {
+ if (!option) return { kind: 'retry', message: 'Reply 1, 2 or 3.' };
+ if (option.value === 'cancel') return { kind: 'push', steps: [this.menuStep()] };
+ await this.svc.uninstall(this.pluginId, option.value === 'purge');
+ return { kind: 'done', message: `🗑 Uninstalled ${i.name}${option.value === 'purge' ? ' and deleted its data' : ''}.` };
+ },
+ };
+ }
+}
+
+/** Plain-text rendering (WhatsApp, terminal, any chat without buttons). */
+export function renderPrompt(p: DialogPrompt, buttons: boolean): string {
+ const lines = [p.text];
+ if (p.freeText) lines.push('', p.freeText);
+ if (p.options?.length && !buttons) {
+ lines.push('', ...p.options.map((o, i) => `*${i + 1}* · ${o.label}`), '', p.freeText ? 'Or reply with a number. "cancel" to stop.' : 'Reply with a number, or "cancel".');
+ }
+ return lines.join('\n');
+}
diff --git a/src/plugins/manager.ts b/src/plugins/manager.ts
index 4985046b..4732be62 100644
--- a/src/plugins/manager.ts
+++ b/src/plugins/manager.ts
@@ -502,7 +502,7 @@ export class PluginManager {
const manifest = installedManifest(id, entry.version);
const field = manifest?.settings?.fields?.[key];
if (!manifest || !field) throw new Error(`"${id}" has no setting called "${key}".`);
- const coerced = coerceSetting(field.type, field.options, value);
+ const coerced = coerceSetting(field.type, field.options, value, field.format);
const values = { ...resolvedSettings(manifest), [key]: coerced };
writeSettings(id, values, manifest.settings?.version ?? 1);
// Settings are read at start: restart a running plugin so it sees them.
@@ -590,7 +590,10 @@ export class PluginManager {
const fields = manifest?.settings?.fields ?? {};
if (manifest && Object.keys(fields).length) {
const values = resolvedSettings(manifest);
- item.settings = Object.entries(fields).map(([key, f]) => ({ key, type: f.type, description: f.description, options: f.options, value: values[key] }));
+ item.settings = Object.entries(fields).map(([key, f]) => ({
+ key, type: f.type, description: f.description, options: f.options, value: values[key],
+ label: f.label, setup: f.setup, required: f.required, optionLabels: f.optionLabels, format: f.format,
+ }));
}
return item;
}
@@ -660,7 +663,13 @@ function isNewer(candidate: string, current: string): boolean {
return semver.valid(candidate) !== null && semver.valid(current) !== null && semver.gt(candidate, current);
}
-function coerceSetting(type: string, options: string[] | undefined, value: unknown): unknown {
+function coerceSetting(type: string, options: string[] | undefined, value: unknown, format: 'text' | 'phone' = 'text'): unknown {
+ if (type === 'string' && format === 'phone') {
+ if (value === '' || value === null || value === undefined) return '';
+ const digits = String(value).replace(/[^\d]/g, '');
+ if (digits.length < 7 || digits.length > 15) throw new Error('Expected a phone number with country code, like +15551234567.');
+ return `+${digits}`;
+ }
if (type === 'boolean') {
if (typeof value === 'boolean') return value;
if (value === 'true' || value === 'on' || value === 'yes') return true;
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index c78a6ce9..25129929 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -89,6 +89,16 @@ const settingField = z.object({
description: z.string().max(300).default(''),
default: z.union([z.string(), z.number(), z.boolean()]).optional(),
options: z.array(z.string()).max(50).optional(),
+ /** Short question or title shown in setup and in /plugins <id>, e.g. "Your WhatsApp number". */
+ label: z.string().max(80).optional(),
+ /** Ask this during setup (right after install, and `/plugins setup <id>`), in declaration order. */
+ setup: z.boolean().default(false),
+ /** Setup can't finish without a value. */
+ required: z.boolean().default(false),
+ /** Plain-language labels for enum options, e.g. { "general": "General: chat only" }. */
+ optionLabels: z.record(z.string(), z.string().max(160)).optional(),
+ /** Input format for string settings, validated and normalised on save. */
+ format: z.enum(['text', 'phone']).default('text'),
}).strict();
const settingKey = z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,40}$/);
@@ -280,7 +290,18 @@ export interface PluginListItem {
lastError?: string;
incompatibleReason?: string;
/** Only in `info`: the settings the plugin declares, with current values. */
- settings?: Array<{ key: string; type: 'string' | 'number' | 'boolean' | 'enum'; description: string; options?: string[]; value: unknown }>;
+ settings?: Array<{
+ key: string;
+ type: 'string' | 'number' | 'boolean' | 'enum';
+ description: string;
+ options?: string[];
+ value: unknown;
+ label?: string;
+ setup?: boolean;
+ required?: boolean;
+ optionLabels?: Record<string, string>;
+ format?: 'text' | 'phone';
+ }>;
}
// ── catalog ──────────────────────────────────────────────────────────────
diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts
index d53a567f..3738e362 100644
--- a/ui/src/lib/api.ts
+++ b/ui/src/lib/api.ts
@@ -275,6 +275,11 @@ export interface PluginSetting {
description: string;
options?: string[];
value: unknown;
+ label?: string;
+ setup?: boolean;
+ required?: boolean;
+ optionLabels?: Record<string, string>;
+ format?: "text" | "phone";
}
export interface PluginItem {
diff --git a/ui/src/pages/Plugins.tsx b/ui/src/pages/Plugins.tsx
index ae004413..65310f09 100644
--- a/ui/src/pages/Plugins.tsx
+++ b/ui/src/pages/Plugins.tsx
@@ -437,7 +437,10 @@ function SettingField({ s, disabled, onSave }: { s: PluginSetting; disabled: boo
return (
<div className="space-y-1">
<div className="flex items-center justify-between gap-3">
- <label className="font-mono text-xs text-foreground" htmlFor={`setting-${s.key}`}>{s.key}</label>
+ <label className="text-sm font-medium text-foreground" htmlFor={`setting-${s.key}`}>
+ {s.label ?? s.key}
+ {s.required && (s.value === undefined || s.value === "") && <span className="ml-2 text-xs text-amber-500">needed</span>}
+ </label>
{s.type === "boolean" && (
<Switch id={`setting-${s.key}`} checked={s.value === true} disabled={disabled} onCheckedChange={(v) => onSave(v)} />
)}
@@ -451,11 +454,11 @@ function SettingField({ s, disabled, onSave }: { s: PluginSetting; disabled: boo
disabled={disabled}
onChange={(e) => onSave(e.target.value)}
>
- {(s.options ?? []).map((o) => <option key={o} value={o}>{o}</option>)}
+ {(s.options ?? []).map((o) => <option key={o} value={o}>{s.optionLabels?.[o] ?? o}</option>)}
</select>
) : s.type !== "boolean" ? (
<form className="flex gap-2" onSubmit={(e) => { e.preventDefault(); onSave(s.type === "number" ? Number(draft) : draft); }}>
- <Input id={`setting-${s.key}`} value={draft} onChange={(e) => setDraft(e.target.value)} type={s.type === "number" ? "number" : "text"} disabled={disabled} className="h-8 text-sm" />
+ <Input id={`setting-${s.key}`} value={draft} onChange={(e) => setDraft(e.target.value)} type={s.type === "number" ? "number" : s.format === "phone" ? "tel" : "text"} placeholder={s.format === "phone" ? "+15551234567" : undefined} disabled={disabled} className="h-8 text-sm" />
<Button size="sm" variant="outline" type="submit" disabled={disabled || draft === String(s.value ?? "")}>Save</Button>
</form>
) : null}
@@ -499,7 +502,7 @@ function PluginDetails({ p, busy, safeMode, onAct, onInstall, onClose }: {
{p.settings && p.settings.length > 0 && (
<div className="space-y-3 rounded-lg border border-border p-3">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Settings</p>
- {p.settings.map((setting) => (
+ {[...p.settings].sort((a, b) => Number(!!b.setup) - Number(!!a.setup)).map((setting) => (
<SettingField
key={setting.key}
s={setting}
diff --git a/website/docs/cli-commands/plugins.mdx b/website/docs/cli-commands/plugins.mdx
index 6c9cb5a2..d0b97a91 100644
--- a/website/docs/cli-commands/plugins.mdx
+++ b/website/docs/cli-commands/plugins.mdx
@@ -30,6 +30,8 @@ away without a restart.
| Chat | Shell | What it does |
|------|-------|--------------|
| `/plugins` | `mercury plugins` | Installed and available plugins, with status |
+| `/plugins ID` | `mercury plugins open ID` | That plugin's menu: its settings, linking, test, turn off, uninstall. Reply with a number (or tap a button on Telegram) |
+| `/plugins setup ID` | `mercury plugins setup ID` | Walk through the plugin's setup again |
| `/plugins search weather` | `mercury plugins search weather` | Find plugins in the catalog |
| `/plugins info ID` | `mercury plugins info ID` | Tools, network access, secrets it reads, settings |
| `/plugins install ID` | `mercury plugins install ID` | Install. Shows what the plugin needs first and asks you to confirm |
@@ -40,6 +42,11 @@ away without a restart.
| `/plugins uninstall ID` | `mercury plugins uninstall ID` | Remove it. Add `--purge` to delete its data too |
| `/plugins set ID KEY VALUE` | `mercury plugins set ID KEY VALUE` | Change a plugin setting |
+After install, Mercury walks you through the plugin's setup, one question
+at a time, in the same chat. For WhatsApp that's your number, what Mercury
+may do in your chat, and linking the spare number. You never need to
+remember a plugin's settings: open `/plugins ID` and pick from the list.
+
`install` accepts a catalog id, a folder, a `.tgz` file, an `https://` URL,
or `github:owner/repo` (latest release). Only catalog plugins are verified
by Mercury; install anything else only from people you trust.
diff --git a/website/docs/reference/plugins.mdx b/website/docs/reference/plugins.mdx
index eb68af80..8a83737c 100644
--- a/website/docs/reference/plugins.mdx
+++ b/website/docs/reference/plugins.mdx
@@ -53,6 +53,15 @@ No npm package is needed: `init` writes the API types next to your code as
}
```
+- **Settings** can carry setup metadata. Settings with `"setup": true` are
+ asked in order right after install, in chat or in the terminal, and appear
+ in the plugin's `/plugins ID` menu. The metadata fields are:
+ - `label`: a plain question, such as "Which number will you chat from?";
+ - `required`;
+ - `optionLabels` for enum choices;
+ - `"format": "phone"`, which is validated and normalised to `+digits`.
+
+ Channel plugins also get a linking step at the end of setup.
- **Tools** are shown to the model as `ID__name` (for example
`weather__forecast`). `readOnly` tools skip approval and are available in
plan mode; every other tool asks the owner first.