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): optional plugins with /plugins install, enable, disable, update, rollback, uninstall (#203)

Salman Qureshie857840c5a80
diff --git a/.gitignore b/.gitignore
index c009508b..db7673e5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,6 @@ soul/
memory/
# Claude Code worktrees / local state
.claude/
+
+# plugin-system tests (src/plugins/test-fixtures.ts)
+.vitest-tmp/
diff --git a/DECISIONS.md b/DECISIONS.md
index e70c9778..4103ab18 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -216,3 +216,28 @@
- **Decision**: One process is the runtime. `bootDaemonThenAttach()` replaces spawn-then-boot at launch and in recovery: spawn the daemon, attach to it (`runAttach` now waits for the attach token and tolerates a token rotated during boot); only when no daemon can run here (Termux, unsupported platform) does the terminal become the runtime. A foreground runtime that finds a live daemon (`daemonOwnsRuntime`: `mercury code`, an attach that could not connect) wires the CLI channel only (`ChannelRegistry({ cliOnly })`), creates no `BotManager`, and does not bind the web port — it is a terminal for the main agent. The event loop is measured (`monitorEventLoopDelay`): `/api/health` reports `loopLag`, and stalls ≥250 ms are logged.
- **Also**: the login service must launch *this* install. `serviceDrift()` compares the plist/unit's program with the running binary; `autoDaemonize` re-points a drifted service (macOS unloads the old label first — a loaded label ignores a rewritten plist and KeepAlive keeps the old daemon alive; Linux restarts the unit), `mercury doctor` reports it, and the attach "foreign port" message names it. On the reporting machine the LaunchAgent still launched the npm-global 1.3.0; that daemon owned :6174 for a day while every `mercury` launch healed around it.
- **Consequence**: Bots and channels run exactly once, in the daemon, on their own thread; the TUI process renders keystrokes and nothing else. The attach TUI is what most sessions see (the daemon auto-starts on login), so parity gaps in it — TUI-only bot threads (`/bots open`), the `/telegram` menu — are now visible and worth closing. Lag has a number: if `loopLag.maxMs` is high in the daemon, something in a bot turn is synchronous and should move off the thread.
+
+## ADR-025: Optional features ship as plugins, isolated and hot-pluggable
+
+- **Context**: Features only some people want (WhatsApp calls, #202; integrations with heavy native pieces) were heading into the single binary, making it bigger and riskier for everyone (#203). A plugin system had to keep Mercury stable when a plugin is bad, and had to work from the compiled binary. Spikes showed that a `bun build --compile` binary can `import()` JS from disk but cannot resolve packages for it. They also showed that `BUN_BE_BUN=1 <binary> script.js` runs scripts without a system Node.
+- **Decision**: Plugins live in `~/.mercury/plugins`. Each one is either an *in-process* single-file ES module, given a scoped `PluginContext`, or an *out-of-process* MCP server over stdio, supervised with restart backoff.
+ - **Contract**: Frozen manifest v1 and Plugin API 1.0. Minor versions only add; a major version is supported for at least two Mercury minors.
+ - **Isolation and hot plug**:
+ - A plugin gets only what it declares: tools, commands, network hosts (through the SSRF guard) and secrets.
+ - Everything made through the context is torn down on disable, so plugins are hot-plugged with no restart.
+ - Tools are namespaced `id__tool`. Non-read-only tools need approval.
+ - Bots see plugin tools only through an explicit allow entry. Members get none.
+ - Built-in command names are reserved.
+ - **Self-protection**:
+ - Atomic installs with checksum, tree and manifest checks; the previous version is kept for rollback.
+ - A cross-process lock.
+ - A circuit breaker after 5 consecutive failures.
+ - A crash-loop limit.
+ - A boot guard that disables the last-changed plugin after two failed starts.
+ - Uncaught errors whose stack points into a plugin disable that plugin instead of exiting.
+ - `--safe-mode` / `MERCURY_PLUGINS=off`.
+ - **Settings**: migrations are declarative (`rename`/`remove`/`mapValues`), so no plugin code runs to migrate, and a backup is kept for rollback.
+ - **Dependencies**: No plugin-to-plugin dependencies in v1.
+ - **Ownership**: Following ADR-024, only the runtime owner runs plugins. Every other process (`mercury plugins …`, attached terminals) forwards changes over the loopback API. Web mutations are loopback-only.
+ - **Authoring**: `init`, `validate` (a conformance kit that starts, inspects, stops and restarts the plugin) and `pack` ship in the binary, so authors need no npm package.
+- **Consequence**: The core binary stays the same size; optional features become catalog entries (`mercuryagent.sh/plugins/catalog.json`, checksum-pinned). In-process plugins still share the daemon's memory and event loop: the guards contain errors and timeouts, not a busy loop or a memory leak. Anything heavy or native should be out-of-process, and the docs say so.
diff --git a/package-lock.json b/package-lock.json
index 14a2cd85..d18034d7 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -31,6 +31,7 @@
"pino": "^10.3.1",
"qrcode-terminal": "^0.12.0",
"react": "^19.3.0",
+ "semver": "7.8.0",
"sql.js": "^1.14.1",
"string-width": "^7.2.0",
"undici": "^6.24.1",
@@ -48,6 +49,7 @@
"@types/node-cron": "^3.0.11",
"@types/qrcode-terminal": "^0.12.2",
"@types/react": "^19.3.0",
+ "@types/semver": "7.7.1",
"ink": "8.0.0",
"react-devtools-core": "^7.0.1",
"tsup": "^8.4.0",
@@ -1441,6 +1443,13 @@
"integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
"license": "MIT"
},
+ "node_modules/@types/semver": {
+ "version": "7.7.1",
+ "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.7.1.tgz",
+ "integrity": "sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/send": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",
@@ -4215,6 +4224,7 @@
"version": "7.8.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz",
"integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==",
+ "license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
@@ -6605,6 +6615,12 @@
"resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
"integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="
},
+ "@types/semver": {
+ "version": "7.7.1",
+ "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.7.1.tgz",
+ "integrity": "sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==",
+ "dev": true
+ },
"@types/send": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",
diff --git a/package.json b/package.json
index 24b19412..8433e63f 100644
--- a/package.json
+++ b/package.json
@@ -87,6 +87,7 @@
"pino": "^10.3.1",
"qrcode-terminal": "^0.12.0",
"react": "^19.3.0",
+ "semver": "7.8.0",
"sql.js": "^1.14.1",
"string-width": "^7.2.0",
"undici": "^6.24.1",
@@ -104,6 +105,7 @@
"@types/node-cron": "^3.0.11",
"@types/qrcode-terminal": "^0.12.2",
"@types/react": "^19.3.0",
+ "@types/semver": "7.7.1",
"ink": "8.0.0",
"react-devtools-core": "^7.0.1",
"tsup": "^8.4.0",
diff --git a/scripts/gen-plugin-sdk.mjs b/scripts/gen-plugin-sdk.mjs
new file mode 100644
index 00000000..5fa18fbd
--- /dev/null
+++ b/scripts/gen-plugin-sdk.mjs
@@ -0,0 +1,11 @@
+// Regenerates src/plugins/sdk-dts.ts from src/plugins/sdk.ts so that
+// `mercury plugins init` (which runs inside a compiled binary with no
+// source files around) can write the Plugin API types into new plugins.
+import { readFileSync, writeFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const root = fileURLToPath(new URL('..', import.meta.url));
+const sdk = readFileSync(`${root}src/plugins/sdk.ts`, 'utf8');
+const out = `// Generated by scripts/gen-plugin-sdk.mjs from src/plugins/sdk.ts. Do not edit.\nexport const PLUGIN_SDK_DTS = ${JSON.stringify(sdk)};\n`;
+writeFileSync(`${root}src/plugins/sdk-dts.ts`, out);
+console.log('wrote src/plugins/sdk-dts.ts');
diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.ts
index 02c8841b..6043abfe 100644
--- a/src/bots/registry-factory.ts
+++ b/src/bots/registry-factory.ts
@@ -8,6 +8,7 @@ import type { MercuryConfig } from '../utils/config.js';
import { logger } from '../utils/logger.js';
import type { BotManifest, BotPermissionsFile, BotPathScope } from './types.js';
import { BOT_DANGEROUS_TOOLS, BOT_SANDBOX_DIRNAME, BOT_SHARED_SANDBOX_DIRNAME } from './store.js';
+import { isPluginToolName, pluginToolAllowed } from '../plugins/tool-bridge.js';
/**
* Tools a bot must never see, regardless of manifest. These are the tools
@@ -152,6 +153,14 @@ export function filterBotTools(all: Record<string, any>, manifest: BotManifest,
for (const [name, tool] of Object.entries(all)) {
if (ALWAYS_STRIPPED.has(name)) continue;
if (deny.has(name)) continue;
+ // Plugin tools are opt-in for bots (fail-closed): only an explicit allow
+ // entry ("<plugin>__<tool>" or "<plugin>__*") lets a bot see one. A
+ // deny-only gate must never expose a tool installed after the bot was set up.
+ if (isPluginToolName(name)) {
+ if (!pluginToolAllowed(name, allow)) continue;
+ out[name] = tool;
+ continue;
+ }
if (allow.length > 0 && !allow.includes(name)) continue;
out[name] = tool;
}
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index 4af51c51..a364ff1e 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -352,6 +352,8 @@ export class PermissionManager {
private rootCache: PermissionContext | null = null;
private binaryResolver: BinaryResolver = pinnedBinary;
private approvedCommandsByContext = new Map<string, Set<string>>();
+ /** "Always allow" choices for plugin tools, per channel (see approvePluginTool). */
+ private approvedPluginToolsByContext = new Map<string, Set<string>>();
private approvedWritesByContext = new Map<string, Set<string>>();
/** Hard-linked files the user answered "always" for, per interaction context. */
private approvedHardlinkReadsByContext = new Map<string, Set<string>>();
@@ -516,6 +518,34 @@ export class PermissionManager {
return result === 'yes' || result === 'always';
}
+ /**
+ * Approval for a plugin tool call (src/plugins). Same rules as the shell
+ * approval lane:
+ * - fail-closed (bots): the tool already passed the bot's explicit
+ * permissions.yaml allow list (filterBotTools), so it runs; there is no
+ * one to ask and no prompt mid-run.
+ * - internal/scheduled turns: only an allow-all context approves.
+ * - session Allow All approves, except web requests (never inherit local).
+ * - "always" is remembered per channel for this plugin tool.
+ * - otherwise the user sees the plugin, tool and arguments.
+ */
+ async approvePluginTool(toolKey: string, prompt: string): Promise<boolean> {
+ const ctx = this.ctx();
+ if (this.failClosed) return true;
+ if (ctx.channelType === 'internal') return ctx.autoApprove;
+ if (this.isGlobalAutoApproveActive()) return true;
+ if (this.approvedPluginToolsByContext.get(ctx.channelId)?.has(toolKey)) return true;
+ if (!this.askHandler) return false;
+ const result = await this.askHandler(prompt);
+ if (result === 'always') {
+ const approved = this.approvedPluginToolsByContext.get(ctx.channelId) ?? new Set<string>();
+ approved.add(toolKey);
+ this.approvedPluginToolsByContext.set(ctx.channelId, approved);
+ return true;
+ }
+ return result === 'yes';
+ }
+
/** Session-level Allow All (user choice). Inside a sub-agent it only changes that sub-agent. */
setAutoApproveAll(value: boolean): void {
this.updateContext(() => ({ autoApprove: value, autoApproveOrigin: value ? 'session' : null }));
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index fb53b49c..38a23b74 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -58,6 +58,7 @@ import type { TokenBudget } from '../utils/tokens.js';
import type { SubAgentSupervisor } from '../core/supervisor.js';
import type { SpotifyClient } from '../spotify/client.js';
import { createDelegateTaskTool, createListAgentsTool, createStopAgentTool } from './subagents/index.js';
+import { getPluginTools } from '../plugins/tool-bridge.js';
import { createDispatchBotTool } from '../bots/tools/dispatch-bot.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
import { logger } from '../utils/logger.js';
@@ -280,15 +281,33 @@ export class CapabilityRegistry {
}
getTools(): Record<string, Tool> {
- if (this.permissions.getCurrentSenderRole() !== 'member') return this.tools;
// Members on a channel that distinguishes roles (e.g. Telegram) must not be
// able to install skills: `install_skill` is the escalation path from chat
// access to arbitrary local execution and is documented as admin-only.
- const filtered: Record<string, Tool> = {};
- for (const [name, tool] of Object.entries(this.tools)) {
- if (name !== 'install_skill') filtered[name] = tool;
+ // Plugin tools are owner-installed code, so members don't get them either.
+ if (this.permissions.getCurrentSenderRole() === 'member') {
+ const filtered: Record<string, Tool> = {};
+ for (const [name, tool] of Object.entries(this.tools)) {
+ if (name !== 'install_skill') filtered[name] = tool;
+ }
+ return filtered;
+ }
+ return this.withPluginTools(this.tools, false);
+ }
+
+ /**
+ * Built-in tools plus the live plugin tools (src/plugins). Read on every
+ * call, so enabling or disabling a plugin takes effect on the next turn.
+ * A built-in tool always wins a name clash.
+ */
+ private withPluginTools(base: Record<string, Tool>, readOnlyOnly: boolean): Record<string, Tool> {
+ const plugin = getPluginTools(this.permissions, { readOnlyOnly });
+ if (Object.keys(plugin).length === 0) return base;
+ const merged: Record<string, Tool> = { ...base };
+ for (const [name, tool] of Object.entries(plugin)) {
+ if (!(name in merged)) merged[name] = tool;
}
- return filtered;
+ return merged;
}
/** Return tools filtered for plan mode — read-only tools only */
@@ -304,7 +323,9 @@ export class CapabilityRegistry {
for (const [name, tool] of Object.entries(this.tools)) {
if (!blocked.has(name)) filtered[name] = tool;
}
- return filtered;
+ // Plan mode: only plugin tools their manifest declares read-only.
+ if (this.permissions.getCurrentSenderRole() === 'member') return filtered;
+ return this.withPluginTools(filtered, true);
}
getToolNames(): string[] {
diff --git a/src/channels/telegram.ts b/src/channels/telegram.ts
index b1e46c30..9c0f095d 100644
--- a/src/channels/telegram.ts
+++ b/src/channels/telegram.ts
@@ -304,6 +304,7 @@ export class TelegramChannel extends BaseChannel {
{ command: 'bg', description: 'Background tasks (list / cancel / run)' },
{ command: 'spotify', description: 'Spotify playback controls' },
{ command: 'skills', description: 'Browse and install skills from the registry' },
+ { command: 'plugins', description: 'Install, enable, disable and remove plugins' },
{ command: 'unpair', description: 'Reset all Telegram access (admin only)' },
{ command: 'new', description: 'Start a fresh conversation (memory is kept)' },
];
diff --git a/src/cli/plugins-cli.ts b/src/cli/plugins-cli.ts
new file mode 100644
index 00000000..a0c8cc45
--- /dev/null
+++ b/src/cli/plugins-cli.ts
@@ -0,0 +1,166 @@
+/**
+ * `mercury plugins …` from a shell. Same commands and wording as `/plugins`
+ * in chat (it runs the same handler), forwarded to the background Mercury
+ * when one is running, so that process starts and stops the plugins itself.
+ * `validate` is the author-side conformance kit and runs here.
+ */
+import type { Command } from 'commander';
+import chalk from 'chalk';
+import { resolve } from 'node:path';
+import type { ChannelMessage } from '../types/channel.js';
+
+async function run(line: string): Promise<void> {
+ const { handlePluginsCommand } = await import('../plugins/commands.js');
+ const msg: ChannelMessage = {
+ id: `cli-plugins-${Date.now()}`,
+ channelId: 'cli',
+ channelType: 'cli',
+ senderId: 'owner',
+ content: line,
+ timestamp: Date.now(),
+ };
+ let failed = false;
+ await handlePluginsCommand(line, msg, {
+ type: 'cli',
+ send: async (text) => {
+ if (text.startsWith('✗')) failed = true;
+ // Chat wording says "/plugins x"; in a shell it's "mercury plugins x".
+ console.log(text.replace(/(^|[\s:(])\/plugins\b/g, '$1mercury plugins'));
+ },
+ });
+ if (failed) process.exitCode = 1;
+}
+
+function quote(args: string[]): string {
+ return args.map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(' ');
+}
+
+export function registerPluginsCli(program: Command): void {
+ const plugins = program
+ .command('plugins')
+ .alias('plugin')
+ .description('Install, enable, disable, update and remove plugins');
+
+ plugins.command('list', { isDefault: true }).alias('ls').description('Installed and available plugins').action(() => run('/plugins list'));
+ plugins.command('search <text...>').description('Find plugins in the catalog').action((text: string[]) => run(`/plugins search ${quote(text)}`));
+ plugins.command('info <id>').description('Details, tools and permissions').action((id: string) => run(`/plugins info ${id}`));
+ plugins
+ .command('install <source>')
+ .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' : ''}`));
+ 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'}`));
+ plugins.command('rollback <id>').description('Go back to the previous installed version').action((id: string) => run(`/plugins rollback ${id}`));
+ plugins
+ .command('uninstall <id>')
+ .alias('remove')
+ .description('Remove a plugin (keeps its data unless --purge)')
+ .option('--purge', 'Also delete its data and settings')
+ .option('-y, --yes', 'Skip the confirmation')
+ .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('init <id>')
+ .description('Start a new plugin in ./<id> (for plugin authors)')
+ .option('--out-of-process', 'An MCP server in its own process instead of a module inside Mercury')
+ .action(async (id: string, opts: { outOfProcess?: boolean }) => {
+ const { scaffoldPlugin } = await import('../plugins/scaffold.js');
+ try {
+ const dir = scaffoldPlugin(process.cwd(), id, opts.outOfProcess ? 'out-of-process' : 'in-process');
+ console.log('');
+ console.log(chalk.green(` ✓ Created ${dir}`));
+ console.log(chalk.dim(` cd ${id} && mercury plugins validate . && mercury plugins install . --yes`));
+ console.log('');
+ } catch (err) {
+ console.error(chalk.red(` ✗ ${(err as Error).message}`));
+ process.exitCode = 1;
+ }
+ });
+
+ plugins
+ .command('pack [folder]')
+ .description('Package a plugin as .tgz and print its checksum and catalog entry (for plugin authors)')
+ .option('-o, --out <dir>', 'Where to write the .tgz', '.')
+ .action(async (folder: string | undefined, opts: { out: string }) => {
+ const { packPlugin } = await import('../plugins/scaffold.js');
+ try {
+ const r = await packPlugin(resolve(folder ?? '.'), resolve(opts.out));
+ console.log('');
+ console.log(chalk.green(` ✓ ${r.file}`));
+ console.log(chalk.dim(` ${(r.size / 1024).toFixed(1)} KB · sha256 ${r.sha256}`));
+ console.log('');
+ console.log(' Catalog entry (fix the artifact URL once the release exists):');
+ console.log(JSON.stringify(r.entry, null, 2).replace(/^/gm, ' '));
+ console.log('');
+ } catch (err) {
+ console.error(chalk.red(` ✗ ${(err as Error).message}`));
+ process.exitCode = 1;
+ }
+ });
+
+ plugins
+ .command('validate [folder]')
+ .description('Check a plugin package the way Mercury will run it (for plugin authors)')
+ .option('--json', 'Print the report as JSON')
+ .action(async (folder: string | undefined, opts: { json?: boolean }) => {
+ const { runConformance } = await import('../plugins/conformance.js');
+ const report = await runConformance(resolve(folder ?? '.'));
+ if (opts.json) {
+ console.log(JSON.stringify(report, null, 2));
+ } else {
+ console.log('');
+ console.log(chalk.bold(` ${report.id ? `${report.id}@${report.version}` : 'plugin'} conformance`));
+ for (const c of report.checks) {
+ console.log(` ${c.ok ? chalk.green('✓') : chalk.red('✗')} ${c.name}${c.detail ? chalk.dim(` · ${c.detail}`) : ''}`);
+ }
+ console.log('');
+ console.log(report.ok ? chalk.green(' Ready to install and publish.') : chalk.red(' Fix the ✗ items above before publishing.'));
+ console.log('');
+ }
+ if (!report.ok) process.exitCode = 1;
+ // An out-of-process server or a plugin timer must not hold the CLI open.
+ setTimeout(() => process.exit(process.exitCode ?? 0), 50).unref();
+ });
+}
+
+/** `mercury doctor --plugins`: what's installed, what's off and why, and what to do. */
+export async function runPluginDoctor(): Promise<void> {
+ const { getPluginService } = await import('../plugins/service.js');
+ const { isSafeModeRequested } = await import('../plugins/manager.js');
+ const { readState } = await import('../plugins/store.js');
+ const svc = getPluginService();
+ console.log('');
+ console.log(chalk.bold(' Plugins'));
+ console.log(chalk.dim(` ${svc.mode === 'daemon' ? 'Asking the running Mercury' : svc.mode === 'offline' ? 'Mercury is not running: showing what is on disk' : 'This process runs plugins'}`));
+ let problems = 0;
+ try {
+ const { items, safeMode, catalogError } = await svc.list();
+ if (safeMode || isSafeModeRequested()) console.log(chalk.yellow(' ⚠ Safe mode is on: no plugin runs until Mercury restarts without --safe-mode / MERCURY_PLUGINS=off.'));
+ const boot = readState().boot;
+ if (boot.failedBoots > 0) console.log(chalk.yellow(` ⚠ Mercury failed to start ${boot.failedBoots} time(s) right after a plugin change${boot.lastChange ? ` (${boot.lastChange.id})` : ''}.`));
+ const installed = items.filter((i) => i.installedVersion);
+ if (!installed.length) console.log(chalk.dim(' No plugins installed.'));
+ for (const i of installed) {
+ const bad = i.status === 'error' || i.status === 'incompatible' || (i.disabled && i.disabled.code !== 'user');
+ if (bad) problems++;
+ const mark = i.status === 'enabled' ? chalk.green('✓') : bad ? chalk.red('✗') : chalk.dim('○');
+ const why = i.status === 'incompatible' ? i.incompatibleReason : i.status === 'error' ? i.lastError ?? 'enabled but not running' : i.disabled && i.disabled.code !== 'user' ? `turned off automatically (${i.disabled.code}): ${i.disabled.message}` : i.status;
+ console.log(` ${mark} ${i.id}@${i.installedVersion} ${chalk.dim(`· ${why}`)}`);
+ if (bad && i.disabled && ['errors', 'crashed', 'activation', 'boot-guard'].includes(i.disabled.code)) {
+ console.log(chalk.dim(` fix: mercury plugins update ${i.id}, or mercury plugins rollback ${i.id}, then mercury plugins enable ${i.id}`));
+ } else if (bad && i.disabled?.code === 'integrity') {
+ console.log(chalk.dim(` fix: its files changed since install. Reinstall it: mercury plugins install ${i.id} --yes`));
+ }
+ }
+ if (catalogError) console.log(chalk.dim(` Catalog: ${catalogError}`));
+ } catch (err) {
+ problems++;
+ console.log(chalk.red(` ✗ ${(err as Error).message}`));
+ }
+ console.log('');
+ if (problems) process.exitCode = 1;
+}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index ea4c01fb..df33117d 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -96,6 +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 { 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';
@@ -749,6 +750,25 @@ export class Agent {
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)) {
+ const channel = this.channels.getChannelForMessage(msg);
+ if (channel) {
+ handlePluginsCommand(trimmed, msg, channel).catch((err) => {
+ logger.error({ err: (err as any)?.message ?? err, content: trimmed.slice(0, 50) }, '/plugins command failed');
+ });
+ }
+ return;
+ }
+
+ // Slash commands contributed by plugins. Built-in names are reserved,
+ // so a plugin can never take over /help, /stop, /bots and so on.
+ if (trimmed.startsWith('/')) {
+ const channel = this.channels.getChannelForMessage(msg);
+ if (channel && tryPluginCommand(trimmed, msg, channel)) return;
+ }
+
// /bot <id> <message> — talk to a named bot from ANY channel (TUI,
// Telegram, web). Durable enqueue; the run's output is delivered back
// to the requesting chat via the job's source (Telegram first).
diff --git a/src/core/commands/fast-path-command.ts b/src/core/commands/fast-path-command.ts
index 59b1e5de..f284bc71 100644
--- a/src/core/commands/fast-path-command.ts
+++ b/src/core/commands/fast-path-command.ts
@@ -77,7 +77,7 @@ export async function handleFastPathCommand(agent: Agent, msg: ChannelMessage):
}
if (trimmed === '/help') {
- await channel.send('Agent is busy. Available: /sessions, /session, /agents, /halt, /stop, /progress, /spotify, /code, /research, /memory, /bg, /bots (always available — the bot lane is separate), /bot <id> <task>', msg.channelId);
+ await channel.send('Agent is busy. Available: /sessions, /session, /agents, /halt, /stop, /progress, /spotify, /code, /research, /memory, /bg, /bots (always available — the bot lane is separate), /bot <id> <task>, /plugins', msg.channelId);
return;
}
diff --git a/src/index.ts b/src/index.ts
index c61d4b05..7b47f002 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -53,6 +53,8 @@ import { ShortTermMemory, LongTermMemory, EpisodicMemory, migrateLegacyMemory }
import { buildConversationHistoryPayload, CloudSessionSynchronizer, SessionRepository } from './sessions/index.js';
import { UserMemoryStore } from './memory/user-memory.js';
import { BotManager } from './bots/bot-manager.js';
+import { getPluginManager, peekPluginManager } from './plugins/manager.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';
import { runStorageDoctor } from './utils/storage-doctor.js';
@@ -2408,6 +2410,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
}
process.on('uncaughtException', (err) => {
try { line(`UNCAUGHT: ${err?.stack || err}`); } catch { /* disk full */ }
+ // A throw from a plugin's own code (a stray timer, an event handler)
+ // disables that plugin instead of taking Mercury down with it.
+ try { if (peekPluginManager()?.attributeFault(err)) return; } catch { /* fall through to exit */ }
try { writeCrashFlag({ reason: `Uncaught: ${String(err?.message || err)}`.slice(0, 300), timestamp: Date.now() }); } catch {}
// A TUI-crashed process must not linger headless: it would hold the
// runtime pid files and silently block every future launch. Print,
@@ -2419,6 +2424,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
});
process.on('unhandledRejection', (reason) => {
try { line(`REJECTION: ${reason instanceof Error ? reason.stack : String(reason)}`); } catch {}
+ try { if (peekPluginManager()?.attributeFault(reason)) return; } catch { /* keep going */ }
// A rejected boot (e.g. "runtime already running") must fail loudly,
// not exit(0) as if nothing happened.
const message = String(reason instanceof Error ? reason.message : reason || '');
@@ -2661,6 +2667,16 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
agent.setSupervisor(supervisor);
}
+ // Plugins run only in the process that owns the runtime (ADR-024); an
+ // attached terminal forwards /plugins to it. Boot is fire-and-forget:
+ // a broken plugin is disabled, never a reason for Mercury not to start.
+ const pluginManager = daemonOwnsRuntime ? undefined : getPluginManager();
+ if (pluginManager) {
+ pluginManager.setRunsPlugins(true);
+ pluginManager.setNotifier((m) => agent.notifyAllChannels(m));
+ void pluginManager.boot().catch((err) => logger.error({ err }, 'Plugin boot failed'));
+ }
+
// Mercury Bots: fleet manager runs outside the main message queue.
let botManager: BotManager | undefined;
if (config.bots?.enabled && !daemonOwnsRuntime) {
@@ -3744,6 +3760,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
// Release the bots' SQLite queue handle — on Windows an open handle
// keeps queue.db locked against any later uninstall/replace.
try { botManager?.dispose(); } catch { /* best effort */ }
+ try { await pluginManager?.shutdown(); } catch { /* best effort */ }
await agent.shutdown();
clearCloudRuntimeOnline();
releaseRuntimeProcess(runtimeMode);
@@ -3819,6 +3836,10 @@ function removeBootCrashHandlers(): void {
}
installBootCrashHandlers();
+// --safe-mode must reach the daemon child too, which is spawned with this
+// process's environment but its own argv.
+if (process.argv.includes('--safe-mode')) process.env.MERCURY_PLUGINS = 'off';
+
const program = new Command();
program
@@ -3826,6 +3847,7 @@ program
.description('Mercury — Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access.')
.version(pkgVersion)
.option('-v, --verbose', 'Show debug logs')
+ .option('--safe-mode', 'Start with every plugin turned off (also MERCURY_PLUGINS=off)')
.action(async () => {
if (!isSetupComplete()) {
await configure();
@@ -3858,6 +3880,7 @@ program
.option('-f, --foreground', 'Run in foreground (attached to terminal)')
.option('-d, --detached', 'Run in background (daemon mode) — same as default')
.option('--daemon', 'Internal flag for daemon child process')
+ .option('--safe-mode', 'Start with every plugin turned off')
.action(async (opts) => {
if (opts.daemon) {
await runWithWatchdog(() => runAgent(true));
@@ -3978,6 +4001,7 @@ program
.description('Reconfigure Mercury setup (name, providers, channels, permissions defaults)')
.option('--platform', 'Show platform compatibility diagnostics')
.option('--storage', 'Show SQLite backend, database files and row counts')
+ .option('--plugins', 'Check installed plugins and why any are turned off')
.action(async (opts) => {
{
// Keys that cannot be right — say so before anything is tried.
@@ -3993,6 +4017,11 @@ program
runStorageDoctor();
return;
}
+ if (opts.plugins) {
+ const { runPluginDoctor } = await import('./cli/plugins-cli.js');
+ await runPluginDoctor();
+ return;
+ }
// The daemon reads providers, keys and channels at boot: a reconfigure
// that only wrote the file looked like it did nothing until a manual
// `mercury restart`. Restart it ourselves when something changed.
@@ -5063,6 +5092,8 @@ program
console.log('');
});
+registerPluginsCli(program);
+
const cloud = program.command('cloud').description('Manage Mercury Cloud connection');
cloud
diff --git a/src/plugins/catalog.ts b/src/plugins/catalog.ts
new file mode 100644
index 00000000..dcf4a43f
--- /dev/null
+++ b/src/plugins/catalog.ts
@@ -0,0 +1,107 @@
+/**
+ * The plugin catalog: an index of installable plugins, each pinned to a
+ * version and SHA-256. Fetched over HTTPS (SSRF-guarded), validated, and
+ * cached so /plugins still works offline. One malformed entry never hides
+ * the rest: entries are validated individually.
+ */
+import { existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { guardedFetch } from '../utils/ssrf.js';
+import { logger } from '../utils/logger.js';
+import { pluginsRoot, writeJsonAtomic } from './store.js';
+import { catalogEntrySchema, type Catalog, type CatalogEntry } from './types.js';
+
+export const DEFAULT_CATALOG_URL = 'https://mercuryagent.sh/plugins/catalog.json';
+const MAX_AGE_MS = 6 * 60 * 60 * 1000;
+const MAX_BYTES = 2 * 1024 * 1024;
+
+export function catalogUrl(): string {
+ const override = process.env.MERCURY_PLUGIN_CATALOG_URL?.trim();
+ return override && /^https:\/\//.test(override) ? override : DEFAULT_CATALOG_URL;
+}
+
+interface CacheFile {
+ url: string;
+ fetchedAt: string;
+ catalog: Catalog;
+}
+
+export interface CatalogResult {
+ entries: CatalogEntry[];
+ fetchedAt?: string;
+ /** True when served from cache because the network fetch failed. */
+ stale: boolean;
+ error?: string;
+}
+
+function cachePath(): string {
+ return join(pluginsRoot(), 'catalog-cache.json');
+}
+
+function readCache(url: string): CacheFile | null {
+ try {
+ if (!existsSync(cachePath())) return null;
+ const c = JSON.parse(readFileSync(cachePath(), 'utf8')) as CacheFile;
+ return c.url === url && Array.isArray(c.catalog?.plugins) ? c : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Keep valid entries, report how many were dropped. */
+export function parseCatalog(raw: unknown): { catalog: Catalog; dropped: number } {
+ const obj = raw as { catalogVersion?: unknown; updatedAt?: unknown; plugins?: unknown };
+ if (!obj || obj.catalogVersion !== 1 || !Array.isArray(obj.plugins)) throw new Error('not a version 1 plugin catalog');
+ const plugins: CatalogEntry[] = [];
+ let dropped = 0;
+ const seen = new Set<string>();
+ for (const entry of obj.plugins.slice(0, 500)) {
+ const parsed = catalogEntrySchema.safeParse(entry);
+ if (parsed.success && !seen.has(parsed.data.id)) {
+ seen.add(parsed.data.id);
+ plugins.push(parsed.data);
+ } else {
+ dropped += 1;
+ }
+ }
+ return { catalog: { catalogVersion: 1, updatedAt: String(obj.updatedAt ?? ''), plugins }, dropped };
+}
+
+/** `MERCURY_PLUGIN_CATALOG_URL=off` disables the catalog (air-gapped installs, tests). */
+export function catalogDisabled(): boolean {
+ return /^(off|none|disabled)$/i.test(process.env.MERCURY_PLUGIN_CATALOG_URL?.trim() ?? '');
+}
+
+export async function getCatalog(opts: { force?: boolean } = {}): Promise<CatalogResult> {
+ if (catalogDisabled()) return { entries: [], stale: false };
+ const url = catalogUrl();
+ const cached = readCache(url);
+ if (!opts.force && cached && Date.now() - Date.parse(cached.fetchedAt) < MAX_AGE_MS) {
+ return { entries: cached.catalog.plugins, fetchedAt: cached.fetchedAt, stale: false };
+ }
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(), 10_000);
+ try {
+ const res = await guardedFetch(url, ac.signal, { accept: 'application/json', 'user-agent': 'mercury-plugins' });
+ if (!res.ok) throw new Error(`catalog returned HTTP ${res.status}`);
+ const text = await res.text();
+ if (text.length > MAX_BYTES) throw new Error('catalog is too large');
+ const { catalog, dropped } = parseCatalog(JSON.parse(text));
+ if (dropped > 0) logger.warn({ dropped }, 'Plugin catalog: skipped invalid entries');
+ const fetchedAt = new Date().toISOString();
+ mkdirSync(pluginsRoot(), { recursive: true });
+ writeJsonAtomic(cachePath(), { url, fetchedAt, catalog } satisfies CacheFile);
+ return { entries: catalog.plugins, fetchedAt, stale: false };
+ } catch (err) {
+ const message = (err as Error).name === 'AbortError' ? 'timed out' : (err as Error).message;
+ logger.info({ err: message }, 'Plugin catalog unavailable; using cache');
+ return { entries: cached?.catalog.plugins ?? [], fetchedAt: cached?.fetchedAt, stale: true, error: message };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export async function findCatalogEntry(id: string, opts: { force?: boolean } = {}): Promise<CatalogEntry | undefined> {
+ const { entries } = await getCatalog(opts);
+ return entries.find((e) => e.id === id);
+}
diff --git a/src/plugins/commands.test.ts b/src/plugins/commands.test.ts
new file mode 100644
index 00000000..b4987009
--- /dev/null
+++ b/src/plugins/commands.test.ts
@@ -0,0 +1,28 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { RESERVED_COMMANDS } from './types.js';
+import { manifestSchema } from './types.js';
+
+const root = dirname(fileURLToPath(import.meta.url));
+
+describe('reserved command names', () => {
+ it('cover every built-in in the TUI autocomplete list (SLASH_COMMANDS)', () => {
+ const src = readFileSync(join(root, '..', 'ui', 'input-composer.tsx'), 'utf8');
+ const block = src.slice(src.indexOf('export const SLASH_COMMANDS'), src.indexOf('];', src.indexOf('export const SLASH_COMMANDS')));
+ const names = [...block.matchAll(/'\/([a-z][a-z0-9_-]*)/g)].map((m) => m[1]);
+ expect(names.length).toBeGreaterThan(20);
+ const missing = [...new Set(names)].filter((n) => !RESERVED_COMMANDS.has(n));
+ expect(missing, 'add these built-ins to RESERVED_COMMANDS in src/plugins/types.ts').toEqual([]);
+ });
+
+ it('a manifest claiming a built-in command is rejected at install', () => {
+ const r = manifestSchema.safeParse({
+ manifestVersion: 1, id: 'evil-help', name: 'x', version: '1.0.0', description: 'x', kind: 'in-process',
+ engines: { mercury: '>=1.0.0' }, entry: 'i.mjs', contributes: { tools: [], commands: [{ name: 'help', description: 'mine now' }] },
+ });
+ expect(r.success).toBe(false);
+ expect(JSON.stringify(r.error?.issues)).toMatch(/\/help is a built-in Mercury command/);
+ });
+});
diff --git a/src/plugins/commands.ts b/src/plugins/commands.ts
new file mode 100644
index 00000000..98429377
--- /dev/null
+++ b/src/plugins/commands.ts
@@ -0,0 +1,301 @@
+/**
+ * `/plugins` in chat (terminal, Telegram, web, Discord, Slack) and dispatch
+ * of slash commands that plugins contribute.
+ *
+ * /plugins everything: installed + catalog, with status
+ * /plugins search <text>
+ * /plugins info <id>
+ * /plugins install <id|path|url|github:owner/repo> [--yes]
+ * /plugins enable <id> /plugins disable <id>
+ * /plugins update [id|all] /plugins rollback <id>
+ * /plugins uninstall <id> [--purge] [--yes]
+ * /plugins set <id> <key> <value>
+ *
+ * Install and uninstall always preview first (what the plugin needs, what
+ * will be removed) and act only with --yes; on Telegram that's one tap.
+ * Members (non-admins on role-aware channels) can only list and read.
+ */
+import type { ChannelMessage } from '../types/channel.js';
+import { getPluginManager } from './manager.js';
+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';
+
+export { RESERVED_COMMANDS };
+
+interface ChannelLike {
+ send(content: string, targetId?: string): Promise<void>;
+ sendWithActions?(content: string, rows: Array<Array<{ label: string; command: string }>>, targetId?: string): Promise<void>;
+ type?: string;
+}
+
+const STATUS_ICON: Record<PluginListItem['status'], string> = {
+ enabled: '✅', disabled: '⏸', 'update-available': '⬆️', available: '○', incompatible: '🚫', installed: '•', error: '⚠️',
+};
+
+function mb(bytes?: number): string {
+ if (!bytes) return '';
+ return bytes >= 1048576 ? `${(bytes / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
+}
+
+function statusBits(i: PluginListItem): string {
+ const bits: string[] = [];
+ if (i.status === 'enabled') bits.push('enabled');
+ else if (i.status === 'disabled') bits.push(i.disabled?.code === 'user' || !i.disabled ? 'disabled' : `disabled: ${i.disabled.message}`);
+ else if (i.status === 'update-available') bits.push('update available');
+ else if (i.status === 'error') bits.push(`not running${i.lastError ? `: ${i.lastError}` : ''}`);
+ else if (i.status === 'incompatible') bits.push(`incompatible: ${i.incompatibleReason ?? ''}`);
+ else bits.push('available');
+ bits.push(i.tier);
+ if (i.kind === 'out-of-process') bits.push('own process');
+ const size = mb(i.sizeBytes);
+ if (size) bits.push(size);
+ if (i.tools.length) bits.push(`${i.tools.length} tool${i.tools.length === 1 ? '' : 's'}`);
+ return bits.join(' · ');
+}
+
+function version(i: PluginListItem): string {
+ return i.installedVersion
+ ? (i.status === 'update-available' ? `${i.installedVersion} → ${i.latestVersion}` : i.installedVersion)
+ : i.latestVersion ?? '';
+}
+
+function line(i: PluginListItem): string {
+ return `${STATUS_ICON[i.status]} ${i.name} ${version(i)} (${i.id}): ${statusBits(i)}`.replace(/\s+/g, ' ').trim();
+}
+
+function describe(i: PluginListItem): string {
+ const lines = [
+ `🧩 ${i.name} (${i.id})`,
+ i.description,
+ '',
+ `Version: ${version(i)}`,
+ `Status: ${statusBits(i)}`,
+ `Runs: ${i.kind === 'out-of-process' ? 'in its own process (crashes can’t affect Mercury)' : 'inside Mercury'}`,
+ `Source: ${i.tier === 'local' ? 'installed from a path or URL (unverified)' : `${i.tier} catalog${i.verified ? ', checksum verified' : ''}`}`,
+ ];
+ if (i.tools.length) lines.push(`Tools: ${i.tools.join(', ')}`);
+ if (i.commands.length) lines.push(`Commands: ${i.commands.join(', ')}`);
+ 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'}`);
+ if (i.lastError && i.status !== 'enabled') lines.push(`Last error: ${i.lastError}`);
+ return lines.join('\n');
+}
+
+function actionsFor(i: PluginListItem): Array<{ label: string; command: string }> {
+ const short = i.name.slice(0, 18);
+ if (i.status === 'available') return [{ label: `⬇ Install ${short}`, command: `/plugins install ${i.id}` }, { label: 'ℹ Info', command: `/plugins info ${i.id}` }];
+ if (i.status === 'incompatible' && !i.installedVersion) return [{ label: `ℹ ${short}`, command: `/plugins info ${i.id}` }];
+ const row: Array<{ label: string; command: string }> = [];
+ if (i.status === 'update-available') row.push({ label: `⬆ Update ${short}`, command: `/plugins update ${i.id}` });
+ if (i.enabled) row.push({ label: `⏸ Disable ${i.status === 'update-available' ? '' : short}`.trim(), command: `/plugins disable ${i.id}` });
+ else row.push({ label: `▶ Enable ${short}`, command: `/plugins enable ${i.id}` });
+ row.push({ label: '🗑 Uninstall', command: `/plugins uninstall ${i.id}` });
+ return row;
+}
+
+const HELP = [
+ 'Usage:',
+ ' /plugins list installed and available plugins',
+ ' /plugins search <text> find plugins',
+ ' /plugins info <id> details, tools and permissions',
+ ' /plugins install <id|path|url> install (asks to confirm)',
+ ' /plugins enable|disable <id>',
+ ' /plugins update [id|all]',
+ ' /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',
+].join('\n');
+
+function isMember(msg: ChannelMessage): boolean {
+ return msg.senderRole === 'member';
+}
+
+export async function handlePluginsCommand(trimmed: string, msg: ChannelMessage, channel: ChannelLike): Promise<void> {
+ const to = msg.channelId;
+ const reply = (text: string) => channel.send(text, to);
+ const tokens = trimmed.replace(/^\/plugins?\b/, '').trim().split(/\s+/).filter(Boolean);
+ 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;
+ const mgr = getPluginService();
+ const mutating = ['install', 'enable', 'disable', 'update', 'rollback', 'uninstall', 'remove', 'set'].includes(sub);
+ if (mutating && isMember(msg)) {
+ await reply('Only the owner or an admin can change plugins.');
+ return;
+ }
+
+ try {
+ switch (sub) {
+ case 'list':
+ case 'ls': {
+ const { items, catalogError, stale, safeMode } = await mgr.list();
+ const installed = items.filter((i) => i.installedVersion);
+ const available = items.filter((i) => !i.installedVersion);
+ const lines = [`🧩 Plugins · ${installed.length} installed, ${installed.filter((i) => i.status === 'enabled').length} enabled · ${available.length} in the catalog`];
+ if (safeMode) lines.push('🛟 Safe mode: plugins are off for this run (restart without --safe-mode).');
+ if (installed.length) lines.push('', 'Installed', ...installed.map(line));
+ if (available.length) lines.push('', 'Available', ...available.slice(0, 25).map(line));
+ if (!installed.length && !available.length) lines.push('', 'Nothing installed yet, and the catalog is empty or unreachable.');
+ if (catalogError) lines.push('', `Catalog ${stale ? 'offline (showing the last copy)' : 'unavailable'}: ${catalogError}`);
+ lines.push('', 'Tip: /plugins info <id> · /plugins install <id> · /plugins help');
+ if (typeof channel.sendWithActions === 'function' && channel.type !== 'cli' && !isMember(msg)) {
+ const rows = [...installed, ...available].slice(0, 10).map(actionsFor);
+ await channel.sendWithActions(lines.join('\n'), rows, to);
+ } else {
+ await reply(lines.join('\n'));
+ }
+ return;
+ }
+ case 'help':
+ await reply(HELP);
+ return;
+ case 'search': {
+ const q = [target, ...rest].join(' ').toLowerCase();
+ if (!q) { await reply('Usage: /plugins search <text>'); return; }
+ const { items } = await mgr.list();
+ const hits = items.filter((i) => `${i.id} ${i.name} ${i.description}`.toLowerCase().includes(q));
+ await reply(hits.length ? hits.map(line).join('\n') : `No plugins match "${q}".`);
+ return;
+ }
+ case 'info': {
+ if (!target) { await reply('Usage: /plugins info <id>'); return; }
+ const i = await mgr.info(target);
+ if (!i) { await reply(`No plugin called "${target}". Try /plugins.`); return; }
+ if (typeof channel.sendWithActions === 'function' && channel.type !== 'cli' && !isMember(msg)) await channel.sendWithActions(describe(i), [actionsFor(i)], to);
+ else await reply(describe(i));
+ return;
+ }
+ case 'install':
+ case 'add': {
+ if (!target) { await reply('Usage: /plugins install <id | folder | file.tgz | https URL | github:owner/repo>'); return; }
+ if (!yes) {
+ await reply(await installPreview(target));
+ if (typeof channel.sendWithActions === 'function' && channel.type !== 'cli') {
+ await channel.sendWithActions('Install it?', [[{ label: '✅ Install', command: `/plugins install ${target} --yes` }, { label: '✖ Cancel', command: '/plugins' }]], to);
+ } else {
+ await reply(`To install, run: /plugins install ${target} --yes`);
+ }
+ return;
+ }
+ await reply(`⬇ Installing ${target}…`);
+ 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
+ ? `${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}.` : ''}`);
+ return;
+ }
+ case 'enable':
+ if (!target) { await reply('Usage: /plugins enable <id>'); return; }
+ await mgr.enable(target);
+ await reply(`▶ Enabled ${target}.`);
+ return;
+ case 'disable':
+ if (!target) { await reply('Usage: /plugins disable <id>'); return; }
+ await mgr.disable(target);
+ await reply(`⏸ Disabled ${target}. Its data and settings are kept; /plugins enable ${target} turns it back on.`);
+ return;
+ case 'update':
+ case 'upgrade': {
+ const id = target && target !== 'all' ? target : undefined;
+ const changed = await mgr.update(id);
+ await reply(changed.length ? changed.map((c) => `⬆ ${c.id}: ${c.from} → ${c.to}`).join('\n') : (id ? `${id} is up to date.` : 'All catalog plugins are up to date.'));
+ return;
+ }
+ case 'rollback': {
+ if (!target) { await reply('Usage: /plugins rollback <id>'); return; }
+ const r = await mgr.rollback(target);
+ await reply(`↩ ${target}: ${r.from} → ${r.to}`);
+ return;
+ }
+ case 'uninstall':
+ case 'remove': {
+ if (!target) { await reply('Usage: /plugins uninstall <id> [--purge]'); return; }
+ const i = await mgr.info(target);
+ if (!i?.installedVersion) { await reply(`"${target}" is not installed.`); return; }
+ if (!yes) {
+ const what = purge ? 'its code, data and settings' : 'its code (data and settings are kept; add --purge to delete them too)';
+ if (typeof channel.sendWithActions === 'function' && channel.type !== 'cli') {
+ await channel.sendWithActions(`Uninstall ${i.name}? This removes ${what}.`, [[
+ { label: '🗑 Uninstall', command: `/plugins uninstall ${target} --yes` },
+ { label: '🗑 + delete data', command: `/plugins uninstall ${target} --purge --yes` },
+ { label: '✖ Cancel', command: '/plugins' },
+ ]], to);
+ } else {
+ await reply(`Uninstalling ${i.name} removes ${what}.\nTo confirm, run: /plugins uninstall ${target}${purge ? ' --purge' : ''} --yes`);
+ }
+ return;
+ }
+ await mgr.uninstall(target, purge);
+ await reply(`🗑 Uninstalled ${i.name}${purge ? ' and deleted its data' : ' (data kept)'}.`);
+ return;
+ }
+ case 'set': {
+ const [key, ...valueParts] = rest;
+ if (!target || !key || !valueParts.length) { await reply('Usage: /plugins set <id> <key> <value>'); return; }
+ await mgr.setSetting(target, key, valueParts.join(' '));
+ await reply(`⚙ ${target}.${key} updated.`);
+ return;
+ }
+ default:
+ await reply(`Unknown /plugins command "${sub}".\n\n${HELP}`);
+ }
+ } catch (err) {
+ await reply(`✗ ${(err as Error).message}`);
+ }
+}
+
+async function installPreview(target: string): Promise<string> {
+ const { entries } = await getCatalog();
+ const entry = entries.find((e) => e.id === target);
+ if (entry) {
+ const art = entry.artifact ?? Object.values(entry.artifacts ?? {})[0];
+ return [
+ `🧩 ${entry.name} ${entry.version} (${entry.id}) · ${entry.tier}`,
+ entry.description,
+ '',
+ `Runs: ${entry.kind === 'out-of-process' ? 'in its own process' : 'inside Mercury'}`,
+ `Download: ${mb(art?.size) || 'unknown size'}, checksum-verified`,
+ `Tools: ${entry.tools.length ? entry.tools.join(', ') : 'none listed'}`,
+ `Network: ${entry.permissions.network.length ? entry.permissions.network.join(', ') : 'none'}`,
+ `Secrets it can read: ${entry.permissions.secrets.length ? entry.permissions.secrets.join(', ') : 'none'}`,
+ ].join('\n');
+ }
+ return [
+ `⚠️ "${target}" is not from the catalog, so its contents aren't verified by Mercury.`,
+ 'Only install plugins from sources you trust: an in-process plugin runs inside Mercury with your permissions.',
+ 'After install, /plugins info <id> shows its tools, network access and the secrets it can read.',
+ ].join('\n');
+}
+
+/** Run `/<name> args` if a plugin registered that command. Returns false if none did. */
+export function tryPluginCommand(trimmed: string, msg: ChannelMessage, channel: ChannelLike): boolean {
+ const m = /^\/([a-z][a-z0-9_]{0,29})(?:\s+([\s\S]*))?$/.exec(trimmed);
+ if (!m || RESERVED_COMMANDS.has(m[1])) return false;
+ const cmd = getPluginCommand(m[1]);
+ if (!cmd) return false;
+ const to = msg.channelId;
+ if (isMember(msg)) {
+ void channel.send('Only the owner or an admin can run plugin commands.', to).catch(() => {});
+ return true;
+ }
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(new Error('timeout')), 120_000);
+ void cmd.run((m[2] ?? '').trim(), { reply: (text) => channel.send(String(text).slice(0, 8000), to), signal: ac.signal })
+ .catch((err) => {
+ getPluginManager().recordFailure(cmd.pluginId, `/${cmd.name}: ${(err as Error).message}`);
+ return channel.send(`✗ /${cmd.name} (${cmd.pluginName}) failed: ${(err as Error).message}`, to);
+ })
+ .catch(() => {})
+ .finally(() => clearTimeout(timer));
+ return true;
+}
+
+export function pluginCommandHelp(): string[] {
+ return listPluginCommands().filter((c) => !RESERVED_COMMANDS.has(c.name)).map((c) => `/${c.name}: ${c.description} (${c.pluginName})`);
+}
diff --git a/src/plugins/conformance.ts b/src/plugins/conformance.ts
new file mode 100644
index 00000000..a8c16176
--- /dev/null
+++ b/src/plugins/conformance.ts
@@ -0,0 +1,164 @@
+/**
+ * Conformance kit: `mercury plugins validate <folder>`.
+ *
+ * Runs a plugin package through everything Mercury will do to it (install
+ * checks, start, the tools it publishes, stop, start again) and reports each
+ * step, so an author finds out before users do. The same checks gate the
+ * official catalog.
+ */
+import { builtinModules } from 'node:module';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { checkTree, loadManifest, verifyPackage } from './installer.js';
+import { mercuryVersion, resolvedSettings } from './store.js';
+import { listLiveTools, listPluginCommands, unpublishPlugin } from './tool-bridge.js';
+import { InProcessRuntime } from './runtime/in-process.js';
+import { OutOfProcessRuntime } from './runtime/out-of-process.js';
+import type { PluginRuntime, RuntimeDeps } from './runtime/types.js';
+import type { PluginManifest } from './types.js';
+
+export interface ConformanceCheck {
+ name: string;
+ ok: boolean;
+ detail?: string;
+}
+
+export interface ConformanceReport {
+ ok: boolean;
+ id?: string;
+ version?: string;
+ checks: ConformanceCheck[];
+}
+
+const BUILTINS = new Set(builtinModules);
+const IMPORT_RE = /(?:\bimport\s*(?:[\w*{}\s,$]+\s*from\s*)?|\bexport\s*[\w*{}\s,$]+\s*from\s*|\bimport\s*\(\s*|\brequire\s*\(\s*)['"]([^'"\n]+)['"]/g;
+
+/**
+ * Imports an in-process entry makes that a compiled Mercury can't satisfy.
+ * Plugins must be bundled into one file; only `node:` builtins and files
+ * inside the package resolve.
+ */
+export function unresolvableImports(source: string): string[] {
+ const bad = new Set<string>();
+ for (const m of source.matchAll(IMPORT_RE)) {
+ const spec = m[1];
+ if (spec.startsWith('node:') || spec.startsWith('./') || spec.startsWith('../')) continue;
+ if (BUILTINS.has(spec)) continue;
+ bad.add(spec);
+ }
+ return [...bad];
+}
+
+function quietDeps(manifest: PluginManifest, dataDir: string, errors: string[]): RuntimeDeps {
+ const note = (level: string) => (message: string) => { if (level === 'error') errors.push(message); };
+ return {
+ mercuryVersion: mercuryVersion(),
+ dataDir,
+ settings: resolvedSettings(manifest),
+ secrets: Object.fromEntries(manifest.permissions.secrets.map((k) => [k, process.env[k]])),
+ log: { debug: note('debug'), info: note('info'), warn: note('warn'), error: note('error') },
+ onError: (message) => errors.push(message),
+ onFatal: (_code, message) => errors.push(message),
+ };
+}
+
+export async function runConformance(dir: string): Promise<ConformanceReport> {
+ const checks: ConformanceCheck[] = [];
+ const pass = (name: string, detail?: string) => checks.push({ name, ok: true, detail });
+ const fail = (name: string, detail: string) => checks.push({ name, ok: false, detail });
+ const done = (manifest?: PluginManifest): ConformanceReport => ({
+ ok: checks.every((c) => c.ok), id: manifest?.id, version: manifest?.version, checks,
+ });
+
+ let manifest: PluginManifest;
+ try {
+ manifest = loadManifest(dir);
+ pass('manifest', `${manifest.id}@${manifest.version} (${manifest.kind}, manifest v${manifest.manifestVersion})`);
+ } catch (err) {
+ fail('manifest', (err as Error).message);
+ return done();
+ }
+
+ try {
+ const { files, bytes } = checkTree(dir);
+ pass('package files', `${files} files, ${(bytes / 1024).toFixed(0)} KB, no links or files outside the folder`);
+ } catch (err) {
+ fail('package files', (err as Error).message);
+ }
+
+ try {
+ await verifyPackage(dir, manifest);
+ pass('compatibility and integrity', `Mercury ${mercuryVersion()}, plugin API ${manifest.engines.pluginApi}`);
+ } catch (err) {
+ fail('compatibility and integrity', (err as Error).message);
+ return done(manifest);
+ }
+
+ if (manifest.kind === 'in-process' && manifest.entry) {
+ try {
+ const bad = unresolvableImports(readFileSync(join(dir, manifest.entry), 'utf8'));
+ if (bad.length) fail('self-contained bundle', `imports packages Mercury can't provide: ${bad.join(', ')}. Bundle them into ${manifest.entry} (e.g. esbuild --bundle --format=esm --platform=node).`);
+ else pass('self-contained bundle', 'only node: builtins and files in the package');
+ } catch (err) {
+ fail('self-contained bundle', (err as Error).message);
+ }
+ }
+
+ for (const t of manifest.contributes.tools) {
+ if (!/[.!?)]$/.test(t.description.trim()) || t.description.trim().length < 20) {
+ checks.push({ name: `tool ${t.name}: description`, ok: true, detail: 'tip: one or two full sentences help the model pick the tool' });
+ }
+ }
+
+ // Start, inspect, stop, start again: hot plug must be repeatable.
+ const dataDir = mkdtempSync(join(tmpdir(), `mercury-plugin-check-${manifest.id}-`));
+ const errors: string[] = [];
+ const make = (): PluginRuntime => manifest.kind === 'in-process'
+ ? new InProcessRuntime(manifest, dir, quietDeps(manifest, dataDir, errors))
+ : new OutOfProcessRuntime(manifest, dir, quietDeps(manifest, dataDir, errors));
+ try {
+ for (const round of [1, 2]) {
+ const label = round === 1 ? 'start' : 'restart (hot plug)';
+ const runtime = make();
+ const t0 = Date.now();
+ try {
+ await runtime.start();
+ pass(label, `running in ${Date.now() - t0} ms`);
+ } catch (err) {
+ fail(label, (err as Error).message);
+ break;
+ }
+
+ if (round === 1) {
+ const live = listLiveTools().filter((t) => t.pluginId === manifest.id);
+ const missing = manifest.contributes.tools.filter((d) => !live.some((t) => t.name === d.name)).map((d) => d.name);
+ if (missing.length) fail('tools', `declared but not provided: ${missing.join(', ')}`);
+ else pass('tools', manifest.contributes.tools.length ? live.map((t) => t.name).join(', ') : 'none declared');
+ for (const t of live) {
+ const s = t.inputSchema as { type?: unknown };
+ if (s && s.type !== 'object') fail(`tool ${t.name}: input schema`, 'inputSchema must be a JSON Schema with "type": "object"');
+ }
+ const cmds = listPluginCommands().filter((c) => c.pluginId === manifest.id);
+ const missingCmds = manifest.contributes.commands.filter((d) => !cmds.some((c) => c.name === d.name)).map((d) => d.name);
+ if (missingCmds.length) fail('commands', `declared but not registered: ${missingCmds.map((n) => `/${n}`).join(', ')}`);
+ else if (manifest.contributes.commands.length) pass('commands', cmds.map((c) => `/${c.name}`).join(', '));
+ }
+
+ const t1 = Date.now();
+ try {
+ await runtime.stop();
+ const leftover = listLiveTools().some((t) => t.pluginId === manifest.id) || listPluginCommands().some((c) => c.pluginId === manifest.id);
+ if (leftover || runtime.isRunning()) fail(`${label}: stop`, 'tools or commands were still registered after stop');
+ else pass(`${label}: stop`, `clean in ${Date.now() - t1} ms`);
+ } catch (err) {
+ fail(`${label}: stop`, (err as Error).message);
+ }
+ }
+ if (errors.length) fail('errors while running', errors.slice(0, 3).join(' | '));
+ } finally {
+ unpublishPlugin(manifest.id);
+ try { rmSync(dataDir, { recursive: true, force: true }); } catch { /* temp */ }
+ }
+ return done(manifest);
+}
diff --git a/src/plugins/installer.test.ts b/src/plugins/installer.test.ts
new file mode 100644
index 00000000..83176137
--- /dev/null
+++ b/src/plugins/installer.test.ts
@@ -0,0 +1,132 @@
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, readdirSync, symlinkSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { installPackage, parseSource, rollbackPackage, sha256File, uninstallPackage, loadManifest } from './installer.js';
+import { pluginDataDir, pluginDir, pluginVersionDir, readState, stagingRoot, withLock } from './store.js';
+import { inProcessPlugin, tempHome } from './test-fixtures.js';
+
+let env: ReturnType<typeof tempHome>;
+let src: string;
+
+beforeEach(() => {
+ env = tempHome();
+ src = join(env.home, 'src');
+ mkdirSync(src, { recursive: true });
+});
+afterEach(() => env.restore());
+
+function tgz(dir: string, out: string): string {
+ execFileSync('tar', ['-czf', out, '-C', dir, '.']);
+ return out;
+}
+
+describe('parseSource', () => {
+ it('recognises ids, paths, https URLs and github repos', () => {
+ expect(parseSource('weather')).toEqual({ kind: 'id', id: 'weather' });
+ expect(parseSource('./plugins/weather')).toMatchObject({ type: 'path' });
+ expect(parseSource('/tmp/x.tgz')).toMatchObject({ type: 'path', path: '/tmp/x.tgz' });
+ expect(parseSource('https://example.com/p.tgz')).toEqual({ type: 'url', url: 'https://example.com/p.tgz' });
+ expect(parseSource('github:acme/[email protected]')).toEqual({ type: 'github', repo: 'acme/mercury-weather', tag: 'v1.2.0' });
+ });
+ it('refuses plain http and nonsense', () => {
+ expect(() => parseSource('http://example.com/p.tgz')).toThrow(/HTTPS/);
+ expect(() => parseSource('Not A Plugin!')).toThrow(/Don't know how/);
+ });
+});
+
+describe('installPackage', () => {
+ it('installs a folder atomically, disabled by default, with a data dir', async () => {
+ const dir = inProcessPlugin(src);
+ const r = await installPackage({ type: 'path', path: dir });
+ expect(r).toMatchObject({ id: 'echo-tools', version: '1.0.0', verified: false, unchanged: false });
+ expect(existsSync(join(pluginVersionDir('echo-tools', '1.0.0'), 'index.mjs'))).toBe(true);
+ expect(existsSync(pluginDataDir('echo-tools'))).toBe(true);
+ expect(readState().plugins['echo-tools']).toMatchObject({ enabled: false, version: '1.0.0', source: { type: 'path' } });
+ expect(existsSync(stagingRoot()) ? readdirSync(stagingRoot()) : []).toEqual([]);
+ });
+
+ it('installs a .tgz (npm-pack style "package/" root works too)', async () => {
+ const dir = inProcessPlugin(src, { id: 'packed' });
+ const wrap = join(env.home, 'wrap');
+ mkdirSync(join(wrap, 'package'), { recursive: true });
+ execFileSync('cp', ['-R', `${dir}/.`, join(wrap, 'package')]);
+ const archive = tgz(wrap, join(env.home, 'packed.tgz'));
+ const r = await installPackage({ type: 'path', path: archive });
+ expect(r.id).toBe('packed');
+ });
+
+ it('returns unchanged for the same version unless forced', async () => {
+ const dir = inProcessPlugin(src);
+ await installPackage({ type: 'path', path: dir });
+ expect((await installPackage({ type: 'path', path: dir })).unchanged).toBe(true);
+ expect((await installPackage({ type: 'path', path: dir }, { force: true })).unchanged).toBe(false);
+ });
+
+ it('rejects packages containing a symlink and leaves nothing behind', async () => {
+ const dir = inProcessPlugin(src, { id: 'sneaky' });
+ symlinkSync('/etc/passwd', join(dir, 'passwd'));
+ await expect(installPackage({ type: 'path', path: dir })).rejects.toThrow(/symbolic link/);
+ expect(existsSync(pluginDir('sneaky'))).toBe(false);
+ expect(readState().plugins.sneaky).toBeUndefined();
+ expect(existsSync(stagingRoot()) ? readdirSync(stagingRoot()) : []).toEqual([]);
+ });
+
+ it('rejects an invalid manifest with a readable message', async () => {
+ const dir = inProcessPlugin(src, { id: 'bad-one', manifest: { kind: 'in-process', entry: '../escape.js' } });
+ await expect(installPackage({ type: 'path', path: dir })).rejects.toThrow(/Invalid mercury-plugin.json: entry/);
+ });
+
+ it('rejects a plugin built for another Mercury version', async () => {
+ const dir = inProcessPlugin(src, { id: 'future', engines: { mercury: '>=99.0.0' } });
+ await expect(installPackage({ type: 'path', path: dir })).rejects.toThrow(/needs Mercury >=99\.0\.0/);
+ });
+
+ it('rejects a plugin needing a newer plugin API', async () => {
+ const dir = inProcessPlugin(src, { id: 'newapi', engines: { mercury: '>=1.0.0', pluginApi: '^2.0.0' } });
+ await expect(installPackage({ type: 'path', path: dir })).rejects.toThrow(/plugin API \^2\.0\.0/);
+ });
+
+ it('rejects a missing entry module', async () => {
+ const dir = inProcessPlugin(src, { id: 'noentry', manifest: { entry: 'missing.mjs' } });
+ await expect(installPackage({ type: 'path', path: dir })).rejects.toThrow(/Entry module "missing.mjs" is missing/);
+ });
+
+ it('verifies declared file checksums', async () => {
+ const dir = inProcessPlugin(src, { id: 'summed' });
+ const good = await sha256File(join(dir, 'index.mjs'));
+ writeFileSync(join(dir, 'mercury-plugin.json'), JSON.stringify({ ...loadManifest(dir), checksums: { 'index.mjs': good.replace(/^./, good[0] === 'a' ? 'b' : 'a') } }));
+ await expect(installPackage({ type: 'path', path: dir })).rejects.toThrow(/Checksum mismatch for index.mjs/);
+ });
+
+ it('keeps the previous version for rollback and prunes older ones', async () => {
+ await installPackage({ type: 'path', path: inProcessPlugin(src, { version: '1.0.0' }) });
+ await installPackage({ type: 'path', path: inProcessPlugin(src, { version: '1.1.0' }) });
+ await installPackage({ type: 'path', path: inProcessPlugin(src, { version: '1.2.0' }) });
+ expect(readdirSync(join(pluginDir('echo-tools'), 'versions')).sort()).toEqual(['1.1.0', '1.2.0']);
+ expect(readState().plugins['echo-tools']).toMatchObject({ version: '1.2.0', previousVersion: '1.1.0' });
+ expect(await rollbackPackage('echo-tools')).toEqual({ from: '1.2.0', to: '1.1.0' });
+ expect(readState().plugins['echo-tools']).toMatchObject({ version: '1.1.0', previousVersion: '1.2.0' });
+ });
+
+ it('uninstall keeps data and settings unless purge is set', async () => {
+ await installPackage({ type: 'path', path: inProcessPlugin(src) });
+ writeFileSync(join(pluginDataDir('echo-tools'), 'note.txt'), 'keep me');
+ await uninstallPackage('echo-tools');
+ expect(readState().plugins['echo-tools']).toBeUndefined();
+ expect(existsSync(join(pluginDataDir('echo-tools'), 'note.txt'))).toBe(true);
+ expect(existsSync(join(pluginDir('echo-tools'), 'versions'))).toBe(false);
+ await installPackage({ type: 'path', path: inProcessPlugin(src) });
+ await uninstallPackage('echo-tools', true);
+ expect(existsSync(pluginDir('echo-tools'))).toBe(false);
+ });
+
+ it('the install lock serialises concurrent writers', async () => {
+ const order: string[] = [];
+ await Promise.all([
+ withLock(async () => { order.push('a1'); await new Promise((r) => setTimeout(r, 50)); order.push('a2'); }),
+ (async () => { await new Promise((r) => setTimeout(r, 5)); await installPackage({ type: 'path', path: inProcessPlugin(src) }); order.push('b'); })(),
+ ]);
+ expect(order).toEqual(['a1', 'a2', 'b']);
+ });
+});
diff --git a/src/plugins/installer.ts b/src/plugins/installer.ts
new file mode 100644
index 00000000..d74cdbbb
--- /dev/null
+++ b/src/plugins/installer.ts
@@ -0,0 +1,453 @@
+/**
+ * Installing, updating, rolling back and uninstalling plugins on disk.
+ *
+ * Every install is atomic: the package is downloaded and unpacked in
+ * `.staging/`, checked (checksum, archive safety, manifest, compatibility,
+ * native file checksums), and only then moved into place with a rename.
+ * Anything that fails leaves the previous state untouched and the staging
+ * folder removed. The previous version is kept for rollback.
+ */
+import { createHash, randomBytes } from 'node:crypto';
+import { execFile } from 'node:child_process';
+import { chmodSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join, relative, resolve, sep } from 'node:path';
+import { promisify } from 'node:util';
+import { guardedFetch } from '../utils/ssrf.js';
+import { logger } from '../utils/logger.js';
+import {
+ incompatibility, pluginDir, pluginVersionDir, readState, stagingRoot, withLock, writeState, currentPlatform,
+} from './store.js';
+import { manifestSchema, PLUGIN_ID_RE, type CatalogEntry, type PluginManifest, type PluginStateEntry } from './types.js';
+
+const execFileAsync = promisify(execFile);
+
+/** Hard limits that keep a hostile or broken package from filling the disk. */
+export const LIMITS = {
+ downloadBytes: 200 * 1024 * 1024,
+ unpackedBytes: 400 * 1024 * 1024,
+ files: 5000,
+ downloadTimeoutMs: 5 * 60 * 1000,
+};
+
+export interface InstallOptions {
+ /** Catalog entry when installing by id (gives the pinned checksum). */
+ catalogEntry?: CatalogEntry;
+ /** Expected SHA-256 of the archive for URL installs. */
+ sha256?: string;
+ /** Allow a different plugin id than expected (never for catalog installs). */
+ expectId?: string;
+ /** Reinstall even if this exact version is already installed. */
+ force?: boolean;
+ onProgress?: (message: string) => void;
+}
+
+export interface InstallResult {
+ id: string;
+ version: string;
+ previousVersion?: string;
+ verified: boolean;
+ manifest: PluginManifest;
+ /** True when it was already installed at this version and nothing changed. */
+ unchanged: boolean;
+}
+
+export type InstallSource =
+ | { type: 'catalog'; entry: CatalogEntry }
+ | { type: 'path'; path: string }
+ | { type: 'url'; url: string }
+ | { type: 'github'; repo: string; tag?: string };
+
+/** Turn what the owner typed into a source. Catalog ids are resolved by the caller. */
+export function parseSource(input: string): { kind: 'id'; id: string } | InstallSource {
+ const s = input.trim();
+ if (/^https:\/\//i.test(s)) return { type: 'url', url: s };
+ if (/^http:\/\//i.test(s)) throw new Error('Plugin downloads must use HTTPS.');
+ const gh = /^(?:github:|https?:\/\/github\.com\/)?([A-Za-z0-9-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?(?:@([\w.-]+))?$/.exec(s);
+ if (s.startsWith('github:') && gh) return { type: 'github', repo: gh[1], tag: gh[2] };
+ const looksLikePath = s.startsWith('.') || s.startsWith('/') || s.startsWith('~') || /^[a-zA-Z]:[\\/]/.test(s) || s.includes(sep) || /\.(tgz|tar\.gz)$/i.test(s);
+ if (looksLikePath) return { type: 'path', path: expandHome(s) };
+ if (PLUGIN_ID_RE.test(s)) return { kind: 'id', id: s };
+ if (gh) return { type: 'github', repo: gh[1], tag: gh[2] };
+ throw new Error(`Don't know how to install "${input}". Use a plugin id, a folder or .tgz path, an https:// URL, or github:owner/repo.`);
+}
+
+function expandHome(p: string): string {
+ return p === '~' || p.startsWith('~/') ? join(homedir(), p.slice(1)) : resolve(p);
+}
+
+// ── download ──────────────────────────────────────────────────────────────
+
+async function download(url: string, dest: string, onProgress?: (m: string) => void): Promise<string> {
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(), LIMITS.downloadTimeoutMs);
+ try {
+ const res = await guardedFetch(url, ac.signal, { 'user-agent': 'mercury-plugin-installer', accept: 'application/octet-stream,*/*' });
+ if (!res.ok || !res.body) throw new Error(`Download failed: HTTP ${res.status} from ${new URL(url).host}`);
+ const declared = Number(res.headers.get('content-length') ?? 0);
+ if (declared > LIMITS.downloadBytes) throw new Error(`Package is too large (${Math.round(declared / 1048576)} MB, limit ${LIMITS.downloadBytes / 1048576} MB).`);
+ const hash = createHash('sha256');
+ const chunks: Buffer[] = [];
+ let total = 0;
+ let lastReport = 0;
+ const reader = res.body.getReader();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > LIMITS.downloadBytes) {
+ ac.abort();
+ throw new Error(`Package is too large (over ${LIMITS.downloadBytes / 1048576} MB).`);
+ }
+ hash.update(value);
+ chunks.push(Buffer.from(value));
+ if (onProgress && total - lastReport > 2 * 1048576) {
+ lastReport = total;
+ onProgress(`Downloaded ${(total / 1048576).toFixed(1)} MB`);
+ }
+ }
+ writeFileSync(dest, Buffer.concat(chunks));
+ return hash.digest('hex');
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export async function sha256File(path: string): Promise<string> {
+ const hash = createHash('sha256');
+ await new Promise<void>((res, rej) => {
+ createReadStream(path).on('data', (c) => hash.update(c)).on('end', () => res()).on('error', rej);
+ });
+ return hash.digest('hex');
+}
+
+async function githubReleaseAsset(repo: string, tag?: string): Promise<string> {
+ const api = `https://api.github.com/repos/${repo}/releases/${tag ? `tags/${encodeURIComponent(tag)}` : 'latest'}`;
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(), 20_000);
+ try {
+ const res = await guardedFetch(api, ac.signal, { accept: 'application/vnd.github+json', 'user-agent': 'mercury-plugin-installer' });
+ if (!res.ok) throw new Error(`GitHub release not found for ${repo}${tag ? `@${tag}` : ''} (HTTP ${res.status}).`);
+ const rel = (await res.json()) as { assets?: { name: string; browser_download_url: string }[] };
+ const assets = rel.assets ?? [];
+ const platform = currentPlatform();
+ const pick = assets.find((a) => a.name === `mercury-plugin-${platform}.tgz`) ?? assets.find((a) => a.name === 'mercury-plugin.tgz');
+ if (!pick) throw new Error(`The ${repo} release has no "mercury-plugin.tgz" or "mercury-plugin-${platform}.tgz" asset.`);
+ return pick.browser_download_url;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+// ── unpack and check ────────────────────────────────────────────────────
+
+async function extractTgz(archive: string, into: string): Promise<void> {
+ mkdirSync(into, { recursive: true });
+ // System tar (bsdtar on macOS/Windows, GNU tar on Linux): both refuse
+ // absolute paths and ".." members by default. We re-check every entry below.
+ try {
+ await execFileAsync('tar', ['-xzf', archive, '-C', into], { timeout: 120_000, windowsHide: true, maxBuffer: 1024 * 1024 });
+ } catch (err) {
+ throw new Error(`Couldn't unpack the plugin archive: ${(err as Error).message.split('\n')[0]}`);
+ }
+}
+
+/**
+ * Walk the unpacked tree and reject anything unsafe: symlinks, hard-linked
+ * or special files, paths escaping the folder, and size/file-count bombs.
+ */
+export function checkTree(root: string): { files: number; bytes: number } {
+ const realRoot = realpathSync(root);
+ let files = 0;
+ let bytes = 0;
+ const walk = (dir: string) => {
+ for (const name of readdirSync(dir)) {
+ const full = join(dir, name);
+ const st = lstatSync(full);
+ if (st.isSymbolicLink()) throw new Error(`Plugin package contains a symbolic link (${relative(root, full)}); refusing to install.`);
+ if (!st.isDirectory() && !st.isFile()) throw new Error(`Plugin package contains a special file (${relative(root, full)}).`);
+ const real = realpathSync(full);
+ if (real !== realRoot && !real.startsWith(realRoot + sep)) throw new Error(`Plugin package path escapes its folder (${relative(root, full)}).`);
+ if (st.isDirectory()) {
+ walk(full);
+ continue;
+ }
+ if (st.nlink > 1) throw new Error(`Plugin package contains a hard link (${relative(root, full)}).`);
+ files += 1;
+ bytes += st.size;
+ if (files > LIMITS.files) throw new Error(`Plugin package has too many files (limit ${LIMITS.files}).`);
+ if (bytes > LIMITS.unpackedBytes) throw new Error(`Plugin package is too large unpacked (limit ${LIMITS.unpackedBytes / 1048576} MB).`);
+ }
+ };
+ walk(root);
+ return { files, bytes };
+}
+
+/** npm-pack style archives put everything under one folder; find the manifest. */
+function findPackageRoot(unpacked: string): string {
+ if (existsSync(join(unpacked, 'mercury-plugin.json'))) return unpacked;
+ const entries = readdirSync(unpacked).filter((n) => !n.startsWith('.'));
+ if (entries.length === 1 && lstatSync(join(unpacked, entries[0])).isDirectory() && existsSync(join(unpacked, entries[0], 'mercury-plugin.json'))) {
+ return join(unpacked, entries[0]);
+ }
+ throw new Error('No mercury-plugin.json found at the top of the plugin package.');
+}
+
+/** Parse and validate a manifest, with readable errors. */
+export function loadManifest(dir: string): PluginManifest {
+ const path = join(dir, 'mercury-plugin.json');
+ let raw: unknown;
+ try {
+ raw = JSON.parse(readFileSync(path, 'utf8'));
+ } catch (err) {
+ throw new Error(`mercury-plugin.json is not valid JSON: ${(err as Error).message}`);
+ }
+ const parsed = manifestSchema.safeParse(raw);
+ if (!parsed.success) {
+ const first = parsed.error.issues.slice(0, 4).map((i) => `${i.path.join('.') || 'manifest'}: ${i.message}`).join('; ');
+ throw new Error(`Invalid mercury-plugin.json: ${first}`);
+ }
+ return parsed.data;
+}
+
+/** Everything that must hold before a package can be installed or started. */
+export async function verifyPackage(dir: string, manifest: PluginManifest): Promise<void> {
+ const why = incompatibility(manifest);
+ if (why) throw new Error(`${manifest.name} ${manifest.version} can't run here: ${why}.`);
+ const inside = (p: string) => {
+ const full = resolve(dir, p);
+ if (full !== dir && !full.startsWith(dir + sep)) throw new Error(`Manifest path escapes the plugin folder: ${p}`);
+ return full;
+ };
+ if (manifest.kind === 'in-process') {
+ const entry = inside(manifest.entry!);
+ if (!existsSync(entry) || !statSync(entry).isFile()) throw new Error(`Entry module "${manifest.entry}" is missing from the package.`);
+ if (!/\.(m?js)$/.test(entry)) throw new Error('The entry module must be a bundled .js or .mjs file.');
+ } else {
+ const spec = manifest.server!.platforms?.[currentPlatform()] ?? manifest.server!;
+ if (spec.command !== 'node') {
+ const cmd = inside(spec.command);
+ if (!existsSync(cmd)) throw new Error(`Server program "${spec.command}" is missing for ${currentPlatform()}.`);
+ if (process.platform !== 'win32') chmodSync(cmd, 0o755);
+ } else if (spec.args[0]) {
+ const script = inside(spec.args[0]);
+ if (!existsSync(script)) throw new Error(`Server script "${spec.args[0]}" is missing from the package.`);
+ }
+ }
+ for (const [rel, expected] of Object.entries(manifest.checksums ?? {})) {
+ const file = inside(rel);
+ if (!existsSync(file)) throw new Error(`File "${rel}" listed in checksums is missing.`);
+ const actual = await sha256File(file);
+ if (actual !== expected) throw new Error(`Checksum mismatch for ${rel}: the file was modified or corrupted.`);
+ }
+}
+
+// ── install ────────────────────────────────────────────────────────────
+
+function newStaging(): string {
+ const dir = join(stagingRoot(), `${Date.now()}-${randomBytes(4).toString('hex')}`);
+ mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+/** Remove leftovers from interrupted installs. Safe to call any time. */
+export function cleanStaging(): void {
+ try { rmSync(stagingRoot(), { recursive: true, force: true }); } catch { /* best effort */ }
+}
+
+export async function installPackage(source: InstallSource, opts: InstallOptions = {}): Promise<InstallResult> {
+ return withLock(async () => {
+ const progress = opts.onProgress ?? (() => {});
+ const staging = newStaging();
+ try {
+ let unpacked: string;
+ let verified = false;
+ let sourceRef: PluginStateEntry['source'];
+
+ if (source.type === 'path') {
+ if (!existsSync(source.path)) throw new Error(`No such file or folder: ${source.path}`);
+ sourceRef = { type: 'path', ref: source.path };
+ if (statSync(source.path).isDirectory()) {
+ progress('Copying plugin folder');
+ unpacked = join(staging, 'pkg');
+ cpSync(source.path, unpacked, {
+ recursive: true,
+ verbatimSymlinks: true,
+ // Skip VCS metadata; keep node_modules (out-of-process plugins may ship dependencies).
+ filter: (src) => {
+ const rel = relative(source.path, src);
+ return rel === '' || !/(^|[\\/])\.git([\\/]|$)/.test(rel);
+ },
+ });
+ } else {
+ progress('Unpacking archive');
+ unpacked = join(staging, 'pkg');
+ await extractTgz(source.path, unpacked);
+ }
+ } else {
+ let url: string;
+ let expected: string | undefined;
+ if (source.type === 'catalog') {
+ const art = source.entry.artifacts?.[currentPlatform()] ?? source.entry.artifact;
+ if (!art) throw new Error(`${source.entry.name} has no build for ${currentPlatform()}.`);
+ url = art.url;
+ expected = art.sha256;
+ sourceRef = { type: 'catalog', ref: source.entry.id };
+ } else if (source.type === 'github') {
+ progress(`Looking up the ${source.repo} release`);
+ url = await githubReleaseAsset(source.repo, source.tag);
+ expected = opts.sha256;
+ sourceRef = { type: 'github', ref: `${source.repo}${source.tag ? `@${source.tag}` : ''}` };
+ } else {
+ url = source.url;
+ expected = opts.sha256;
+ sourceRef = { type: 'url', ref: source.url };
+ }
+ progress(`Downloading from ${new URL(url).host}`);
+ const archive = join(staging, 'package.tgz');
+ const actual = await download(url, archive, progress);
+ if (expected) {
+ if (actual !== expected.toLowerCase()) throw new Error('Checksum mismatch: the download does not match the published SHA-256. Nothing was installed.');
+ verified = source.type === 'catalog';
+ }
+ progress('Unpacking');
+ unpacked = join(staging, 'pkg');
+ await extractTgz(archive, unpacked);
+ }
+
+ progress('Checking the package');
+ checkTree(unpacked);
+ const root = findPackageRoot(unpacked);
+ const manifest = loadManifest(root);
+ if (source.type === 'catalog') {
+ if (manifest.id !== source.entry.id) throw new Error(`Package id "${manifest.id}" doesn't match the catalog entry "${source.entry.id}".`);
+ if (manifest.version !== source.entry.version) throw new Error(`Package version ${manifest.version} doesn't match the catalog (${source.entry.version}).`);
+ }
+ if (opts.expectId && manifest.id !== opts.expectId) throw new Error(`This package is "${manifest.id}", not "${opts.expectId}".`);
+ await verifyPackage(root, manifest);
+
+ const state = readState();
+ const existing = state.plugins[manifest.id];
+ if (existing && existing.version === manifest.version && !opts.force && existsSync(pluginVersionDir(manifest.id, manifest.version))) {
+ return { id: manifest.id, version: manifest.version, verified: existing.verified, manifest, unchanged: true };
+ }
+
+ progress('Installing');
+ const versionsDir = join(pluginDir(manifest.id), 'versions');
+ mkdirSync(versionsDir, { recursive: true });
+ mkdirSync(join(pluginDir(manifest.id), 'data'), { recursive: true });
+ const target = pluginVersionDir(manifest.id, manifest.version);
+ let trash: string | null = null;
+ if (existsSync(target)) {
+ trash = join(staging, 'replaced');
+ renameSync(target, trash);
+ }
+ try {
+ renameSync(root, target);
+ } catch (err) {
+ if (trash) renameSync(trash, target);
+ throw err;
+ }
+
+ const now = new Date().toISOString();
+ const previousVersion = existing && existing.version !== manifest.version ? existing.version : existing?.previousVersion;
+ state.plugins[manifest.id] = {
+ version: manifest.version,
+ previousVersion,
+ // A fresh install starts disabled; updates keep the owner's choice.
+ enabled: existing?.enabled ?? false,
+ kind: manifest.kind,
+ source: sourceRef,
+ verified,
+ installedAt: existing?.installedAt ?? now,
+ updatedAt: now,
+ // Any disable reason from the old version doesn't carry over, except the owner's.
+ disabled: existing?.disabled?.code === 'user' ? existing.disabled : undefined,
+ };
+ if (state.plugins[manifest.id].enabled) state.boot.lastChange = { id: manifest.id, at: now };
+ writeState(state);
+ pruneVersions(manifest.id, [manifest.version, previousVersion].filter(Boolean) as string[]);
+ logger.info({ plugin: manifest.id, version: manifest.version, previousVersion, verified, source: sourceRef.type }, 'Plugin installed');
+ return { id: manifest.id, version: manifest.version, previousVersion, verified, manifest, unchanged: false };
+ } finally {
+ try { rmSync(staging, { recursive: true, force: true }); } catch { /* best effort */ }
+ }
+ });
+}
+
+/** Keep only the listed versions on disk (current and one previous). */
+function pruneVersions(id: string, keep: string[]): void {
+ const dir = join(pluginDir(id), 'versions');
+ if (!existsSync(dir)) return;
+ for (const v of readdirSync(dir)) {
+ if (!keep.includes(v)) {
+ try { rmSync(join(dir, v), { recursive: true, force: true }); } catch (err) { logger.warn({ err, plugin: id, version: v }, 'Could not prune old plugin version'); }
+ }
+ }
+}
+
+/** Switch back to the previous version, if it's still on disk. */
+export async function rollbackPackage(id: string): Promise<{ from: string; to: string }> {
+ return withLock(async () => {
+ const state = readState();
+ const entry = state.plugins[id];
+ if (!entry) throw new Error(`Plugin "${id}" is not installed.`);
+ const prev = entry.previousVersion;
+ if (!prev || !existsSync(pluginVersionDir(id, prev))) throw new Error(`No previous version of "${id}" to roll back to.`);
+ const manifest = loadManifest(pluginVersionDir(id, prev));
+ await verifyPackage(pluginVersionDir(id, prev), manifest);
+ const from = entry.version;
+ entry.version = prev;
+ entry.previousVersion = from;
+ entry.kind = manifest.kind;
+ entry.updatedAt = new Date().toISOString();
+ if (entry.disabled && entry.disabled.code !== 'user') entry.disabled = undefined;
+ if (entry.enabled) state.boot.lastChange = { id, at: entry.updatedAt };
+ writeState(state);
+ return { from, to: prev };
+ });
+}
+
+/** Remove a plugin. Its data and settings are kept unless `purge` is set. */
+export async function uninstallPackage(id: string, purge = false): Promise<{ removedData: boolean }> {
+ return withLock(async () => {
+ const state = readState();
+ const had = !!state.plugins[id];
+ delete state.plugins[id];
+ if (state.boot.lastChange?.id === id) state.boot.lastChange = undefined;
+ writeState(state);
+ const dir = pluginDir(id);
+ if (purge) {
+ if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
+ } else if (existsSync(join(dir, 'versions'))) {
+ rmSync(join(dir, 'versions'), { recursive: true, force: true });
+ }
+ if (!had && !existsSync(dir)) throw new Error(`Plugin "${id}" is not installed.`);
+ logger.info({ plugin: id, purge }, 'Plugin uninstalled');
+ return { removedData: purge };
+ });
+}
+
+/** The manifest of the installed (current) version, or null if missing or broken. */
+export function installedManifest(id: string, version: string): PluginManifest | null {
+ try {
+ return loadManifest(pluginVersionDir(id, version));
+ } catch {
+ return null;
+ }
+}
+
+export function packageSize(id: string, version: string): number {
+ let bytes = 0;
+ const walk = (d: string) => {
+ for (const n of readdirSync(d)) {
+ const f = join(d, n);
+ const st = lstatSync(f);
+ if (st.isDirectory()) walk(f);
+ else bytes += st.size;
+ }
+ };
+ try { walk(pluginVersionDir(id, version)); } catch { /* missing */ }
+ return bytes;
+}
+
diff --git a/src/plugins/integration.test.ts b/src/plugins/integration.test.ts
new file mode 100644
index 00000000..af50774f
--- /dev/null
+++ b/src/plugins/integration.test.ts
@@ -0,0 +1,79 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { PermissionManager } from '../capabilities/permissions.js';
+import { filterBotTools } from '../bots/registry-factory.js';
+import type { BotManifest } from '../bots/types.js';
+import { isPluginToolName, pluginToolAllowed } from './tool-bridge.js';
+import { tempHome } from './test-fixtures.js';
+
+let env: ReturnType<typeof tempHome>;
+beforeEach(() => { env = tempHome(); });
+afterEach(() => env.restore());
+
+const tools = { read_file: {}, run_command: {}, 'weather__forecast': {}, 'weather__alerts': {}, 'notes__write': {} };
+const manifest = { id: 'b', name: 'B' } as unknown as BotManifest;
+
+describe('bots never see plugin tools unless explicitly allowed', () => {
+ it('deny-only gate (the default) hides every plugin tool', () => {
+ const out = filterBotTools(tools, manifest, { tools: { deny: ['run_command'] } } as never);
+ expect(Object.keys(out)).toEqual(['read_file']);
+ });
+ it('an exact allow entry exposes that tool only', () => {
+ const out = filterBotTools(tools, manifest, { tools: { allow: ['read_file', 'weather__forecast'] } } as never);
+ expect(Object.keys(out)).toEqual(['read_file', 'weather__forecast']);
+ });
+ it('"<plugin>__*" exposes one plugin\'s tools, not others', () => {
+ const out = filterBotTools(tools, manifest, { tools: { allow: ['weather__*'] } } as never);
+ expect(Object.keys(out)).toEqual(['weather__forecast', 'weather__alerts']);
+ });
+ it('deny still wins over allow', () => {
+ const out = filterBotTools(tools, manifest, { tools: { allow: ['weather__*'], deny: ['weather__alerts'] } } as never);
+ expect(Object.keys(out)).toEqual(['weather__forecast']);
+ });
+ it('name helpers', () => {
+ expect(isPluginToolName('weather__forecast')).toBe(true);
+ expect(isPluginToolName('read_file')).toBe(false);
+ expect(isPluginToolName('Weather__x')).toBe(false);
+ expect(pluginToolAllowed('notes__write', ['weather__*'])).toBe(false);
+ });
+});
+
+describe('approvePluginTool', () => {
+ it('fail-closed (bots): runs without asking (the bot gate already allowed it)', async () => {
+ const pm = new PermissionManager();
+ pm.setFailClosed(true);
+ pm.onAsk(async () => { throw new Error('bots must never be asked'); });
+ expect(await pm.approvePluginTool('weather__forecast', 'x')).toBe(true);
+ });
+ it('internal turns approve only under allow-all', async () => {
+ const pm = new PermissionManager();
+ pm.setCurrentContext('internal', 'sched-1');
+ expect(await pm.approvePluginTool('notes__write', 'x')).toBe(false);
+ pm.setAutoApproveAll(true);
+ expect(await pm.approvePluginTool('notes__write', 'x')).toBe(true);
+ });
+ it('session Allow All approves locally but never for web requests', async () => {
+ const pm = new PermissionManager();
+ pm.setCurrentContext('cli', 'local');
+ pm.setAutoApproveAll(true);
+ expect(await pm.approvePluginTool('notes__write', 'x')).toBe(true);
+ pm.setCurrentContext('web', 'session-9');
+ pm.setAutoApproveAll(true);
+ pm.onAsk(async () => 'no');
+ expect(await pm.approvePluginTool('notes__write', 'x')).toBe(false);
+ });
+ it('"always" is remembered per channel, not across channels', async () => {
+ const pm = new PermissionManager();
+ pm.setCurrentContext('telegram', 'chat-1');
+ pm.onAsk(async () => 'always');
+ expect(await pm.approvePluginTool('notes__write', 'x')).toBe(true);
+ pm.onAsk(async () => 'no');
+ expect(await pm.approvePluginTool('notes__write', 'x')).toBe(true);
+ pm.setCurrentContext('telegram', 'chat-2');
+ expect(await pm.approvePluginTool('notes__write', 'x')).toBe(false);
+ });
+ it('no one to ask means no', async () => {
+ const pm = new PermissionManager();
+ pm.setCurrentContext('cli', 'local');
+ expect(await pm.approvePluginTool('notes__write', 'x')).toBe(false);
+ });
+});
diff --git a/src/plugins/lifecycle.test.ts b/src/plugins/lifecycle.test.ts
new file mode 100644
index 00000000..660fb2e0
--- /dev/null
+++ b/src/plugins/lifecycle.test.ts
@@ -0,0 +1,147 @@
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { PluginManager, resetPluginManager } from './manager.js';
+import { installedManifest } from './installer.js';
+import { pluginDir, pluginSettingsPath, readState, resolvedSettings } from './store.js';
+import { listLiveTools, resetToolBridge } from './tool-bridge.js';
+import { runConformance, unresolvableImports } from './conformance.js';
+import { manifestSchema } from './types.js';
+import pluginRoutes from '../web/api/plugins.js';
+import { inProcessPlugin, outOfProcessPlugin, tempHome } from './test-fixtures.js';
+
+let env: ReturnType<typeof tempHome>;
+let src: string;
+let mgr: PluginManager;
+
+beforeEach(() => {
+ env = tempHome();
+ src = join(env.home, 'src');
+ mkdirSync(src, { recursive: true });
+ resetToolBridge();
+ mgr = new PluginManager({ safeMode: false, notify: () => {} });
+});
+
+afterEach(async () => {
+ await mgr.shutdown();
+ resetToolBridge();
+ resetPluginManager();
+ env.restore();
+});
+
+const v1Settings = {
+ settings: {
+ version: 1,
+ fields: { units: { type: 'enum', options: ['celsius', 'fahrenheit'], default: 'celsius' }, city: { type: 'string', default: '' } },
+ },
+};
+const v2Settings = {
+ settings: {
+ version: 2,
+ fields: { unit: { type: 'enum', options: ['c', 'f'], default: 'c' }, city: { type: 'string', default: '' } },
+ migrations: [{ to: 2, rename: { units: 'unit' }, mapValues: { unit: { celsius: 'c', fahrenheit: 'f' } } }],
+ },
+};
+
+describe('settings migrations', () => {
+ it('upgrades saved settings on update and restores the old ones on rollback', async () => {
+ await mgr.install(inProcessPlugin(src, { id: 'weather', version: '1.0.0', manifest: v1Settings }));
+ await mgr.setSetting('weather', 'units', 'fahrenheit');
+ await mgr.setSetting('weather', 'city', 'Lahore');
+
+ await mgr.install(inProcessPlugin(src, { id: 'weather', version: '2.0.0', manifest: v2Settings }));
+ expect(readState().plugins.weather.version).toBe('2.0.0');
+ const saved = JSON.parse(readFileSync(pluginSettingsPath('weather'), 'utf8'));
+ expect(saved).toEqual({ settingsVersion: 2, values: { unit: 'f', city: 'Lahore' } });
+ expect(resolvedSettings(installedManifest('weather', '2.0.0')!)).toEqual({ unit: 'f', city: 'Lahore' });
+ expect(existsSync(join(pluginDir('weather'), 'settings.v1.json'))).toBe(true);
+
+ await mgr.rollback('weather');
+ expect(readState().plugins.weather.version).toBe('1.0.0');
+ expect(resolvedSettings(installedManifest('weather', '1.0.0')!)).toEqual({ units: 'fahrenheit', city: 'Lahore' });
+ });
+
+ it('a corrupt settings file never stops the plugin: it starts on defaults', async () => {
+ await mgr.install(inProcessPlugin(src, { id: 'weather', manifest: v1Settings }));
+ writeFileSync(pluginSettingsPath('weather'), '{not json');
+ await mgr.disable('weather');
+ await mgr.enable('weather');
+ expect(listLiveTools().some((t) => t.pluginId === 'weather')).toBe(true);
+ expect(resolvedSettings(installedManifest('weather', '1.0.0')!)).toEqual({ units: 'celsius', city: '' });
+ });
+
+ it('rejects migrations that skip past the settings version or go backwards', () => {
+ const base = JSON.parse(readFileSync(join(inProcessPlugin(src, { id: 'bad-mig' }), 'mercury-plugin.json'), 'utf8'));
+ const bad = { ...base, settings: { version: 2, fields: {}, migrations: [{ to: 3 }] } };
+ expect(manifestSchema.safeParse(bad).success).toBe(false);
+ const backwards = { ...base, settings: { version: 3, fields: {}, migrations: [{ to: 3 }, { to: 2 }] } };
+ expect(manifestSchema.safeParse(backwards).success).toBe(false);
+ });
+});
+
+describe('conformance kit', () => {
+ it('passes a well-formed in-process plugin, including stop and restart', async () => {
+ const report = await runConformance(inProcessPlugin(src, { id: 'good-one', tools: [{ name: 'echo', description: 'Echo the input back to the caller.' }] }));
+ expect(report.checks.filter((c) => !c.ok)).toEqual([]);
+ expect(report.checks.map((c) => c.name)).toEqual(expect.arrayContaining(['manifest', 'self-contained bundle', 'start', 'tools', 'start: stop', 'restart (hot plug)', 'restart (hot plug): stop']));
+ expect(listLiveTools()).toEqual([]);
+ });
+
+ it('passes an out-of-process MCP plugin', async () => {
+ const report = await runConformance(outOfProcessPlugin(src, { id: 'mcp-ok' }));
+ expect(report.checks.filter((c) => !c.ok)).toEqual([]);
+ });
+
+ it('flags a plugin that imports packages instead of bundling them', async () => {
+ const dir = inProcessPlugin(src, {
+ id: 'unbundled',
+ code: `import { z } from 'zod';\nexport async function activate(ctx) {}`,
+ });
+ const report = await runConformance(dir);
+ expect(report.ok).toBe(false);
+ expect(report.checks.find((c) => c.name === 'self-contained bundle')?.ok).toBe(false);
+ });
+
+ it('flags a declared tool the plugin never registers', async () => {
+ const dir = inProcessPlugin(src, { id: 'liar', code: 'export async function activate() {}' });
+ const report = await runConformance(dir);
+ expect(report.checks.find((c) => c.name === 'tools')).toMatchObject({ ok: false });
+ });
+
+ it('import scanner allows builtins and relative files only', () => {
+ expect(unresolvableImports(`import fs from 'node:fs'; import path from "path"; import x from './x.js'; const y = await import('../y.mjs');`)).toEqual([]);
+ expect(unresolvableImports(`import a from 'lodash'; export { b } from '@scope/pkg'; require('left-pad')`)).toEqual(['lodash', '@scope/pkg', 'left-pad']);
+ });
+});
+
+describe('web API', () => {
+ const loopback = { incoming: { socket: { remoteAddress: '127.0.0.1' } } };
+ const lan = { incoming: { socket: { remoteAddress: '192.168.1.20' } } };
+ const post = (body: unknown) => ({ method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' } });
+
+ it('only accepts changes from this machine', async () => {
+ const dir = inProcessPlugin(src, { id: 'web-test' });
+ const denied = await pluginRoutes.request('/api/plugins/install', post({ source: dir }), lan);
+ expect(denied.status).toBe(403);
+ expect(readState().plugins['web-test']).toBeUndefined();
+
+ const ok = await pluginRoutes.request('/api/plugins/install', post({ source: dir }), loopback);
+ expect(ok.status).toBe(200);
+ expect(((await ok.json()) as { id: string }).id).toBe('web-test');
+
+ const list = await pluginRoutes.request('/api/plugins', {}, lan);
+ expect(list.status).toBe(200);
+ expect(((await list.json()) as { items: Array<{ id: string }> }).items.map((i: { id: string }) => i.id)).toContain('web-test');
+
+ expect((await pluginRoutes.request('/api/plugins/web-test/disable', post({}), lan)).status).toBe(403);
+ expect((await pluginRoutes.request('/api/plugins/web-test', { method: 'DELETE' }, lan)).status).toBe(403);
+ expect((await pluginRoutes.request('/api/plugins/web-test', { method: 'DELETE' }, loopback)).status).toBe(200);
+ expect(readState().plugins['web-test']).toBeUndefined();
+ });
+
+ it('returns 404 for an unknown plugin and 400 for a bad source', async () => {
+ expect((await pluginRoutes.request('/api/plugins/nope-nope/enable', post({}), loopback)).status).toBe(404);
+ expect((await pluginRoutes.request('/api/plugins/install', post({ source: '' }), loopback)).status).toBe(400);
+ expect((await pluginRoutes.request('/api/plugins/install', post({ source: 'http://insecure.example/p.tgz' }), loopback)).status).toBe(400);
+ });
+});
diff --git a/src/plugins/manager.test.ts b/src/plugins/manager.test.ts
new file mode 100644
index 00000000..09110014
--- /dev/null
+++ b/src/plugins/manager.test.ts
@@ -0,0 +1,320 @@
+import { mkdirSync } 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 { CIRCUIT_BREAKER_FAILURES, PluginManager } from './manager.js';
+import { IN_PROCESS_TIMEOUTS } from './runtime/in-process.js';
+import { OUT_OF_PROCESS } from './runtime/out-of-process.js';
+import { readState, updateState, pluginDir } from './store.js';
+import { getPluginCommand, getPluginTools, listLiveTools, resetToolBridge } from './tool-bridge.js';
+import { inProcessPlugin, outOfProcessPlugin, sleep, tempHome, waitFor } from './test-fixtures.js';
+
+let env: ReturnType<typeof tempHome>;
+let src: string;
+let mgr: PluginManager;
+let notices: string[];
+const savedTimeouts = { ...IN_PROCESS_TIMEOUTS };
+const savedOop = { ...OUT_OF_PROCESS };
+
+beforeEach(() => {
+ env = tempHome();
+ src = join(env.home, 'src');
+ mkdirSync(src, { recursive: true });
+ resetToolBridge();
+ notices = [];
+ mgr = new PluginManager({ safeMode: false, notify: (m) => { notices.push(m); } });
+});
+
+afterEach(async () => {
+ await mgr.shutdown();
+ Object.assign(IN_PROCESS_TIMEOUTS, savedTimeouts);
+ Object.assign(OUT_OF_PROCESS, savedOop);
+ resetToolBridge();
+ env.restore();
+});
+
+async function call(tools: Record<string, Tool>, name: string, args: Record<string, unknown> = {}): Promise<unknown> {
+ const t = tools[name] as Tool & { execute: (a: unknown, o: unknown) => Promise<unknown> };
+ expect(t, `tool ${name}`).toBeDefined();
+ return t.execute(args, { toolCallId: 't1', messages: [] });
+}
+
+describe('in-process plugins', () => {
+ it('install → enabled → tools are live, namespaced and callable', async () => {
+ await mgr.install(inProcessPlugin(src));
+ const tools = getPluginTools(new PermissionManager());
+ expect(Object.keys(tools)).toEqual(['echo-tools__echo']);
+ expect(await call(tools, 'echo-tools__echo', { text: 'hi' })).toBe('echo: hi');
+ const { items } = await mgr.list();
+ expect(items.find((i) => i.id === 'echo-tools')).toMatchObject({ status: 'enabled', running: true, enabled: true });
+ });
+
+ it('disable removes the tools; enable brings them back with a fresh instance', async () => {
+ await mgr.install(inProcessPlugin(src));
+ await mgr.disable('echo-tools');
+ expect(listLiveTools()).toHaveLength(0);
+ expect(readState().plugins['echo-tools']).toMatchObject({ enabled: false, disabled: { code: 'user' } });
+ await mgr.enable('echo-tools');
+ expect(listLiveTools().map((t) => t.name)).toEqual(['echo']);
+ });
+
+ it('activate() that throws disables the plugin with the reason and keeps Mercury running', async () => {
+ const dir = inProcessPlugin(src, { id: 'throws', code: 'export async function activate() { throw new Error("boom in activate"); }' });
+ await expect(mgr.install(dir)).rejects.toThrow(/boom in activate/);
+ expect(readState().plugins.throws).toMatchObject({ enabled: false, disabled: { code: 'activation' } });
+ expect(notices.join('\n')).toMatch(/throws.*boom in activate/);
+ expect(listLiveTools()).toHaveLength(0);
+ });
+
+ it('activate() that hangs times out', async () => {
+ IN_PROCESS_TIMEOUTS.activate = 200;
+ const dir = inProcessPlugin(src, { id: 'hangs', code: 'export function activate() { return new Promise(() => {}); }' });
+ await expect(mgr.install(dir)).rejects.toThrow(/activate\(\) timed out/);
+ expect(readState().plugins.hangs.disabled?.code).toBe('activation');
+ });
+
+ it('a module without activate() is rejected', async () => {
+ const dir = inProcessPlugin(src, { id: 'noact', code: 'export const x = 1;' });
+ await expect(mgr.install(dir)).rejects.toThrow(/does not export an activate/);
+ });
+
+ it('registering an undeclared tool fails activation', async () => {
+ const dir = inProcessPlugin(src, {
+ id: 'sneaky-tool',
+ code: `export function activate(ctx) { ctx.tools.register({ name: 'rm_everything', inputSchema: { type: 'object' }, execute: () => 'x' }); }`,
+ });
+ await expect(mgr.install(dir)).rejects.toThrow(/"rm_everything" is not declared/);
+ });
+
+ it('a plugin importing a package fails with the "bundle it" explanation', async () => {
+ const dir = inProcessPlugin(src, { id: 'needs-dep', code: `import x from 'some-package-that-is-not-there'; export function activate() {}` });
+ await expect(mgr.install(dir)).rejects.toThrow(/Couldn't start/);
+ });
+
+ it(`${CIRCUIT_BREAKER_FAILURES} tool failures in a row disable the plugin`, async () => {
+ const dir = inProcessPlugin(src, {
+ id: 'flaky',
+ tools: [{ name: 'fail', readOnly: true }],
+ code: `export function activate(ctx) { ctx.tools.register({ name: 'fail', inputSchema: { type: 'object' }, execute: () => { throw new Error('nope'); } }); }`,
+ });
+ await mgr.install(dir);
+ const tools = getPluginTools(new PermissionManager());
+ for (let i = 0; i < CIRCUIT_BREAKER_FAILURES; i++) {
+ expect(await call(tools, 'flaky__fail')).toMatch(/Error from plugin tool flaky__fail: nope/);
+ }
+ await waitFor(() => readState().plugins.flaky?.enabled === false);
+ expect(readState().plugins.flaky.disabled).toMatchObject({ code: 'errors' });
+ expect(listLiveTools()).toHaveLength(0);
+ });
+
+ it('a slow tool times out and the model gets an error, not a hang', async () => {
+ const dir = inProcessPlugin(src, {
+ id: 'slow',
+ tools: [{ name: 'wait', readOnly: true, timeoutMs: 1000 }],
+ code: `export function activate(ctx) { ctx.tools.register({ name: 'wait', inputSchema: { type: 'object' }, execute: () => new Promise(() => {}) }); }`,
+ });
+ await mgr.install(dir);
+ const started = Date.now();
+ expect(await call(getPluginTools(new PermissionManager()), 'slow__wait')).toMatch(/timed out after 1s/);
+ expect(Date.now() - started).toBeLessThan(3000);
+ });
+
+ it('tracked timers stop when the plugin is disabled, and errors inside them are contained', async () => {
+ const dir = inProcessPlugin(src, {
+ id: 'ticker',
+ tools: [{ name: 'count', readOnly: true }],
+ code: `let n = 0; export function activate(ctx) {
+ ctx.timers.setInterval(() => { n++; if (n === 2) throw new Error('tick error'); }, 1000);
+ ctx.tools.register({ name: 'count', inputSchema: { type: 'object' }, execute: () => String(n) });
+ }`,
+ });
+ await mgr.install(dir);
+ await sleep(2300);
+ const before = Number(await call(getPluginTools(new PermissionManager()), 'ticker__count'));
+ expect(before).toBeGreaterThanOrEqual(2);
+ expect(readState().plugins.ticker.enabled).toBe(true);
+ await mgr.disable('ticker');
+ await sleep(1200);
+ expect(listLiveTools()).toHaveLength(0);
+ });
+
+ it('ctx.fetch refuses hosts the manifest did not declare', async () => {
+ const dir = inProcessPlugin(src, {
+ id: 'fetcher',
+ tools: [{ name: 'get', readOnly: true }],
+ network: ['api.example.com'],
+ code: `export function activate(ctx) { ctx.tools.register({ name: 'get', inputSchema: { type: 'object' }, execute: async (a) => { await ctx.fetch(a.url); return 'fetched'; } }); }`,
+ });
+ await mgr.install(dir);
+ const out = await call(getPluginTools(new PermissionManager()), 'fetcher__get', { url: 'https://evil.example.net/x' });
+ expect(out).toMatch(/evil\.example\.net is not declared/);
+ });
+
+ it('secrets: only declared names are readable', async () => {
+ process.env.FIXTURE_TOKEN = 'declared-value';
+ process.env.OTHER_SECRET = 'must-not-leak';
+ const dir = inProcessPlugin(src, {
+ id: 'secrets-in',
+ tools: [{ name: 'peek', readOnly: true }],
+ secrets: ['FIXTURE_TOKEN'],
+ code: `export function activate(ctx) { ctx.tools.register({ name: 'peek', inputSchema: { type: 'object' }, execute: () => JSON.stringify({ a: ctx.secrets.get('FIXTURE_TOKEN') ?? null, b: ctx.secrets.get('OTHER_SECRET') ?? null }) }); }`,
+ });
+ await mgr.install(dir);
+ expect(JSON.parse(String(await call(getPluginTools(new PermissionManager()), 'secrets-in__peek')))).toEqual({ a: 'declared-value', b: null });
+ delete process.env.FIXTURE_TOKEN;
+ delete process.env.OTHER_SECRET;
+ });
+
+ it('slash commands register under declared names and reply', async () => {
+ const dir = inProcessPlugin(src, {
+ id: 'greeter',
+ tools: [],
+ commands: [{ name: 'greet', description: 'Say hello' }],
+ code: `export function activate(ctx) { ctx.commands.register({ name: 'greet', run: async (args, io) => { await io.reply('hello ' + args); } }); }`,
+ });
+ await mgr.install(dir);
+ const replies: string[] = [];
+ await getPluginCommand('greet')!.run('world', { reply: async (t) => { replies.push(t); }, signal: new AbortController().signal });
+ expect(replies).toEqual(['hello world']);
+ await mgr.disable('greeter');
+ expect(getPluginCommand('greet')).toBeUndefined();
+ });
+
+ it('an uncaught error from plugin code is attributed and the plugin disabled', async () => {
+ await mgr.install(inProcessPlugin(src, { id: 'crasher' }));
+ const err = new Error('raw timer blew up');
+ err.stack = `Error: raw timer blew up\n at Timeout._onTimeout (${pluginDir('crasher')}/versions/1.0.0/index.mjs:3:11)`;
+ expect(mgr.attributeFault(err)).toBe(true);
+ await waitFor(() => readState().plugins.crasher?.enabled === false);
+ expect(mgr.attributeFault(new Error('not from a plugin'))).toBe(false);
+ });
+
+ it('non-read-only tools ask for approval; "no" means not run', async () => {
+ await mgr.install(inProcessPlugin(src, { id: 'writer', tools: [{ name: 'write_it', readOnly: false }] }));
+ const pm = new PermissionManager();
+ const prompts: string[] = [];
+ pm.onAsk(async (p) => { prompts.push(p); return 'no'; });
+ expect(await call(getPluginTools(pm), 'writer__write_it', { text: 'x' })).toMatch(/was not approved/);
+ expect(prompts[0]).toMatch(/Run plugin tool Fixture writer → write_it with \{"text":"x"\}/);
+ pm.onAsk(async () => 'always');
+ expect(await call(getPluginTools(pm), 'writer__write_it', { text: 'y' })).toBe('write_it: y');
+ pm.onAsk(async () => { throw new Error('should not ask again'); });
+ expect(await call(getPluginTools(pm), 'writer__write_it', { text: 'z' })).toBe('write_it: z');
+ });
+
+ it('plan mode only sees read-only plugin tools', async () => {
+ await mgr.install(inProcessPlugin(src, { id: 'mixed', tools: [{ name: 'look', readOnly: true }, { name: 'change', readOnly: false }] }));
+ expect(Object.keys(getPluginTools(new PermissionManager(), { readOnlyOnly: true }))).toEqual(['mixed__look']);
+ });
+});
+
+describe('boot, safe mode and the boot guard', () => {
+ it('boot starts enabled plugins; shutdown records a clean exit', async () => {
+ await mgr.install(inProcessPlugin(src));
+ await mgr.shutdown();
+ resetToolBridge();
+ const m2 = new PluginManager({ safeMode: false });
+ await m2.boot();
+ expect(listLiveTools().map((t) => t.name)).toEqual(['echo']);
+ expect(readState().boot.inProgress).toBe(true);
+ await m2.shutdown();
+ expect(readState().boot).toMatchObject({ inProgress: false, failedBoots: 0 });
+ });
+
+ it('safe mode loads nothing and refuses to enable', async () => {
+ await mgr.install(inProcessPlugin(src));
+ await mgr.shutdown();
+ resetToolBridge();
+ const safe = new PluginManager({ safeMode: true });
+ await safe.boot();
+ expect(listLiveTools()).toHaveLength(0);
+ await expect(safe.enable('echo-tools')).rejects.toThrow(/safe mode/);
+ expect((await safe.list()).safeMode).toBe(true);
+ });
+
+ it('two failed boots right after a plugin change disable that plugin', async () => {
+ await mgr.install(inProcessPlugin(src));
+ await mgr.shutdown();
+ // Simulate two crashes during boot (no clean shutdown, never reached "healthy").
+ await updateState((s) => { s.boot.inProgress = true; s.boot.failedBoots = 1; });
+ resetToolBridge();
+ const notes: string[] = [];
+ const m2 = new PluginManager({ safeMode: false, notify: (m) => { notes.push(m); } });
+ await m2.boot();
+ expect(readState().plugins['echo-tools']).toMatchObject({ enabled: false, disabled: { code: 'boot-guard' } });
+ expect(listLiveTools()).toHaveLength(0);
+ expect(notes.join()).toMatch(/failed to start twice/);
+ await m2.shutdown();
+ });
+
+ it('a broken installed copy is disabled at start, not loaded', async () => {
+ await mgr.install(inProcessPlugin(src));
+ await mgr.shutdown();
+ const { rmSync } = await import('node:fs');
+ rmSync(join(pluginDir('echo-tools'), 'versions', '1.0.0', 'index.mjs'));
+ resetToolBridge();
+ const m2 = new PluginManager({ safeMode: false });
+ await m2.boot();
+ // The entry file vanished after install: caught by the integrity check before loading.
+ expect(readState().plugins['echo-tools'].disabled).toMatchObject({ code: 'integrity', message: expect.stringMatching(/Entry module "index.mjs" is missing/) });
+ await m2.shutdown();
+ });
+});
+
+describe('out-of-process plugins (MCP over stdio)', () => {
+ it('handshake, tools/list (undeclared tools ignored), tools/call', async () => {
+ await mgr.install(outOfProcessPlugin(src));
+ const tools = getPluginTools(new PermissionManager());
+ expect(Object.keys(tools).sort()).toEqual(['mcp-math__add', 'mcp-math__secret']);
+ expect(await call(tools, 'mcp-math__add', { a: 2, b: 3 })).toBe('5');
+ });
+
+ it('gets only declared secrets in its environment', async () => {
+ process.env.FIXTURE_TOKEN = 'tok';
+ process.env.OTHER_SECRET = 'nope';
+ await mgr.install(outOfProcessPlugin(src));
+ expect(JSON.parse(String(await call(getPluginTools(new PermissionManager()), 'mcp-math__secret')))).toEqual({ declared: 'tok', leaked: null });
+ delete process.env.FIXTURE_TOKEN;
+ delete process.env.OTHER_SECRET;
+ });
+
+ it('a server that never completes the handshake is disabled with a clear reason', async () => {
+ OUT_OF_PROCESS.initTimeoutMs = 500;
+ await expect(mgr.install(outOfProcessPlugin(src, { id: 'silent', mode: 'no-handshake' }))).rejects.toThrow(/initialize timed out/);
+ expect(readState().plugins.silent.disabled?.code).toBe('activation');
+ });
+
+ it('a server that exits at start reports its stderr', async () => {
+ await expect(mgr.install(outOfProcessPlugin(src, { id: 'dies', mode: 'crash-at-start' }))).rejects.toThrow(/boom at start|exited/);
+ });
+
+ it('crashes restart with backoff; too many crashes disable it', async () => {
+ OUT_OF_PROCESS.backoffStartMs = 50;
+ OUT_OF_PROCESS.maxCrashes = 2;
+ await mgr.install(outOfProcessPlugin(src, { id: 'crashy', mode: 'crash-on-call' }));
+ for (let i = 0; i < 3; i++) {
+ await waitFor(() => listLiveTools().some((t) => t.pluginId === 'crashy'), 5000);
+ expect(await call(getPluginTools(new PermissionManager()), 'crashy__add', { a: 1, b: 1 })).toMatch(/Error from plugin tool/);
+ }
+ await waitFor(() => readState().plugins.crashy?.enabled === false && notices.length > 0, 8000);
+ expect(readState().plugins.crashy.disabled?.code).toBe('crashed');
+ expect(notices.join('\n')).toMatch(/crashy.*crashed/);
+ }, 20_000);
+
+ it('a hung call times out, and the server is recycled', async () => {
+ OUT_OF_PROCESS.backoffStartMs = 50;
+ await mgr.install(outOfProcessPlugin(src, { id: 'hangy', mode: 'hang-on-call', tools: [{ name: 'add', description: 'x', readOnly: true, timeoutMs: 1000 }] }));
+ const out = await call(getPluginTools(new PermissionManager()), 'hangy__add', { a: 1, b: 2 });
+ expect(out).toMatch(/timed out/);
+ await waitFor(() => listLiveTools().some((t) => t.pluginId === 'hangy'), 5000);
+ }, 15_000);
+
+ it('disable stops the process and unpublishes its tools', async () => {
+ await mgr.install(outOfProcessPlugin(src));
+ await mgr.disable('mcp-math');
+ expect(listLiveTools()).toHaveLength(0);
+ const { items } = await mgr.list();
+ expect(items.find((i) => i.id === 'mcp-math')).toMatchObject({ status: 'disabled', running: false });
+ });
+});
diff --git a/src/plugins/manager.ts b/src/plugins/manager.ts
new file mode 100644
index 00000000..4cb41b2c
--- /dev/null
+++ b/src/plugins/manager.ts
@@ -0,0 +1,564 @@
+/**
+ * PluginManager: the one place that decides which plugins run.
+ *
+ * Every surface (/plugins in chat, Telegram buttons, the dashboard, the
+ * `mercury plugins` CLI, the HTTP API) goes through this class, so they
+ * always agree. Only the process that owns the runtime (the daemon, or a
+ * standalone foreground runtime) runs plugins (ADR-024).
+ *
+ * Fault handling, in order of escalation:
+ * - a tool call fails → error returned to the model, failure counted
+ * - 5 failures in a row → plugin disabled ("errors"), owner notified
+ * - activation fails → plugin disabled ("activation"), owner notified
+ * - server crashes 6× / 10m→ plugin disabled ("crashed"), owner notified
+ * - uncaught error whose stack is inside a plugin folder → that plugin
+ * disabled; the daemon keeps running instead of exiting
+ * - daemon fails to boot twice right after a plugin change → that plugin
+ * disabled ("boot-guard") on the next start
+ * - `mercury --safe-mode` or MERCURY_PLUGINS=off → no plugins load at all
+ */
+import { existsSync } from 'node:fs';
+import { sep } from 'node:path';
+import semver from 'semver';
+import { logger } from '../utils/logger.js';
+import { findCatalogEntry, getCatalog } from './catalog.js';
+import {
+ cleanStaging, installedManifest, installPackage, packageSize, parseSource, rollbackPackage, uninstallPackage, verifyPackage,
+ type InstallResult,
+} from './installer.js';
+import {
+ incompatibility, mercuryVersion, pluginDataDir, pluginDir, pluginVersionDir, readState, resolvedSettings, updateState, writeSettings, migrateSettings,
+} from './store.js';
+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 type { PluginRuntime } from './runtime/types.js';
+import type { CatalogEntry, DisabledCode, PluginListItem, PluginManifest, PluginsState } from './types.js';
+
+export const CIRCUIT_BREAKER_FAILURES = 5;
+export const BOOT_HEALTHY_AFTER_MS = 60_000;
+const BOOT_GUARD_WINDOW_MS = 24 * 60 * 60 * 1000;
+
+interface Running {
+ runtime: PluginRuntime;
+ manifest: PluginManifest;
+ version: string;
+ startedAt: number;
+ consecutiveFailures: number;
+ lastError?: string;
+}
+
+export interface PluginManagerOptions {
+ safeMode?: boolean;
+ /**
+ * Whether this process runs plugins. Only the process that owns the
+ * runtime does (ADR-024); others change state on disk or forward to it.
+ */
+ runsPlugins?: boolean;
+ /** How to tell the owner something happened (e.g. agent.notifyAllChannels). */
+ notify?: (message: string) => void | Promise<void>;
+}
+
+export type ChangeListener = () => void;
+
+export class PluginManager {
+ private running = new Map<string, Running>();
+ private lastErrors = new Map<string, string>();
+ private starting = new Set<string>();
+ private listeners = new Set<ChangeListener>();
+ private readonly safeMode: boolean;
+ private notifyFn: (message: string) => void | Promise<void>;
+ private reconciling: Promise<void> | null = null;
+ private healthyTimer: ReturnType<typeof setTimeout> | null = null;
+ private booted = false;
+ private runs: boolean;
+
+ constructor(opts: PluginManagerOptions = {}) {
+ this.safeMode = opts.safeMode ?? isSafeModeRequested();
+ this.runs = opts.runsPlugins ?? true;
+ this.notifyFn = opts.notify ?? (() => {});
+ setToolOutcomeSink((pluginId, outcome) => {
+ if (outcome.ok) this.recordSuccess(pluginId);
+ else this.recordFailure(pluginId, outcome.timeout ? `timed out: ${outcome.error}` : outcome.error);
+ });
+ }
+
+ setNotifier(fn: (message: string) => void | Promise<void>): void {
+ this.notifyFn = fn;
+ }
+
+ isSafeMode(): boolean {
+ return this.safeMode;
+ }
+
+ runsPlugins(): boolean {
+ return this.runs;
+ }
+
+ /** Called once by the process that owns the runtime, before boot(). */
+ setRunsPlugins(value: boolean): void {
+ this.runs = value;
+ }
+
+ onChange(listener: ChangeListener): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ private changed(): void {
+ for (const l of this.listeners) {
+ try { l(); } catch { /* listeners never break us */ }
+ }
+ }
+
+ private notify(message: string): void {
+ try {
+ void Promise.resolve(this.notifyFn(message)).catch(() => {});
+ } catch { /* never throw from a notification */ }
+ }
+
+ // ── boot / shutdown ──────────────────────────────────────────────────
+
+ /** Daemon start: crash guard, then start every enabled plugin. Never throws. */
+ async boot(): Promise<void> {
+ if (this.booted || !this.runs) return;
+ this.booted = true;
+ cleanStaging();
+ if (this.safeMode) {
+ logger.warn('Safe mode: plugins are not loaded');
+ return;
+ }
+ try {
+ let guarded: string | undefined;
+ await updateState((s) => {
+ s.boot.failedBoots = s.boot.inProgress ? s.boot.failedBoots + 1 : 0;
+ const change = s.boot.lastChange;
+ const recent = change && Date.now() - Date.parse(change.at) < BOOT_GUARD_WINDOW_MS;
+ if (s.boot.failedBoots >= 2 && change && recent && s.plugins[change.id]?.enabled) {
+ const entry = s.plugins[change.id];
+ entry.enabled = false;
+ entry.disabled = { code: 'boot-guard', message: 'Mercury failed to start twice right after this plugin was enabled or updated.', at: new Date().toISOString() };
+ guarded = change.id;
+ s.boot.failedBoots = 0;
+ s.boot.lastChange = undefined;
+ }
+ s.boot.inProgress = true;
+ });
+ if (guarded) {
+ logger.warn({ plugin: guarded }, 'Boot guard disabled a plugin');
+ this.notify(`⚠️ Plugin "${guarded}" was disabled: Mercury failed to start twice right after it was enabled or updated. Re-enable it with /plugins enable ${guarded} once it's fixed.`);
+ }
+ } catch (err) {
+ logger.warn({ err }, 'Plugin boot guard could not read state');
+ }
+ await this.reconcile();
+ this.healthyTimer = setTimeout(() => {
+ void updateState((s) => {
+ s.boot.inProgress = false;
+ s.boot.failedBoots = 0;
+ }).catch(() => {});
+ }, BOOT_HEALTHY_AFTER_MS);
+ this.healthyTimer.unref?.();
+ }
+
+ /** Graceful shutdown: stop plugins and record a clean exit (not a crash). */
+ async shutdown(): Promise<void> {
+ if (this.healthyTimer) clearTimeout(this.healthyTimer);
+ const ids = [...this.running.keys()];
+ await Promise.all(ids.map((id) => this.stopRuntime(id)));
+ if (this.booted && !this.safeMode) {
+ await updateState((s) => {
+ s.boot.inProgress = false;
+ s.boot.failedBoots = 0;
+ }).catch(() => {});
+ }
+ }
+
+ // ── reconcile ────────────────────────────────────────────────────────
+
+ /** Make the running set match state.json. Serialised; never throws. */
+ async reconcile(): Promise<void> {
+ if (this.safeMode || !this.runs) return;
+ if (this.reconciling) return this.reconciling;
+ this.reconciling = (async () => {
+ try {
+ const state = readState();
+ for (const [id, run] of [...this.running]) {
+ const entry = state.plugins[id];
+ if (!entry || !entry.enabled || entry.version !== run.version) await this.stopRuntime(id);
+ }
+ for (const [id, entry] of Object.entries(state.plugins)) {
+ if (entry.enabled && !this.running.has(id)) await this.startRuntime(id, entry.version);
+ }
+ } catch (err) {
+ logger.error({ err }, 'Plugin reconcile failed');
+ } finally {
+ this.reconciling = null;
+ this.changed();
+ }
+ })();
+ return this.reconciling;
+ }
+
+ private async startRuntime(id: string, version: string): Promise<void> {
+ if (this.starting.has(id)) return;
+ this.starting.add(id);
+ try {
+ const dir = pluginVersionDir(id, version);
+ const manifest = installedManifest(id, version);
+ if (!manifest || !existsSync(dir)) {
+ await this.disableWith(id, 'activation', 'The installed files are missing or the manifest is broken. Reinstall the plugin.');
+ return;
+ }
+ const why = incompatibility(manifest);
+ if (why) {
+ await this.disableWith(id, 'incompatible', why);
+ return;
+ }
+ try {
+ await verifyPackage(dir, manifest);
+ } catch (err) {
+ await this.disableWith(id, 'integrity', (err as Error).message);
+ return;
+ }
+ try {
+ const moved = migrateSettings(manifest);
+ if (moved) logger.info({ plugin: id, ...moved }, 'Plugin settings migrated');
+ } catch (err) {
+ // Never fatal: the plugin starts with defaults for anything unreadable.
+ logger.warn({ plugin: id, err }, 'Plugin settings migration failed');
+ }
+ const deps = {
+ mercuryVersion: mercuryVersion(),
+ dataDir: pluginDataDir(id),
+ settings: resolvedSettings(manifest),
+ secrets: Object.fromEntries(manifest.permissions.secrets.map((k) => [k, process.env[k]])),
+ log: inProcessLogger(id),
+ onError: (message: string) => this.recordFailure(id, message),
+ onFatal: (code: 'crashed' | 'activation', message: string) => {
+ void this.disableWith(id, code, message);
+ },
+ };
+ const runtime: PluginRuntime = manifest.kind === 'in-process'
+ ? new InProcessRuntime(manifest, dir, deps)
+ : new OutOfProcessRuntime(manifest, dir, deps);
+ try {
+ await runtime.start();
+ } catch (err) {
+ try { await runtime.stop(); } catch { /* already down */ }
+ 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.lastErrors.delete(id);
+ logger.info({ plugin: id, version, kind: manifest.kind }, 'Plugin started');
+ } finally {
+ this.starting.delete(id);
+ }
+ }
+
+ private async stopRuntime(id: string): Promise<void> {
+ const run = this.running.get(id);
+ this.running.delete(id);
+ if (!run) {
+ unpublishPlugin(id);
+ return;
+ }
+ try {
+ await run.runtime.stop();
+ } catch (err) {
+ logger.warn({ err, plugin: id }, 'Plugin did not stop cleanly');
+ } finally {
+ unpublishPlugin(id);
+ }
+ }
+
+ // ── health ───────────────────────────────────────────────────────────
+
+ private recordSuccess(id: string): void {
+ const run = this.running.get(id);
+ if (run) run.consecutiveFailures = 0;
+ }
+
+ recordFailure(id: string, message: string): void {
+ this.lastErrors.set(id, message);
+ const run = this.running.get(id);
+ if (!run) return;
+ run.consecutiveFailures += 1;
+ run.lastError = message;
+ if (run.consecutiveFailures >= CIRCUIT_BREAKER_FAILURES) {
+ void this.disableWith(id, 'errors', `${CIRCUIT_BREAKER_FAILURES} failures in a row. Last: ${message}`);
+ }
+ }
+
+ private async disableWith(id: string, code: DisabledCode, message: string): Promise<void> {
+ this.lastErrors.set(id, message);
+ await this.stopRuntime(id);
+ await updateState((s) => {
+ const entry = s.plugins[id];
+ if (!entry) return;
+ entry.enabled = false;
+ entry.disabled = { code, message: message.slice(0, 500), at: new Date().toISOString() };
+ }).catch((err) => logger.error({ err, plugin: id }, 'Could not record plugin disable'));
+ logger.warn({ plugin: id, code, message }, 'Plugin disabled');
+ if (code !== 'user') this.notify(`⚠️ Plugin "${id}" was disabled: ${message}`);
+ this.changed();
+ }
+
+ /**
+ * Called from the process-level uncaughtException / unhandledRejection
+ * handlers. If the error came from a plugin's files, disable that plugin
+ * and report true so the daemon keeps running.
+ */
+ attributeFault(err: unknown): boolean {
+ const stack = err instanceof Error ? `${err.stack ?? ''}` : '';
+ if (!stack) return false;
+ for (const id of this.running.keys()) {
+ const dir = pluginDir(id) + sep;
+ const asUrl = dir.split(sep).join('/');
+ if (stack.includes(dir) || stack.includes(asUrl)) {
+ logger.error({ plugin: id, err }, 'Uncaught error from a plugin');
+ void this.disableWith(id, 'errors', `Uncaught error: ${(err as Error).message}`);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // ── owner actions ────────────────────────────────────────────────────
+
+ /** Install from a catalog id, folder, .tgz, https URL or github:owner/repo. Enables it unless told not to. */
+ async install(input: string, opts: { enable?: boolean; force?: boolean; onProgress?: (m: string) => void } = {}): Promise<InstallResult & { tier: 'official' | 'community' | 'local' }> {
+ const parsed = parseSource(input);
+ let result: InstallResult;
+ let tier: 'official' | 'community' | 'local' = 'local';
+ if ('kind' in parsed) {
+ const entry = await findCatalogEntry(parsed.id, { force: true });
+ if (!entry) {
+ const folder = existsSync(parsed.id) ? ` There is a folder called "${parsed.id}" here: to install it, use ./${parsed.id}` : ' Try /plugins to see what\'s available.';
+ throw new Error(`No plugin called "${parsed.id}" in the catalog.${folder}`);
+ }
+ const why = incompatibility({ engines: entry.engines, platforms: entry.artifacts ? Object.keys(entry.artifacts) as PluginManifest['platforms'] : undefined });
+ if (why) throw new Error(`${entry.name} can't be installed here: ${why}.`);
+ result = await installPackage({ type: 'catalog', entry }, { force: opts.force, onProgress: opts.onProgress });
+ tier = entry.tier;
+ } else {
+ result = await installPackage(parsed, { force: opts.force, onProgress: opts.onProgress });
+ }
+ if (opts.enable !== false) {
+ await this.enable(result.id);
+ } else {
+ await this.reconcile();
+ }
+ return { ...result, tier };
+ }
+
+ async enable(id: string): Promise<void> {
+ if (this.safeMode) throw new Error('Mercury is in safe mode: plugins are off for this run. Restart without --safe-mode to use them.');
+ await updateState((s) => {
+ const entry = s.plugins[id];
+ if (!entry) throw new Error(`Plugin "${id}" is not installed.`);
+ entry.enabled = true;
+ entry.disabled = undefined;
+ s.boot.lastChange = { id, at: new Date().toISOString() };
+ });
+ this.lastErrors.delete(id);
+ await this.reconcile();
+ const after = readState().plugins[id];
+ if (after && !after.enabled && after.disabled) throw new Error(after.disabled.message);
+ }
+
+ async disable(id: string): Promise<void> {
+ await updateState((s) => {
+ const entry = s.plugins[id];
+ if (!entry) throw new Error(`Plugin "${id}" is not installed.`);
+ entry.enabled = false;
+ entry.disabled = { code: 'user', message: 'Disabled by the owner.', at: new Date().toISOString() };
+ });
+ await this.reconcile();
+ }
+
+ async uninstall(id: string, opts: { purge?: boolean } = {}): Promise<void> {
+ await this.stopRuntime(id);
+ await uninstallPackage(id, opts.purge === true);
+ this.lastErrors.delete(id);
+ await this.reconcile();
+ }
+
+ /** Update one plugin, or every catalog plugin with a newer version. Returns what changed. */
+ async update(id?: string, opts: { onProgress?: (m: string) => void } = {}): Promise<Array<{ id: string; from: string; to: string }>> {
+ const state = readState();
+ const { entries } = await getCatalog({ force: true });
+ const targets = id ? [id] : Object.keys(state.plugins);
+ const done: Array<{ id: string; from: string; to: string }> = [];
+ for (const pid of targets) {
+ const entry = state.plugins[pid];
+ if (!entry) {
+ if (id) throw new Error(`Plugin "${pid}" is not installed.`);
+ continue;
+ }
+ if (entry.source.type !== 'catalog') {
+ if (id) throw new Error(`"${pid}" was installed from ${entry.source.type === 'path' ? 'a local path' : entry.source.ref}; reinstall it from there to update.`);
+ continue;
+ }
+ const latest = entries.find((e) => e.id === pid);
+ if (!latest || !isNewer(latest.version, entry.version)) continue;
+ const r = await installPackage({ type: 'catalog', entry: latest }, { onProgress: opts.onProgress });
+ done.push({ id: pid, from: entry.version, to: r.version });
+ }
+ await this.reconcile();
+ return done;
+ }
+
+ async rollback(id: string): Promise<{ from: string; to: string }> {
+ const r = await rollbackPackage(id);
+ await this.reconcile();
+ return r;
+ }
+
+ async setSetting(id: string, key: string, value: unknown): Promise<void> {
+ const entry = readState().plugins[id];
+ if (!entry) throw new Error(`Plugin "${id}" is not installed.`);
+ 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 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.
+ if (this.running.has(id)) {
+ await this.stopRuntime(id);
+ await this.reconcile();
+ }
+ }
+
+ // ── views ────────────────────────────────────────────────────────────
+
+ /** Catalog + installed plugins, merged into one list for every surface. */
+ async list(opts: { refresh?: boolean } = {}): Promise<{ items: PluginListItem[]; catalogError?: string; stale: boolean; safeMode: boolean }> {
+ const state = readState();
+ const catalog = await getCatalog({ force: opts.refresh });
+ const byId = new Map<string, CatalogEntry>(catalog.entries.map((e) => [e.id, e]));
+ const items: PluginListItem[] = [];
+ const ids = new Set([...Object.keys(state.plugins), ...byId.keys()]);
+ for (const id of ids) items.push(this.describe(id, state, byId.get(id)));
+ items.sort((a, b) => rank(a) - rank(b) || a.name.localeCompare(b.name));
+ return { items, catalogError: catalog.error, stale: catalog.stale, safeMode: this.safeMode };
+ }
+
+ async info(id: string): Promise<PluginListItem | null> {
+ const state = readState();
+ const entry = (await getCatalog()).entries.find((e) => e.id === id);
+ if (!state.plugins[id] && !entry) return null;
+ const item = this.describe(id, state, entry);
+ const inst = state.plugins[id];
+ const manifest = inst ? installedManifest(id, inst.version) : null;
+ 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] }));
+ }
+ return item;
+ }
+
+ private describe(id: string, state: PluginsState, cat?: CatalogEntry): PluginListItem {
+ const inst = state.plugins[id];
+ const manifest = inst ? installedManifest(id, inst.version) : null;
+ const run = this.running.get(id);
+ const catIncompat = cat ? incompatibility({ engines: cat.engines, platforms: cat.artifacts ? Object.keys(cat.artifacts) as PluginManifest['platforms'] : undefined }) : null;
+ const instIncompat = manifest ? incompatibility(manifest) : null;
+ let status: PluginListItem['status'];
+ if (!inst) status = catIncompat ? 'incompatible' : 'available';
+ else if (!manifest) status = 'error';
+ else if (cat && inst.source.type === 'catalog' && isNewer(cat.version, inst.version)) status = 'update-available';
+ else if (inst.enabled && run) status = 'enabled';
+ // Not running here: in safe mode it's off; in a process that doesn't run
+ // plugins (CLI, attached terminal) it's enabled and runs in the daemon.
+ else if (inst.enabled && !run) status = !this.runs ? 'enabled' : this.safeMode ? 'disabled' : 'error';
+ else if (instIncompat) status = 'incompatible';
+ else status = 'disabled';
+ return {
+ id,
+ name: manifest?.name ?? cat?.name ?? id,
+ description: manifest?.description ?? cat?.description ?? '',
+ kind: manifest?.kind ?? cat?.kind ?? 'in-process',
+ tier: inst && inst.source.type !== 'catalog' ? 'local' : cat?.tier ?? 'local',
+ status,
+ installedVersion: inst?.version,
+ latestVersion: cat?.version,
+ sizeBytes: inst ? packageSize(id, inst.version) : (cat?.artifacts ? Object.values(cat.artifacts)[0]?.size : cat?.artifact?.size),
+ enabled: inst?.enabled ?? false,
+ running: !!run && run.runtime.isRunning(),
+ 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}`) : [],
+ permissions: manifest?.permissions ?? (cat ? { network: cat.permissions.network, secrets: cat.permissions.secrets } : undefined),
+ disabled: inst?.disabled,
+ lastError: run?.lastError ?? this.lastErrors.get(id),
+ incompatibleReason: instIncompat ?? catIncompat ?? undefined,
+ };
+ }
+
+ /** Short health summary for /api/health and `mercury doctor`. */
+ health(): { safeMode: boolean; running: number; tools: number; commands: number; plugins: Array<{ id: string; version: string; kind: string; failures: number; lastError?: string }> } {
+ return {
+ safeMode: this.safeMode,
+ running: this.running.size,
+ tools: listLiveTools().length,
+ commands: listPluginCommands().length,
+ plugins: [...this.running.entries()].map(([id, r]) => ({ id, version: r.version, kind: r.runtime.kind, failures: r.consecutiveFailures, lastError: r.lastError })),
+ };
+ }
+}
+
+function rank(i: PluginListItem): number {
+ return { enabled: 0, 'update-available': 1, error: 2, disabled: 3, installed: 4, available: 5, incompatible: 6 }[i.status];
+}
+
+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 {
+ if (type === 'boolean') {
+ if (typeof value === 'boolean') return value;
+ if (value === 'true' || value === 'on' || value === 'yes') return true;
+ if (value === 'false' || value === 'off' || value === 'no') return false;
+ throw new Error('Expected true or false.');
+ }
+ if (type === 'number') {
+ const n = typeof value === 'number' ? value : Number(value);
+ if (!Number.isFinite(n)) throw new Error('Expected a number.');
+ return n;
+ }
+ if (type === 'enum') {
+ if (typeof value !== 'string' || !options?.includes(value)) throw new Error(`Expected one of: ${(options ?? []).join(', ')}.`);
+ return value;
+ }
+ if (typeof value !== 'string') throw new Error('Expected text.');
+ return value;
+}
+
+export function isSafeModeRequested(): boolean {
+ return process.argv.includes('--safe-mode') || /^(off|0|false|no)$/i.test(process.env.MERCURY_PLUGINS ?? '');
+}
+
+// ── process-wide instance ──────────────────────────────────────────────
+
+let instance: PluginManager | null = null;
+
+/** The process-wide manager. It runs nothing until the runtime owner calls setRunsPlugins(true). */
+export function getPluginManager(): PluginManager {
+ if (!instance) instance = new PluginManager({ runsPlugins: false });
+ return instance;
+}
+
+/** The manager only if one exists (crash handlers must not create one). */
+export function peekPluginManager(): PluginManager | null {
+ return instance;
+}
+
+/** Test hook. */
+export function resetPluginManager(): void {
+ instance = null;
+}
diff --git a/src/plugins/runtime/in-process.ts b/src/plugins/runtime/in-process.ts
new file mode 100644
index 00000000..0fd92242
--- /dev/null
+++ b/src/plugins/runtime/in-process.ts
@@ -0,0 +1,273 @@
+/**
+ * In-process plugin runtime: loads the plugin's bundled ES module into the
+ * daemon and hands it a PluginContext.
+ *
+ * Containment, since the code shares our process:
+ * - loading, activate() and deactivate() each have a timeout;
+ * - tools/commands can only be registered under names the manifest
+ * declared, so the install prompt always tells the truth;
+ * - timers go through ctx.timers, which catches their errors and clears
+ * them on stop; fetches go through ctx.fetch (declared hosts, SSRF guard,
+ * aborted on stop);
+ * - stop() tears down everything registered, however activate() ended.
+ * What try/catch cannot contain (a busy loop, process.exit) is why
+ * untrusted code belongs in an out-of-process plugin.
+ */
+import { pathToFileURL } from 'node:url';
+import { resolve } from 'node:path';
+import { assertFetchableTarget, MAX_REDIRECTS } from '../../utils/ssrf.js';
+import { logger } from '../../utils/logger.js';
+import { PLUGIN_API_VERSION, type PluginManifest } from '../types.js';
+import type { Disposable, PluginCommandDefinition, PluginContext, PluginModule, PluginToolDefinition } from '../sdk.js';
+import { publishCommand, publishTool, unpublishPlugin } from '../tool-bridge.js';
+import type { PluginRuntime, RuntimeDeps } from './types.js';
+
+export const IN_PROCESS_TIMEOUTS = { load: 10_000, activate: 15_000, deactivate: 5_000, dispose: 3_000 };
+
+function withTimeout<T>(p: Promise<T>, ms: number, what: string): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ return Promise.race([
+ p.finally(() => timer && clearTimeout(timer)),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`${what} timed out after ${Math.round(ms / 1000)}s`)), ms);
+ }),
+ ]);
+}
+
+/** Host may match exactly, or a "*.example.com" entry matches subdomains (not the apex). */
+export function hostAllowed(host: string, allowed: readonly string[]): boolean {
+ const h = host.toLowerCase().replace(/\.$/, '');
+ return allowed.some((rule) => {
+ const r = rule.toLowerCase();
+ if (r.startsWith('*.')) return h.endsWith(r.slice(1)) && h.length > r.length - 1;
+ return h === r;
+ });
+}
+
+let loadCounter = 0;
+
+export class InProcessRuntime implements PluginRuntime {
+ readonly kind = 'in-process' as const;
+ private ac = new AbortController();
+ private disposables: Array<() => void | Promise<void>> = [];
+ private module: PluginModule | null = null;
+ private running = false;
+ private registered = new Set<string>();
+
+ constructor(private readonly manifest: PluginManifest, private readonly dir: string, private readonly deps: RuntimeDeps) {}
+
+ isRunning(): boolean {
+ return this.running;
+ }
+
+ async start(): Promise<void> {
+ this.ac = new AbortController();
+ const entry = resolve(this.dir, this.manifest.entry!);
+ const href = pathToFileURL(entry).href;
+ loadCounter += 1;
+ let mod: unknown;
+ try {
+ // A query string gives a fresh module instance after disable → enable.
+ mod = await withTimeout(import(`${href}?instance=${loadCounter}`), IN_PROCESS_TIMEOUTS.load, 'Loading the plugin');
+ } catch (err) {
+ const msg = (err as Error).message ?? '';
+ if (!/Cannot find (module|package)|ERR_MODULE_NOT_FOUND|not found/i.test(msg) || /Cannot find package/i.test(msg)) throw this.explainLoadError(err);
+ mod = await withTimeout(import(href), IN_PROCESS_TIMEOUTS.load, 'Loading the plugin').catch((e) => { throw this.explainLoadError(e); });
+ }
+ const m = mod as Partial<PluginModule> & { default?: Partial<PluginModule> };
+ const plugin = (typeof m.activate === 'function' ? m : m.default) as PluginModule | undefined;
+ if (!plugin || typeof plugin.activate !== 'function') throw new Error('The plugin module does not export an activate(ctx) function.');
+ this.module = plugin;
+ this.running = true;
+ try {
+ await withTimeout(Promise.resolve().then(() => plugin.activate(this.context())), IN_PROCESS_TIMEOUTS.activate, 'activate()');
+ } catch (err) {
+ await this.stop();
+ throw err;
+ }
+ const declared = this.manifest.contributes.tools.map((t) => t.name);
+ const missing = declared.filter((n) => !this.registered.has(`tool:${n}`));
+ if (missing.length > 0) this.deps.log.warn(`declared tools not registered by activate(): ${missing.join(', ')}`);
+ }
+
+ private explainLoadError(err: unknown): Error {
+ const msg = (err as Error)?.message ?? String(err);
+ if (/Cannot find package/i.test(msg)) {
+ return new Error(`${msg.split('\n')[0]}. In-process plugins must be bundled into a single file; Mercury can't resolve packages for them.`);
+ }
+ return err instanceof Error ? err : new Error(msg);
+ }
+
+ async stop(): Promise<void> {
+ const wasRunning = this.running;
+ this.running = false;
+ this.ac.abort(new Error('plugin stopped'));
+ if (wasRunning && this.module?.deactivate) {
+ try {
+ await withTimeout(Promise.resolve().then(() => this.module!.deactivate!()), IN_PROCESS_TIMEOUTS.deactivate, 'deactivate()');
+ } catch (err) {
+ this.deps.log.warn(`deactivate() failed: ${(err as Error).message}`);
+ }
+ }
+ const pending = this.disposables.splice(0).reverse();
+ for (const d of pending) {
+ try {
+ await withTimeout(Promise.resolve().then(d), IN_PROCESS_TIMEOUTS.dispose, 'cleanup');
+ } catch (err) {
+ this.deps.log.warn(`cleanup failed: ${(err as Error).message}`);
+ }
+ }
+ unpublishPlugin(this.manifest.id);
+ this.registered.clear();
+ this.module = null;
+ }
+
+ private track(fn: () => void | Promise<void>): Disposable {
+ let done = false;
+ const d = () => {
+ if (done) return;
+ done = true;
+ return fn();
+ };
+ this.disposables.push(d);
+ return { dispose: () => void d() };
+ }
+
+ /** Run plugin code from a timer or callback; failures count against the plugin instead of crashing us. */
+ private guard(fn: () => void | Promise<void>, where: string): void {
+ if (!this.running) return;
+ Promise.resolve()
+ .then(fn)
+ .catch((err) => this.deps.onError(`${where}: ${(err as Error)?.message ?? String(err)}`));
+ }
+
+ private context(): PluginContext {
+ const m = this.manifest;
+ const declaredTools = new Map(m.contributes.tools.map((t) => [t.name, t]));
+ const declaredCommands = new Map(m.contributes.commands.map((c) => [c.name, c]));
+ const declaredSecrets = new Set(m.permissions.secrets);
+ const signal = this.ac.signal;
+ const self = this;
+
+ const register = (def: PluginToolDefinition): Disposable => {
+ if (!self.running) throw new Error('Plugin is not running.');
+ const decl = declaredTools.get(def?.name);
+ if (!decl) throw new Error(`Tool "${def?.name}" is not declared in mercury-plugin.json (contributes.tools).`);
+ if (typeof def.execute !== 'function') throw new Error(`Tool "${def.name}" has no execute function.`);
+ const schema = def.inputSchema ?? { type: 'object', properties: {} };
+ if (typeof schema !== 'object' || (schema as { type?: unknown }).type !== 'object') {
+ throw new Error(`Tool "${def.name}" needs an inputSchema with type "object".`);
+ }
+ const unpublish = publishTool({
+ pluginId: m.id,
+ pluginName: m.name,
+ name: decl.name,
+ description: decl.description,
+ inputSchema: schema,
+ readOnly: decl.readOnly,
+ timeoutMs: decl.timeoutMs,
+ invoke: async (args, toolSignal) => {
+ if (!self.running) throw new Error('the plugin is not running');
+ const combined = AbortSignal.any([toolSignal, signal]);
+ return def.execute(args, { signal: combined });
+ },
+ });
+ self.registered.add(`tool:${decl.name}`);
+ return self.track(() => {
+ unpublish();
+ self.registered.delete(`tool:${decl.name}`);
+ });
+ };
+
+ const registerCommand = (def: PluginCommandDefinition): Disposable => {
+ if (!self.running) throw new Error('Plugin is not running.');
+ const decl = declaredCommands.get(def?.name);
+ if (!decl) throw new Error(`Command "${def?.name}" is not declared in mercury-plugin.json (contributes.commands).`);
+ if (typeof def.run !== 'function') throw new Error(`Command "${def.name}" has no run function.`);
+ const unpublish = publishCommand({
+ pluginId: m.id,
+ pluginName: m.name,
+ name: decl.name,
+ description: decl.description,
+ run: async (args, io) => {
+ if (!self.running) throw new Error('the plugin is not running');
+ await def.run(args, { reply: io.reply, signal: AbortSignal.any([io.signal, signal]) });
+ },
+ });
+ self.registered.add(`command:${decl.name}`);
+ return self.track(() => {
+ unpublish();
+ self.registered.delete(`command:${decl.name}`);
+ });
+ };
+
+ const pluginFetch = async (url: string, init: RequestInit = {}): Promise<Response> => {
+ if (!self.running) throw new Error('Plugin is not running.');
+ let target = url;
+ const reqSignal = init.signal ? AbortSignal.any([init.signal, signal]) : signal;
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
+ const parsed = new URL(target);
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') throw new Error(`Only http(s) requests are allowed (got ${parsed.protocol}).`);
+ if (!hostAllowed(parsed.hostname, m.permissions.network)) {
+ throw new Error(`Network access to ${parsed.hostname} is not declared in this plugin's permissions.network.`);
+ }
+ await assertFetchableTarget(parsed.href);
+ const res = await fetch(parsed.href, { ...init, signal: reqSignal, redirect: 'manual' });
+ if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
+ try { void res.body?.cancel(); } catch { /* ignore */ }
+ target = new URL(res.headers.get('location')!, parsed).href;
+ continue;
+ }
+ return res;
+ }
+ throw new Error(`Too many redirects (more than ${MAX_REDIRECTS}).`);
+ };
+
+ const scoped = this.deps.log;
+ return Object.freeze({
+ apiVersion: PLUGIN_API_VERSION,
+ mercuryVersion: this.deps.mercuryVersion,
+ plugin: Object.freeze({ id: m.id, version: m.version, dataDir: this.deps.dataDir }),
+ log: Object.freeze({
+ debug: (msg: string, data?: Record<string, unknown>) => scoped.debug(msg, data),
+ info: (msg: string, data?: Record<string, unknown>) => scoped.info(msg, data),
+ warn: (msg: string, data?: Record<string, unknown>) => scoped.warn(msg, data),
+ error: (msg: string, data?: Record<string, unknown>) => scoped.error(msg, data),
+ }),
+ settings: Object.freeze({
+ get: <T,>(key: string) => self.deps.settings[key] as T | undefined,
+ all: () => ({ ...self.deps.settings }),
+ }),
+ secrets: Object.freeze({
+ get: (name: string) => (declaredSecrets.has(name) ? self.deps.secrets[name] : undefined),
+ }),
+ tools: Object.freeze({ register }),
+ commands: Object.freeze({ register: registerCommand }),
+ timers: Object.freeze({
+ setTimeout: (fn: () => void | Promise<void>, ms: number): Disposable => {
+ const h = setTimeout(() => self.guard(fn, 'timer'), Math.max(0, ms));
+ return self.track(() => clearTimeout(h));
+ },
+ setInterval: (fn: () => void | Promise<void>, ms: number): Disposable => {
+ const h = setInterval(() => self.guard(fn, 'interval'), Math.max(1000, ms));
+ return self.track(() => clearInterval(h));
+ },
+ }),
+ fetch: pluginFetch,
+ signal,
+ onDispose: (fn: () => void | Promise<void>) => {
+ self.track(fn);
+ },
+ }) as PluginContext;
+ }
+}
+
+export function inProcessLogger(pluginId: string): RuntimeDeps['log'] {
+ const child = logger.child({ plugin: pluginId });
+ return {
+ debug: (msg, data) => child.debug(data ?? {}, msg),
+ info: (msg, data) => child.info(data ?? {}, msg),
+ warn: (msg, data) => child.warn(data ?? {}, msg),
+ error: (msg, data) => child.error(data ?? {}, msg),
+ };
+}
diff --git a/src/plugins/runtime/out-of-process.ts b/src/plugins/runtime/out-of-process.ts
new file mode 100644
index 00000000..23f5707f
--- /dev/null
+++ b/src/plugins/runtime/out-of-process.ts
@@ -0,0 +1,355 @@
+/**
+ * Out-of-process plugin runtime: the plugin is a child process speaking MCP
+ * (JSON-RPC 2.0, newline-delimited) over stdio. Mercury implements the
+ * client side of the subset tools need: initialize, notifications/initialized,
+ * tools/list, tools/call, ping, and notifications/tools/list_changed.
+ *
+ * Because it's a separate process, nothing it does can block or crash the
+ * daemon. Supervision:
+ * - every request has a timeout; a hung server is killed and restarted;
+ * - crashes restart with exponential backoff (1s → 60s);
+ * - more than 5 crashes in 10 minutes stops it and disables the plugin;
+ * - the child gets a minimal environment: PATH/HOME-style basics, the
+ * plugin's own folders, and only the secrets its manifest declared.
+ */
+import { spawn, type ChildProcess } from 'node:child_process';
+import { resolve } from 'node:path';
+import { createInterface } from 'node:readline';
+import { PLUGIN_API_VERSION, type PluginManifest } from '../types.js';
+import { currentPlatform } from '../store.js';
+import { publishTool, unpublishPlugin } from '../tool-bridge.js';
+import type { PluginRuntime, RuntimeDeps } from './types.js';
+
+export const OUT_OF_PROCESS = {
+ initTimeoutMs: 20_000,
+ listTimeoutMs: 15_000,
+ stopGraceMs: 3_000,
+ maxCrashes: 5,
+ crashWindowMs: 10 * 60 * 1000,
+ backoffStartMs: 1_000,
+ backoffMaxMs: 60_000,
+ maxLineBytes: 8 * 1024 * 1024,
+};
+
+const MCP_PROTOCOL_VERSION = '2025-06-18';
+
+/** Environment variables passed through to plugin processes; nothing else leaks. */
+const PASS_ENV = ['PATH', 'HOME', 'USERPROFILE', 'SYSTEMROOT', 'SystemRoot', 'TEMP', 'TMP', 'TMPDIR', 'LANG', 'LC_ALL', 'TZ', 'APPDATA', 'LOCALAPPDATA', 'PROGRAMDATA', 'COMSPEC', 'PATHEXT', 'WINDIR'];
+
+interface Pending {
+ resolve(value: unknown): void;
+ reject(err: Error): void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+interface McpTool {
+ name: string;
+ description?: string;
+ inputSchema?: Record<string, unknown>;
+}
+
+export class OutOfProcessRuntime implements PluginRuntime {
+ readonly kind = 'out-of-process' as const;
+ private child: ChildProcess | null = null;
+ private nextId = 1;
+ private pending = new Map<number, Pending>();
+ private wanted = false;
+ private ready = false;
+ private crashes: number[] = [];
+ private backoff = OUT_OF_PROCESS.backoffStartMs;
+ private restartTimer: ReturnType<typeof setTimeout> | null = null;
+ private stderrTail: string[] = [];
+
+ constructor(private readonly manifest: PluginManifest, private readonly dir: string, private readonly deps: RuntimeDeps) {}
+
+ isRunning(): boolean {
+ return this.ready;
+ }
+
+ /** Start and complete the MCP handshake. Throws if the first start fails. */
+ async start(): Promise<void> {
+ this.wanted = true;
+ await this.launch();
+ }
+
+ async stop(): Promise<void> {
+ this.wanted = false;
+ if (this.restartTimer) clearTimeout(this.restartTimer);
+ this.restartTimer = null;
+ await this.kill();
+ unpublishPlugin(this.manifest.id);
+ }
+
+ private command(): { cmd: string; args: string[]; env: Record<string, string> } {
+ const spec = this.manifest.server!.platforms?.[currentPlatform()] ?? this.manifest.server!;
+ const extraEnv: Record<string, string> = {};
+ if (spec.command === 'node') {
+ // npm installs run on Node; standalone binaries are Bun and can run a
+ // script themselves with BUN_BE_BUN=1 (no system Node needed).
+ if (typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined') extraEnv.BUN_BE_BUN = '1';
+ return { cmd: process.execPath, args: spec.args.map((a, i) => (i === 0 ? resolve(this.dir, a) : a)), env: extraEnv };
+ }
+ return { cmd: resolve(this.dir, spec.command), args: spec.args, env: extraEnv };
+ }
+
+ private buildEnv(extra: Record<string, string>): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const k of PASS_ENV) if (process.env[k]) env[k] = process.env[k]!;
+ for (const [k, v] of Object.entries(this.deps.secrets)) if (v !== undefined) env[k] = v;
+ env.MERCURY_PLUGIN_ID = this.manifest.id;
+ env.MERCURY_PLUGIN_VERSION = this.manifest.version;
+ env.MERCURY_PLUGIN_DATA_DIR = this.deps.dataDir;
+ env.MERCURY_PLUGIN_API = PLUGIN_API_VERSION;
+ env.MERCURY_PLUGIN_SETTINGS = JSON.stringify(this.deps.settings);
+ return { ...env, ...extra };
+ }
+
+ private async launch(): Promise<void> {
+ const { cmd, args, env } = this.command();
+ const child = spawn(cmd, args, {
+ cwd: this.dir,
+ env: this.buildEnv(env),
+ stdio: ['pipe', 'pipe', 'pipe'],
+ windowsHide: true,
+ });
+ this.child = child;
+ this.ready = false;
+ this.stderrTail = [];
+
+ const spawned = new Promise<void>((res, rej) => {
+ child.once('spawn', () => res());
+ child.once('error', (err) => rej(new Error(`Couldn't start the plugin process: ${err.message}`)));
+ });
+
+ const out = createInterface({ input: child.stdout!, crlfDelay: Infinity });
+ out.on('line', (line) => this.onLine(line));
+ child.stderr!.setEncoding('utf8');
+ child.stderr!.on('data', (chunk: string) => {
+ for (const l of chunk.split('\n')) {
+ if (!l.trim()) continue;
+ this.stderrTail.push(l.slice(0, 500));
+ if (this.stderrTail.length > 20) this.stderrTail.shift();
+ this.deps.log.debug(`stderr: ${l.slice(0, 500)}`);
+ }
+ });
+ child.stdin!.on('error', () => { /* broken pipe on crash; handled by exit */ });
+ child.once('exit', (code, sig) => this.onExit(child, code, sig));
+
+ await spawned;
+ try {
+ await this.request('initialize', {
+ protocolVersion: MCP_PROTOCOL_VERSION,
+ capabilities: {},
+ 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;
+ } catch (err) {
+ const tail = this.stderrTail.slice(-3).join(' | ');
+ await this.kill();
+ throw new Error(`${(err as Error).message}${tail ? ` (stderr: ${tail})` : ''}`);
+ }
+ }
+
+ private async refreshTools(): Promise<void> {
+ const res = (await this.request('tools/list', {}, OUT_OF_PROCESS.listTimeoutMs)) as { tools?: McpTool[] };
+ const offered = new Map((res?.tools ?? []).map((t) => [t.name, t]));
+ unpublishPlugin(this.manifest.id);
+ for (const decl of this.manifest.contributes.tools) {
+ const t = offered.get(decl.name);
+ if (!t) {
+ this.deps.log.warn(`declared tool "${decl.name}" is not offered by the server`);
+ continue;
+ }
+ const schema = t.inputSchema && t.inputSchema.type === 'object' ? t.inputSchema : { type: 'object', properties: {} };
+ publishTool({
+ pluginId: this.manifest.id,
+ pluginName: this.manifest.name,
+ name: decl.name,
+ description: decl.description,
+ inputSchema: schema,
+ readOnly: decl.readOnly,
+ timeoutMs: decl.timeoutMs,
+ invoke: (args, signal) => this.callTool(decl.name, args, signal, decl.timeoutMs),
+ });
+ }
+ for (const name of offered.keys()) {
+ if (!this.manifest.contributes.tools.some((d) => d.name === name)) {
+ this.deps.log.warn(`server offers undeclared tool "${name}"; ignored (declare it in mercury-plugin.json)`);
+ }
+ }
+ }
+
+ private async callTool(name: string, args: Record<string, unknown>, signal: AbortSignal, timeoutMs: number): Promise<unknown> {
+ if (!this.ready) throw new Error('the plugin process is not running');
+ const res = (await this.request('tools/call', { name, arguments: args }, timeoutMs + 1000, signal)) as {
+ content?: Array<{ type: string; text?: string }>;
+ isError?: boolean;
+ structuredContent?: unknown;
+ };
+ const text = (res?.content ?? []).map((c) => (c.type === 'text' ? c.text ?? '' : `[${c.type} content]`)).join('\n');
+ if (res?.isError) throw new Error(text || 'the tool reported an error');
+ return text || (res?.structuredContent !== undefined ? res.structuredContent : 'Done.');
+ }
+
+ private request(method: string, params: unknown, timeoutMs: number, signal?: AbortSignal): 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++;
+ return new Promise((resolvePromise, rejectPromise) => {
+ const timer = setTimeout(() => {
+ 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`);
+ }, timeoutMs);
+ this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
+ if (signal) {
+ const onAbort = () => {
+ const p = this.pending.get(id);
+ if (!p) return;
+ clearTimeout(p.timer);
+ this.pending.delete(id);
+ this.notify('notifications/cancelled', { requestId: id, reason: 'cancelled' });
+ rejectPromise(new Error('cancelled'));
+ };
+ if (signal.aborted) onAbort();
+ else signal.addEventListener('abort', onAbort, { once: true });
+ }
+ child.stdin!.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`);
+ });
+ }
+
+ private notify(method: string, params: unknown): void {
+ const child = this.child;
+ if (!child?.stdin?.writable) return;
+ try {
+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method, params })}\n`);
+ } catch { /* closing */ }
+ }
+
+ private onLine(line: string): void {
+ if (!line.trim()) return;
+ if (line.length > OUT_OF_PROCESS.maxLineBytes) {
+ this.deps.onError('protocol: message too large');
+ return;
+ }
+ let msg: { id?: number | string; method?: string; result?: unknown; error?: { message?: string }; params?: unknown };
+ try {
+ msg = JSON.parse(line);
+ } catch {
+ // Servers sometimes print logs to stdout; MCP reserves stdout for protocol.
+ this.deps.log.debug(`non-protocol stdout: ${line.slice(0, 200)}`);
+ return;
+ }
+ if (msg.method && msg.id !== undefined) {
+ // Server → client requests: we support ping; refuse everything else (sampling, roots…).
+ if (msg.method === 'ping') this.reply(msg.id, {});
+ else this.replyError(msg.id, -32601, `Mercury does not support ${msg.method}`);
+ return;
+ }
+ 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}`));
+ }
+ return;
+ }
+ if (typeof msg.id !== 'number') return;
+ const p = this.pending.get(msg.id);
+ if (!p) return;
+ clearTimeout(p.timer);
+ this.pending.delete(msg.id);
+ if (msg.error) p.reject(new Error(msg.error.message ?? 'server error'));
+ else p.resolve(msg.result);
+ }
+
+ private reply(id: number | string, result: unknown): void {
+ this.child?.stdin?.write(`${JSON.stringify({ jsonrpc: '2.0', id, result })}\n`);
+ }
+
+ private replyError(id: number | string, code: number, message: string): void {
+ this.child?.stdin?.write(`${JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } })}\n`);
+ }
+
+ private failPending(reason: string): void {
+ for (const [id, p] of this.pending) {
+ clearTimeout(p.timer);
+ p.reject(new Error(reason));
+ this.pending.delete(id);
+ }
+ }
+
+ private onExit(child: ChildProcess, code: number | null, sig: NodeJS.Signals | null): void {
+ if (this.child !== child) return;
+ this.child = null;
+ const wasReady = this.ready;
+ this.ready = false;
+ this.failPending('the plugin process exited');
+ unpublishPlugin(this.manifest.id);
+ if (!this.wanted) return;
+ const tail = this.stderrTail.slice(-3).join(' | ');
+ const why = `exited (${sig ?? `code ${code}`})${tail ? `: ${tail}` : ''}`;
+ if (!wasReady) return; // start() reports first-launch failures itself
+ // Counted once, by the crash window below. (A call that was in flight
+ // already counts as a failed tool call; don't double-count the crash.)
+ this.deps.log.warn(`plugin process ${why}`);
+ this.scheduleRestart(why);
+ }
+
+ private scheduleRestart(why: string): void {
+ const now = Date.now();
+ this.crashes = this.crashes.filter((t) => now - t < OUT_OF_PROCESS.crashWindowMs);
+ this.crashes.push(now);
+ if (this.crashes.length > OUT_OF_PROCESS.maxCrashes) {
+ this.wanted = false;
+ this.deps.onFatal?.('crashed', `crashed ${this.crashes.length} times in ${OUT_OF_PROCESS.crashWindowMs / 60000} minutes (last: ${why})`);
+ return;
+ }
+ const delay = this.backoff;
+ this.backoff = Math.min(this.backoff * 2, OUT_OF_PROCESS.backoffMaxMs);
+ this.deps.log.warn(`restarting in ${Math.round(delay / 1000)}s after it ${why}`);
+ this.restartTimer = setTimeout(() => {
+ this.restartTimer = null;
+ if (!this.wanted) return;
+ this.launch().catch((err) => {
+ this.deps.onError(`restart failed: ${(err as Error).message}`);
+ this.scheduleRestart(`restart failed: ${(err as Error).message}`);
+ });
+ }, delay);
+ }
+
+ /** Kill a hung server; the exit handler restarts it. */
+ private async recycle(reason: string): Promise<void> {
+ if (!this.child || !this.wanted) return;
+ this.deps.log.warn(`killing unresponsive plugin process: ${reason}`);
+ this.child.kill('SIGKILL');
+ }
+
+ private async kill(): Promise<void> {
+ const child = this.child;
+ this.ready = false;
+ if (!child) return;
+ this.failPending('the plugin is stopping');
+ await new Promise<void>((res) => {
+ if (child.exitCode !== null || child.signalCode !== null) return res();
+ const t = setTimeout(() => {
+ try { child.kill('SIGKILL'); } catch { /* gone */ }
+ }, OUT_OF_PROCESS.stopGraceMs);
+ child.once('exit', () => {
+ clearTimeout(t);
+ res();
+ });
+ try {
+ child.stdin?.end();
+ child.kill('SIGTERM');
+ } catch {
+ clearTimeout(t);
+ res();
+ }
+ });
+ if (this.child === child) this.child = null;
+ }
+}
+
diff --git a/src/plugins/runtime/types.ts b/src/plugins/runtime/types.ts
new file mode 100644
index 00000000..a23cceec
--- /dev/null
+++ b/src/plugins/runtime/types.ts
@@ -0,0 +1,27 @@
+export interface RuntimeLog {
+ debug(message: string, data?: Record<string, unknown>): void;
+ info(message: string, data?: Record<string, unknown>): void;
+ warn(message: string, data?: Record<string, unknown>): void;
+ error(message: string, data?: Record<string, unknown>): void;
+}
+
+export interface RuntimeDeps {
+ mercuryVersion: string;
+ dataDir: string;
+ /** Resolved settings (defaults filled in, unknown keys dropped). */
+ settings: Record<string, unknown>;
+ /** Only the secrets the manifest declared, read from ~/.mercury/.env. */
+ secrets: Record<string, string | undefined>;
+ log: RuntimeLog;
+ /** A failure outside a tool call (timer, crash, protocol error). Counts toward the circuit breaker. */
+ 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;
+}
+
+export interface PluginRuntime {
+ readonly kind: 'in-process' | 'out-of-process';
+ start(): Promise<void>;
+ stop(): Promise<void>;
+ isRunning(): boolean;
+}
diff --git a/src/plugins/scaffold.test.ts b/src/plugins/scaffold.test.ts
new file mode 100644
index 00000000..f4d9cb9d
--- /dev/null
+++ b/src/plugins/scaffold.test.ts
@@ -0,0 +1,45 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { PluginManager } from './manager.js';
+import { runConformance } from './conformance.js';
+import { packPlugin, scaffoldPlugin } from './scaffold.js';
+import { PLUGIN_SDK_DTS } from './sdk-dts.js';
+import { readState } from './store.js';
+import { getPluginTools, resetToolBridge } from './tool-bridge.js';
+import { PermissionManager } from '../capabilities/permissions.js';
+import { tempHome } from './test-fixtures.js';
+
+let env: ReturnType<typeof tempHome>;
+let mgr: PluginManager;
+beforeEach(() => { env = tempHome(); resetToolBridge(); mgr = new PluginManager({ safeMode: false, notify: () => {} }); });
+afterEach(async () => { await mgr.shutdown(); resetToolBridge(); env.restore(); });
+
+describe('author tooling', () => {
+ it('the embedded SDK types match src/plugins/sdk.ts (run: node scripts/gen-plugin-sdk.mjs)', () => {
+ expect(PLUGIN_SDK_DTS).toBe(readFileSync(join(process.cwd(), 'src/plugins/sdk.ts'), 'utf8'));
+ });
+
+ for (const kind of ['in-process', 'out-of-process'] as const) {
+ it(`a fresh ${kind} scaffold passes conformance, packs, installs and works`, async () => {
+ const dir = scaffoldPlugin(env.home, kind === 'in-process' ? 'hello-world' : 'hello-mcp', kind);
+ const report = await runConformance(dir);
+ expect(report.checks.filter((c) => !c.ok)).toEqual([]);
+
+ const packed = await packPlugin(dir, join(env.home, 'out'));
+ expect(packed.entry.artifact?.sha256).toBe(packed.sha256);
+ await mgr.install(packed.file);
+ const id = report.id!;
+ expect(readState().plugins[id]).toMatchObject({ version: '0.1.0', enabled: true });
+
+ const tools = getPluginTools(new PermissionManager());
+ const greet = tools[`${id}__greet`] as unknown as { execute: (a: unknown, o: unknown) => Promise<unknown> };
+ expect(await greet.execute({ name: 'Ada' }, { toolCallId: 't', messages: [] })).toBe('Hello, Ada!');
+ });
+ }
+
+ it('refuses ids that would take a built-in command', () => {
+ expect(() => scaffoldPlugin(env.home, 'help', 'in-process')).toThrow();
+ expect(() => scaffoldPlugin(env.home, 'stop', 'in-process')).toThrow(/built-in/);
+ });
+});
diff --git a/src/plugins/scaffold.ts b/src/plugins/scaffold.ts
new file mode 100644
index 00000000..e3556a5e
--- /dev/null
+++ b/src/plugins/scaffold.ts
@@ -0,0 +1,235 @@
+/**
+ * Author tooling: `mercury plugins init` (a working plugin to start from)
+ * and `mercury plugins pack` (the .tgz, its checksum and the catalog entry).
+ * Together with `validate` (conformance.ts) this is the whole author loop,
+ * with nothing to install from npm.
+ */
+import { execFile } from 'node:child_process';
+import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from 'node:fs';
+import { basename, join, resolve } from 'node:path';
+import { promisify } from 'node:util';
+import semver from 'semver';
+import { checkTree, loadManifest, sha256File } from './installer.js';
+import { mercuryVersion } from './store.js';
+import { PLUGIN_SDK_DTS } from './sdk-dts.js';
+import { PLUGIN_ID_RE, PLUGIN_API_VERSION, RESERVED_COMMANDS, type CatalogEntry } from './types.js';
+
+const execFileAsync = promisify(execFile);
+
+export type ScaffoldKind = 'in-process' | 'out-of-process';
+
+function engineRange(): string {
+ const v = semver.coerce(mercuryVersion())?.version ?? '1.0.0';
+ return `>=${semver.major(v)}.${semver.minor(v)}.0 <${semver.major(v) + 1}.0.0`;
+}
+
+function titleCase(id: string): string {
+ return id.split('-').map((w) => w[0].toUpperCase() + w.slice(1)).join(' ');
+}
+
+const IN_PROCESS_ENTRY = (id: string) => `// @ts-check
+/**
+ * ${titleCase(id)}: a Mercury in-process plugin.
+ *
+ * Rules that keep Mercury stable (checked by \`mercury plugins validate\`):
+ * - Ship ONE self-contained file. Bundle any npm packages into it
+ * (esbuild --bundle --format=esm --platform=node); only node: builtins
+ * resolve at runtime.
+ * - Talk to Mercury only through \`ctx\`. Timers, tools and commands made
+ * through it are cleaned up when the plugin is turned off.
+ * - Use ctx.fetch for network access; only hosts in the manifest work.
+ *
+ * @param {import('./mercury-plugin').PluginContext} ctx
+ */
+export async function activate(ctx) {
+ ctx.tools.register({
+ name: 'greet',
+ inputSchema: {
+ type: 'object',
+ properties: { name: { type: 'string', description: 'Who to greet' } },
+ required: ['name'],
+ },
+ execute: async (args) => {
+ const greeting = ctx.settings.get('greeting') ?? 'Hello';
+ return \`\${greeting}, \${String(args.name)}!\`;
+ },
+ });
+
+ ctx.commands.register({
+ name: '${id.replace(/-/g, '_').slice(0, 30)}',
+ run: async (args, io) => {
+ await io.reply(\`${titleCase(id)} is running. You said: \${args || '(nothing)'}\`);
+ },
+ });
+
+ ctx.log.info('activated');
+}
+
+/** Optional. Anything registered through ctx is already cleaned up for you. */
+export async function deactivate() {}
+`;
+
+const OUT_OF_PROCESS_SERVER = (id: string) => `// ${titleCase(id)}: a Mercury out-of-process plugin.
+//
+// A minimal MCP server over stdio (JSON-RPC 2.0, one message per line),
+// with no dependencies. Mercury starts it with its own runtime, restarts it
+// if it crashes, and stops it when the plugin is turned off. You can swap
+// this for any MCP SDK, or ship a native binary and point "server.command"
+// at it. Settings arrive as JSON in MERCURY_PLUGIN_SETTINGS; declared
+// secrets arrive as environment variables. Log to stderr, never stdout.
+import { createInterface } from 'node:readline';
+
+const settings = JSON.parse(process.env.MERCURY_PLUGIN_SETTINGS || '{}');
+const send = (message) => process.stdout.write(JSON.stringify(message) + '\\n');
+
+const tools = [
+ {
+ name: 'greet',
+ description: 'Greet someone by name.',
+ inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
+ },
+];
+
+async function callTool(name, args) {
+ if (name === 'greet') return \`\${settings.greeting ?? 'Hello'}, \${String(args?.name)}!\`;
+ throw new Error(\`Unknown tool \${name}\`);
+}
+
+createInterface({ input: process.stdin }).on('line', async (line) => {
+ let msg;
+ try { msg = JSON.parse(line); } catch { return; }
+ const reply = (result) => send({ jsonrpc: '2.0', id: msg.id, result });
+ const fail = (message) => send({ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message } });
+ switch (msg.method) {
+ case 'initialize':
+ return reply({ protocolVersion: '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: '${id}', version: '0.1.0' } });
+ case 'ping':
+ return reply({});
+ case 'tools/list':
+ return reply({ tools });
+ case 'tools/call':
+ try {
+ const text = await callTool(msg.params?.name, msg.params?.arguments);
+ return reply({ content: [{ type: 'text', text }] });
+ } catch (err) {
+ return reply({ content: [{ type: 'text', text: String(err?.message ?? err) }], isError: true });
+ }
+ default:
+ if (msg.id !== undefined) fail(\`Method not found: \${msg.method}\`);
+ }
+});
+`;
+
+const README = (id: string, kind: ScaffoldKind) => `# ${titleCase(id)}
+
+A Mercury ${kind} plugin.
+
+## Develop
+
+\`\`\`sh
+mercury plugins validate . # checks it the way Mercury will run it
+mercury plugins install . --yes # install this folder into your Mercury
+mercury plugins info ${id}
+\`\`\`
+
+Edit, then run \`mercury plugins install . --yes\` again: the new version
+replaces the running one (bump "version" in mercury-plugin.json).
+
+## Publish
+
+\`\`\`sh
+mercury plugins pack . # writes ${id}-<version>.tgz and prints its catalog entry
+\`\`\`
+
+Attach the .tgz to a GitHub release as \`mercury-plugin.tgz\` and anyone can
+install it with \`mercury plugins install github:<owner>/<repo>\`. To be
+listed in \`/plugins\`, open a pull request adding the printed entry to the
+Mercury plugin catalog.
+
+## Contract
+
+- Plugin API ${PLUGIN_API_VERSION} (types in \`mercury-plugin.d.ts\`). Minor
+ versions only add; a breaking change is a new major, and the previous one
+ stays supported for at least two Mercury minor releases.
+- No dependencies on other plugins.
+- Renamed or removed a setting? Bump \`settings.version\` and add a
+ \`settings.migrations\` step so saved values carry over.
+`;
+
+export function scaffoldPlugin(parent: string, id: string, kind: ScaffoldKind = 'in-process'): string {
+ if (!PLUGIN_ID_RE.test(id)) throw new Error('Plugin ids are 3-32 characters: lowercase letters, digits and hyphens, starting with a letter.');
+ const command = id.replace(/-/g, '_').slice(0, 30);
+ if (kind === 'in-process' && RESERVED_COMMANDS.has(command)) throw new Error(`"${id}" would add /${command}, which is a built-in command. Pick another id.`);
+ const dir = resolve(parent, id);
+ if (existsSync(dir) && readdirSync(dir).length) throw new Error(`${dir} already exists and isn't empty.`);
+ mkdirSync(dir, { recursive: true });
+
+ const manifest: Record<string, unknown> = {
+ manifestVersion: 1,
+ id,
+ name: titleCase(id),
+ version: '0.1.0',
+ description: `${titleCase(id)} for Mercury.`,
+ kind,
+ engines: { mercury: engineRange(), pluginApi: `^${PLUGIN_API_VERSION}` },
+ ...(kind === 'in-process' ? { entry: 'index.mjs' } : { server: { command: 'node', args: ['server.mjs'] } }),
+ contributes: {
+ tools: [{ name: 'greet', description: 'Greet someone by name.', readOnly: true }],
+ ...(kind === 'in-process' ? { commands: [{ name: command, description: `Check that ${titleCase(id)} is running` }] } : {}),
+ },
+ permissions: { network: [], secrets: [] },
+ settings: {
+ version: 1,
+ fields: { greeting: { type: 'string', description: 'How to start a greeting', default: 'Hello' } },
+ },
+ };
+ writeFileSync(join(dir, 'mercury-plugin.json'), `${JSON.stringify(manifest, null, 2)}\n`);
+ if (kind === 'in-process') {
+ writeFileSync(join(dir, 'index.mjs'), IN_PROCESS_ENTRY(id));
+ writeFileSync(join(dir, 'mercury-plugin.d.ts'), PLUGIN_SDK_DTS);
+ } else {
+ writeFileSync(join(dir, 'server.mjs'), OUT_OF_PROCESS_SERVER(id));
+ }
+ writeFileSync(join(dir, 'README.md'), README(id, kind));
+ writeFileSync(join(dir, '.gitignore'), '*.tgz\nnode_modules/\n');
+ return dir;
+}
+
+export interface PackResult {
+ file: string;
+ sha256: string;
+ size: number;
+ entry: Omit<CatalogEntry, 'tier'> & { tier: 'community' };
+}
+
+/** Build `<id>-<version>.tgz` from a plugin folder, plus its catalog entry. */
+export async function packPlugin(dir: string, outDir = process.cwd()): Promise<PackResult> {
+ const root = resolve(dir);
+ const manifest = loadManifest(root);
+ checkTree(root);
+ mkdirSync(outDir, { recursive: true });
+ const file = join(resolve(outDir), `${manifest.id}-${manifest.version}.tgz`);
+ const skip = new Set(['.git', 'node_modules', '.DS_Store']);
+ const members = readdirSync(root).filter((n) => !skip.has(n) && !n.endsWith('.tgz') && !n.endsWith('.d.ts'));
+ await execFileAsync('tar', ['-czf', file, '-C', root, ...members]);
+ const sha256 = await sha256File(file);
+ const size = statSync(file).size;
+ return {
+ file,
+ sha256,
+ size,
+ entry: {
+ id: manifest.id,
+ name: manifest.name,
+ description: manifest.description,
+ version: manifest.version,
+ kind: manifest.kind,
+ tier: 'community',
+ ...(manifest.homepage ? { homepage: manifest.homepage } : {}),
+ engines: manifest.engines,
+ artifact: { url: `https://github.com/<owner>/<repo>/releases/download/v${manifest.version}/${basename(file)}`, sha256, size },
+ tools: manifest.contributes.tools.map((t) => t.name),
+ permissions: manifest.permissions,
+ },
+ };
+}
diff --git a/src/plugins/sdk-dts.ts b/src/plugins/sdk-dts.ts
new file mode 100644
index 00000000..1a096e08
--- /dev/null
+++ b/src/plugins/sdk-dts.ts
@@ -0,0 +1,2 @@
+// Generated by scripts/gen-plugin-sdk.mjs from src/plugins/sdk.ts. Do not edit.
+export const PLUGIN_SDK_DTS = "/**\n * Plugin API 1.0: what an in-process plugin sees.\n *\n * A plugin module exports `activate(ctx)` and, optionally, `deactivate()`.\n * Everything it registers or schedules through `ctx` is torn down\n * automatically when the plugin is disabled, uninstalled or updated, so a\n * plugin that only uses the context cannot leak timers or tools.\n *\n * `mercury plugins init` writes these types into every new plugin as\n * mercury-plugin.d.ts (src/plugins/sdk-dts.ts, regenerated by\n * `node scripts/gen-plugin-sdk.mjs`; a test keeps the two in sync).\n */\n\nexport interface Disposable {\n dispose(): void;\n}\n\nexport interface PluginLogger {\n debug(message: string, data?: Record<string, unknown>): void;\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n error(message: string, data?: Record<string, unknown>): void;\n}\n\nexport interface PluginToolDefinition {\n /** Must match a tool declared in the manifest's `contributes.tools`. */\n name: string;\n /** JSON Schema (type \"object\") for the tool's arguments. */\n inputSchema: Record<string, unknown>;\n /**\n * Runs the tool. Return a string, or any JSON-serialisable value. Throwing\n * reports an error to the model; repeated failures disable the plugin.\n * `signal` aborts on timeout, on disable, and when the turn is cancelled.\n */\n execute(args: Record<string, unknown>, options: { signal: AbortSignal }): unknown | Promise<unknown>;\n}\n\nexport interface PluginCommandIO {\n /** Send a message back to whoever ran the command (terminal, Telegram, web). */\n reply(text: string): Promise<void>;\n signal: AbortSignal;\n}\n\nexport interface PluginCommandDefinition {\n /** Must match a command declared in the manifest's `contributes.commands`. Invoked as `/<name>`. */\n name: string;\n run(args: string, io: PluginCommandIO): void | Promise<void>;\n}\n\nexport interface PluginContext {\n /** Plugin API version Mercury implements, e.g. \"1.0.0\". */\n readonly apiVersion: string;\n readonly mercuryVersion: string;\n readonly plugin: {\n readonly id: string;\n readonly version: string;\n /** A folder this plugin owns. Kept across updates; deleted only on uninstall --purge. */\n readonly dataDir: string;\n };\n readonly log: PluginLogger;\n readonly settings: {\n get<T = unknown>(key: string): T | undefined;\n all(): Record<string, unknown>;\n };\n /** Only the secrets declared in the manifest's `permissions.secrets` are readable. */\n readonly secrets: {\n get(name: string): string | undefined;\n };\n readonly tools: {\n register(definition: PluginToolDefinition): Disposable;\n };\n readonly commands: {\n register(definition: PluginCommandDefinition): Disposable;\n };\n /** Tracked timers: cleared automatically on disable. Errors inside them are contained. */\n readonly timers: {\n setTimeout(fn: () => void | Promise<void>, ms: number): Disposable;\n setInterval(fn: () => void | Promise<void>, ms: number): Disposable;\n };\n /**\n * fetch() limited to the hosts declared in `permissions.network`, through\n * Mercury's SSRF guard (private and loopback addresses are blocked).\n * Requests are aborted when the plugin is disabled.\n */\n fetch(url: string, init?: RequestInit): Promise<Response>;\n /** Aborted when the plugin is being disabled, updated or uninstalled. */\n readonly signal: AbortSignal;\n /** Run cleanup when the plugin stops. */\n onDispose(fn: () => void | Promise<void>): void;\n}\n\nexport interface PluginModule {\n activate(ctx: PluginContext): void | Promise<void>;\n deactivate?(): void | Promise<void>;\n}\n";
diff --git a/src/plugins/sdk.ts b/src/plugins/sdk.ts
new file mode 100644
index 00000000..8d72a688
--- /dev/null
+++ b/src/plugins/sdk.ts
@@ -0,0 +1,95 @@
+/**
+ * Plugin API 1.0: what an in-process plugin sees.
+ *
+ * A plugin module exports `activate(ctx)` and, optionally, `deactivate()`.
+ * Everything it registers or schedules through `ctx` is torn down
+ * automatically when the plugin is disabled, uninstalled or updated, so a
+ * plugin that only uses the context cannot leak timers or tools.
+ *
+ * `mercury plugins init` writes these types into every new plugin as
+ * mercury-plugin.d.ts (src/plugins/sdk-dts.ts, regenerated by
+ * `node scripts/gen-plugin-sdk.mjs`; a test keeps the two in sync).
+ */
+
+export interface Disposable {
+ dispose(): void;
+}
+
+export interface PluginLogger {
+ debug(message: string, data?: Record<string, unknown>): void;
+ info(message: string, data?: Record<string, unknown>): void;
+ warn(message: string, data?: Record<string, unknown>): void;
+ error(message: string, data?: Record<string, unknown>): void;
+}
+
+export interface PluginToolDefinition {
+ /** Must match a tool declared in the manifest's `contributes.tools`. */
+ name: string;
+ /** JSON Schema (type "object") for the tool's arguments. */
+ inputSchema: Record<string, unknown>;
+ /**
+ * Runs the tool. Return a string, or any JSON-serialisable value. Throwing
+ * reports an error to the model; repeated failures disable the plugin.
+ * `signal` aborts on timeout, on disable, and when the turn is cancelled.
+ */
+ execute(args: Record<string, unknown>, options: { signal: AbortSignal }): unknown | Promise<unknown>;
+}
+
+export interface PluginCommandIO {
+ /** Send a message back to whoever ran the command (terminal, Telegram, web). */
+ reply(text: string): Promise<void>;
+ signal: AbortSignal;
+}
+
+export interface PluginCommandDefinition {
+ /** Must match a command declared in the manifest's `contributes.commands`. Invoked as `/<name>`. */
+ name: string;
+ run(args: string, io: PluginCommandIO): void | Promise<void>;
+}
+
+export interface PluginContext {
+ /** Plugin API version Mercury implements, e.g. "1.0.0". */
+ readonly apiVersion: string;
+ readonly mercuryVersion: string;
+ readonly plugin: {
+ readonly id: string;
+ readonly version: string;
+ /** A folder this plugin owns. Kept across updates; deleted only on uninstall --purge. */
+ readonly dataDir: string;
+ };
+ readonly log: PluginLogger;
+ readonly settings: {
+ get<T = unknown>(key: string): T | undefined;
+ all(): Record<string, unknown>;
+ };
+ /** Only the secrets declared in the manifest's `permissions.secrets` are readable. */
+ readonly secrets: {
+ get(name: string): string | undefined;
+ };
+ readonly tools: {
+ register(definition: PluginToolDefinition): Disposable;
+ };
+ readonly commands: {
+ register(definition: PluginCommandDefinition): Disposable;
+ };
+ /** Tracked timers: cleared automatically on disable. Errors inside them are contained. */
+ readonly timers: {
+ setTimeout(fn: () => void | Promise<void>, ms: number): Disposable;
+ setInterval(fn: () => void | Promise<void>, ms: number): Disposable;
+ };
+ /**
+ * fetch() limited to the hosts declared in `permissions.network`, through
+ * Mercury's SSRF guard (private and loopback addresses are blocked).
+ * Requests are aborted when the plugin is disabled.
+ */
+ fetch(url: string, init?: RequestInit): Promise<Response>;
+ /** Aborted when the plugin is being disabled, updated or uninstalled. */
+ readonly signal: AbortSignal;
+ /** Run cleanup when the plugin stops. */
+ onDispose(fn: () => void | Promise<void>): void;
+}
+
+export interface PluginModule {
+ activate(ctx: PluginContext): void | Promise<void>;
+ deactivate?(): void | Promise<void>;
+}
diff --git a/src/plugins/service.ts b/src/plugins/service.ts
new file mode 100644
index 00000000..136f9fce
--- /dev/null
+++ b/src/plugins/service.ts
@@ -0,0 +1,112 @@
+/**
+ * One interface for "change plugins", whichever process you're in.
+ *
+ * Plugins only ever run in the process that owns the runtime (the daemon,
+ * or a standalone foreground runtime; ADR-024). Everything else, a
+ * `mercury plugins …` CLI call or a terminal attached beside a running
+ * daemon, forwards each operation to that process over the authenticated
+ * loopback API, so the daemon stops/starts plugins itself and two
+ * processes never run the same plugin. When no daemon is running, the
+ * operation is done on disk directly and takes effect at the next start.
+ */
+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';
+
+export interface ListResult {
+ items: PluginListItem[];
+ catalogError?: string;
+ stale: boolean;
+ safeMode: boolean;
+}
+
+export interface InstallSummary {
+ id: string;
+ name: string;
+ version: string;
+ previousVersion?: string;
+ verified: boolean;
+ unchanged: boolean;
+ tier: 'official' | 'community' | 'local';
+}
+
+export interface PluginService {
+ /** "local" runs plugins here; "daemon" forwards to it; "offline" edits disk only. */
+ readonly mode: 'local' | 'daemon' | 'offline';
+ list(refresh?: boolean): Promise<ListResult>;
+ info(id: string): Promise<PluginListItem | null>;
+ install(source: string, opts?: { enable?: boolean; force?: boolean }): Promise<InstallSummary>;
+ enable(id: string): Promise<void>;
+ disable(id: string): Promise<void>;
+ update(id?: string): Promise<Array<{ id: string; from: string; to: string }>>;
+ rollback(id: string): Promise<{ from: string; to: string }>;
+ uninstall(id: string, purge?: boolean): Promise<void>;
+ setSetting(id: string, key: string, value: unknown): Promise<void>;
+}
+
+export function localService(mgr: PluginManager, mode: 'local' | 'offline' = 'local'): PluginService {
+ return {
+ mode,
+ list: (refresh) => mgr.list({ refresh }),
+ info: (id) => mgr.info(id),
+ install: async (source, opts) => {
+ const r = await mgr.install(source, opts);
+ return { id: r.id, name: r.manifest.name, version: r.version, previousVersion: r.previousVersion, verified: r.verified, unchanged: r.unchanged, tier: r.tier };
+ },
+ enable: (id) => mgr.enable(id),
+ disable: (id) => mgr.disable(id),
+ update: (id) => mgr.update(id),
+ rollback: (id) => mgr.rollback(id),
+ uninstall: (id, purge) => mgr.uninstall(id, { purge }),
+ setSetting: (id, key, value) => mgr.setSetting(id, key, value),
+ };
+}
+
+async function call<T>(method: string, path: string, body?: unknown, timeoutMs = 60_000): Promise<T> {
+ const token = readAttachToken();
+ if (!token) throw new Error('Mercury is running in the background but its local API token is missing. Try `mercury restart`.');
+ let res: Response;
+ try {
+ res = await fetch(`http://127.0.0.1:${getWebPort()}${path}`, {
+ method,
+ headers: { Authorization: `Bearer ${token}`, 'content-type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ } catch (err) {
+ throw new Error(`Couldn't reach the background Mercury (${(err as Error).message}).`);
+ }
+ const data = (await res.json().catch(() => ({}))) as { error?: string } & T;
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
+ return data;
+}
+
+export function daemonService(): PluginService {
+ const enc = encodeURIComponent;
+ return {
+ mode: 'daemon',
+ list: (refresh) => call<ListResult>('GET', `/api/plugins${refresh ? '?refresh=1' : ''}`),
+ info: async (id) => (await call<{ plugin: PluginListItem | null }>('GET', `/api/plugins/${enc(id)}`)).plugin,
+ install: (source, opts) => call<InstallSummary>('POST', '/api/plugins/install', { source, ...opts }, 10 * 60_000),
+ enable: async (id) => { await call('POST', `/api/plugins/${enc(id)}/enable`); },
+ disable: async (id) => { await call('POST', `/api/plugins/${enc(id)}/disable`); },
+ update: async (id) => (await call<{ changed: Array<{ id: string; from: string; to: string }> }>('POST', `/api/plugins/${id ? `${enc(id)}/` : ''}update`, {}, 10 * 60_000)).changed,
+ 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 }); },
+ };
+}
+
+/**
+ * The right service for this process: local when we run plugins, the
+ * daemon when one is running, otherwise on-disk only.
+ */
+export function getPluginService(): PluginService {
+ const mgr = getPluginManager();
+ if (mgr.runsPlugins()) return localService(mgr);
+ // Whichever process owns the runtime (daemon, or a foreground `mercury
+ // start -f`) serves the API and runs the plugins.
+ if (getDaemonStatus().running || getForegroundRuntimeStatus().running) return daemonService();
+ return localService(mgr, 'offline');
+}
diff --git a/src/plugins/store.ts b/src/plugins/store.ts
new file mode 100644
index 00000000..da6fe11e
--- /dev/null
+++ b/src/plugins/store.ts
@@ -0,0 +1,328 @@
+/**
+ * On-disk layout and state for plugins.
+ *
+ * ~/.mercury/plugins/
+ * state.json which plugins are installed / enabled (atomic writes)
+ * catalog-cache.json last catalog fetched, so /plugins works offline
+ * .lock install/uninstall lock (CLI and daemon share it)
+ * .staging/ scratch space for installs; never read by the loader
+ * <id>/
+ * versions/<version>/ the installed package (current + one previous)
+ * data/ plugin-owned data, kept across updates
+ * settings.json owner settings, kept across updates
+ */
+import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import semver from 'semver';
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { getMercuryHome } from '../utils/config.js';
+import { logger } from '../utils/logger.js';
+import {
+ MANIFEST_VERSION, PLUGIN_API_VERSION, PLUGIN_ID_RE,
+ type PluginManifest, type PluginsState, type PlatformKey,
+} from './types.js';
+
+export function pluginsRoot(): string {
+ return join(getMercuryHome(), 'plugins');
+}
+export function pluginDir(id: string): string {
+ assertId(id);
+ return join(pluginsRoot(), id);
+}
+export function pluginVersionDir(id: string, version: string): string {
+ return join(pluginDir(id), 'versions', version);
+}
+export function pluginDataDir(id: string): string {
+ return join(pluginDir(id), 'data');
+}
+export function pluginSettingsPath(id: string): string {
+ return join(pluginDir(id), 'settings.json');
+}
+export function stagingRoot(): string {
+ return join(pluginsRoot(), '.staging');
+}
+
+export function assertId(id: string): void {
+ if (!PLUGIN_ID_RE.test(id)) throw new Error(`Invalid plugin id "${id}"`);
+}
+
+// ── platform and compatibility ─────────────────────────────────────────────
+
+export function currentPlatform(): PlatformKey {
+ const os = process.platform === 'android' ? 'android' : process.platform;
+ return `${os}-${process.arch}` as PlatformKey;
+}
+
+/** Mercury's own version: stamped into compiled builds, else package.json. */
+export function mercuryVersion(): string {
+ const stamped = (globalThis as { __MERCURY_VERSION__?: string }).__MERCURY_VERSION__;
+ if (stamped) return stamped;
+ return process.env.MERCURY_VERSION_OVERRIDE ?? packageVersion();
+}
+
+let cachedPkgVersion: string | null = null;
+function packageVersion(): string {
+ if (cachedPkgVersion) return cachedPkgVersion;
+ let here = process.cwd();
+ try { here = dirname(fileURLToPath(import.meta.url)); } catch { /* compiled binary: virtual path */ }
+ const candidates = [join(here, '..', '..', 'package.json'), join(here, '..', 'package.json'), join(process.cwd(), 'package.json')];
+ for (const p of candidates) {
+ try {
+ const pkg = JSON.parse(readFileSync(p, 'utf8')) as { name?: string; version?: string };
+ if (pkg.name === '@cosmicstack/mercury-agent' && pkg.version) return (cachedPkgVersion = pkg.version);
+ } catch { /* next */ }
+ }
+ return (cachedPkgVersion = '0.0.0');
+}
+
+/**
+ * Why a manifest can't run here, or null if it can. Pre-release Mercury
+ * builds (dev channel) are matched as their release version.
+ */
+export function incompatibility(manifest: Pick<PluginManifest, 'engines' | 'platforms'> & { manifestVersion?: number }): string | null {
+ if (manifest.manifestVersion !== undefined && manifest.manifestVersion !== MANIFEST_VERSION) {
+ return `manifest version ${manifest.manifestVersion} is not supported (this Mercury reads version ${MANIFEST_VERSION})`;
+ }
+ const mv = semver.coerce(mercuryVersion())?.version ?? '0.0.0';
+ if (!semver.satisfies(mv, manifest.engines.mercury, { includePrerelease: true })) {
+ return `needs Mercury ${manifest.engines.mercury}, this is ${mv}`;
+ }
+ const api = manifest.engines.pluginApi ?? '^1.0.0';
+ if (!semver.satisfies(PLUGIN_API_VERSION, api)) {
+ return `needs plugin API ${api}, this Mercury provides ${PLUGIN_API_VERSION}`;
+ }
+ if (manifest.platforms && !manifest.platforms.includes(currentPlatform())) {
+ return `not available for ${currentPlatform()} (supports ${manifest.platforms.join(', ')})`;
+ }
+ return null;
+}
+
+// ── state ─────────────────────────────────────────────────────────────────
+
+function emptyState(): PluginsState {
+ return { stateVersion: 1, plugins: {}, boot: { inProgress: false, failedBoots: 0 } };
+}
+
+function statePath(): string {
+ return join(pluginsRoot(), 'state.json');
+}
+
+/** Read state.json. A missing or corrupt file never throws: corrupt files are set aside. */
+export function readState(): PluginsState {
+ const path = statePath();
+ if (!existsSync(path)) return emptyState();
+ try {
+ const raw = JSON.parse(readFileSync(path, 'utf8')) as Partial<PluginsState>;
+ if (raw.stateVersion !== 1 || typeof raw.plugins !== 'object' || raw.plugins === null) throw new Error('unexpected shape');
+ const plugins: PluginsState['plugins'] = {};
+ for (const [id, entry] of Object.entries(raw.plugins)) {
+ if (PLUGIN_ID_RE.test(id) && entry && typeof entry.version === 'string') plugins[id] = entry;
+ }
+ return {
+ stateVersion: 1,
+ plugins,
+ boot: {
+ inProgress: raw.boot?.inProgress === true,
+ failedBoots: Number.isInteger(raw.boot?.failedBoots) ? raw.boot!.failedBoots : 0,
+ lastChange: raw.boot?.lastChange,
+ },
+ };
+ } catch (err) {
+ const aside = `${path}.corrupt-${Date.now()}`;
+ try { renameSync(path, aside); } catch { /* ignore */ }
+ logger.warn({ err, aside }, 'Plugin state was unreadable; set it aside and started empty (no plugins load)');
+ return emptyState();
+ }
+}
+
+/** Atomic write: temp file + rename, so a crash mid-write can't corrupt state. */
+export function writeState(state: PluginsState): void {
+ mkdirSync(pluginsRoot(), { recursive: true });
+ writeJsonAtomic(statePath(), state);
+}
+
+export function writeJsonAtomic(path: string, data: unknown): void {
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
+ writeFileSync(tmp, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600 });
+ renameSync(tmp, path);
+}
+
+/** Read-modify-write under the install lock. */
+export async function updateState(mutate: (s: PluginsState) => void): Promise<PluginsState> {
+ return withLock(async () => {
+ const s = readState();
+ mutate(s);
+ writeState(s);
+ return s;
+ });
+}
+
+// ── lock ──────────────────────────────────────────────────────────────────
+
+const LOCK_STALE_MS = 10 * 60 * 1000;
+
+function lockPath(): string {
+ return join(pluginsRoot(), '.lock');
+}
+
+function pidAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (err) {
+ return (err as NodeJS.ErrnoException).code === 'EPERM';
+ }
+}
+
+/**
+ * Lock for anything that changes plugins on disk.
+ * - Across processes: an exclusive lock file (the daemon and a
+ * `mercury plugins …` CLI call can run at the same time). Stale locks
+ * (dead pid, or older than 10 minutes) are taken over.
+ * - Within a process: a queue, so concurrent async callers run one at a time.
+ * - Re-entrant only for genuinely nested calls (same async context), via
+ * AsyncLocalStorage, never for unrelated concurrent work.
+ */
+const lockContext = new AsyncLocalStorage<boolean>();
+let lockQueue: Promise<unknown> = Promise.resolve();
+
+export async function withLock<T>(fn: () => Promise<T>, timeoutMs = 30_000): Promise<T> {
+ if (lockContext.getStore()) return fn();
+ const run = async (): Promise<T> => {
+ await acquireFileLock(timeoutMs);
+ try {
+ return await lockContext.run(true, fn);
+ } finally {
+ try { rmSync(lockPath(), { force: true }); } catch { /* ignore */ }
+ }
+ };
+ const result = lockQueue.then(run, run);
+ lockQueue = result.catch(() => {});
+ return result;
+}
+
+async function acquireFileLock(timeoutMs: number): Promise<void> {
+ mkdirSync(pluginsRoot(), { recursive: true });
+ const path = lockPath();
+ const started = Date.now();
+ for (;;) {
+ try {
+ const fd = openSync(path, 'wx', 0o600);
+ writeSync(fd, String(process.pid));
+ closeSync(fd);
+ return;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;
+ let stale = false;
+ try {
+ const pid = Number(readFileSync(path, 'utf8').trim());
+ const age = Date.now() - statSync(path).mtimeMs;
+ stale = !Number.isInteger(pid) || pid <= 0 || !pidAlive(pid) || age > LOCK_STALE_MS;
+ } catch {
+ stale = true;
+ }
+ if (stale) {
+ try { rmSync(path, { force: true }); } catch { /* raced */ }
+ continue;
+ }
+ if (Date.now() - started > timeoutMs) throw new Error('Another plugin install or uninstall is in progress. Try again in a moment.');
+ await new Promise((r) => setTimeout(r, 150));
+ }
+ }
+}
+
+// ── settings ──────────────────────────────────────────────────────────────
+
+interface SettingsFile {
+ settingsVersion: number;
+ values: Record<string, unknown>;
+}
+
+function readSettingsFile(path: string): SettingsFile | null {
+ try {
+ const raw = JSON.parse(readFileSync(path, 'utf8')) as Partial<SettingsFile>;
+ const values = raw.values && typeof raw.values === 'object' && !Array.isArray(raw.values) ? raw.values : {};
+ const v = Number.isInteger(raw.settingsVersion) && (raw.settingsVersion as number) >= 1 ? (raw.settingsVersion as number) : 1;
+ return { settingsVersion: v, values };
+ } catch {
+ return null;
+ }
+}
+
+export function readSettings(id: string): Record<string, unknown> {
+ return readSettingsFile(pluginSettingsPath(id))?.values ?? {};
+}
+
+/** Saved settings from `from` brought up to the manifest's settings version. */
+export function migrateSettingValues(manifest: PluginManifest, values: Record<string, unknown>, from: number): Record<string, unknown> {
+ const out = { ...values };
+ for (const step of manifest.settings?.migrations ?? []) {
+ if (step.to <= from) continue;
+ for (const [oldKey, newKey] of Object.entries(step.rename)) {
+ if (oldKey in out) {
+ if (!(newKey in out)) out[newKey] = out[oldKey];
+ delete out[oldKey];
+ }
+ }
+ for (const key of step.remove) delete out[key];
+ for (const [key, map] of Object.entries(step.mapValues)) {
+ const v = out[key];
+ if ((typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') && Object.prototype.hasOwnProperty.call(map, String(v))) {
+ out[key] = map[String(v)];
+ }
+ }
+ }
+ return out;
+}
+
+/**
+ * Bring settings.json up to this version's settings version, once, before
+ * the plugin starts. The file being replaced is kept as
+ * `settings.v<N>.json`, so a rollback to the older plugin finds its own
+ * settings again instead of values it doesn't understand.
+ */
+export function migrateSettings(manifest: PluginManifest): { from: number; to: number } | null {
+ const target = manifest.settings?.version ?? 1;
+ const path = pluginSettingsPath(manifest.id);
+ const saved = readSettingsFile(path);
+ if (!saved || saved.settingsVersion === target) return null;
+ const backup = (v: number) => join(pluginDir(manifest.id), `settings.v${v}.json`);
+ writeJsonAtomic(backup(saved.settingsVersion), saved);
+ if (saved.settingsVersion > target) {
+ // Rolled back to an older plugin: restore that version's saved settings if we have them.
+ const older = readSettingsFile(backup(target));
+ writeJsonAtomic(path, older && older.settingsVersion === target ? older : { settingsVersion: target, values: {} });
+ } else {
+ writeJsonAtomic(path, { settingsVersion: target, values: migrateSettingValues(manifest, saved.values, saved.settingsVersion) });
+ }
+ return { from: saved.settingsVersion, to: target };
+}
+
+/**
+ * Settings with defaults filled in and values coerced to the declared types.
+ * Unknown keys are dropped, so a plugin never sees a value its manifest
+ * doesn't describe. Older saved versions are migrated in memory first.
+ */
+export function resolvedSettings(manifest: PluginManifest): Record<string, unknown> {
+ const fields = manifest.settings?.fields ?? {};
+ const file = readSettingsFile(pluginSettingsPath(manifest.id));
+ const target = manifest.settings?.version ?? 1;
+ const saved = !file ? {} : file.settingsVersion < target ? migrateSettingValues(manifest, file.values, file.settingsVersion) : file.settingsVersion > target ? {} : file.values;
+ const out: Record<string, unknown> = {};
+ for (const [key, field] of Object.entries(fields)) {
+ const v = saved[key];
+ let value: unknown = field.default;
+ if (field.type === 'boolean' && typeof v === 'boolean') value = v;
+ else if (field.type === 'number' && typeof v === 'number' && Number.isFinite(v)) value = v;
+ else if (field.type === 'string' && typeof v === 'string') value = v;
+ else if (field.type === 'enum' && typeof v === 'string' && field.options?.includes(v)) value = v;
+ if (value !== undefined) out[key] = value;
+ }
+ return out;
+}
+
+export function writeSettings(id: string, values: Record<string, unknown>, settingsVersion: number): void {
+ mkdirSync(pluginDir(id), { recursive: true });
+ writeJsonAtomic(pluginSettingsPath(id), { settingsVersion, values });
+}
diff --git a/src/plugins/test-fixtures.ts b/src/plugins/test-fixtures.ts
new file mode 100644
index 00000000..e551a8bc
--- /dev/null
+++ b/src/plugins/test-fixtures.ts
@@ -0,0 +1,152 @@
+/**
+ * Test fixtures for the plugin system: throwaway MERCURY_HOME, and plugin
+ * packages that behave well or badly on purpose. Used only by *.test.ts.
+ */
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+export function tempHome(): { home: string; restore: () => void } {
+ // Inside the repo: Vitest's module runner can only import files under the
+ // project root, and in-process plugins are loaded with import().
+ const base = join(process.cwd(), '.vitest-tmp');
+ mkdirSync(base, { recursive: true });
+ const home = mkdtempSync(join(base, 'mercury-plugins-'));
+ const prev = process.env.MERCURY_HOME;
+ const prevCatalog = process.env.MERCURY_PLUGIN_CATALOG_URL;
+ process.env.MERCURY_HOME = home;
+ process.env.MERCURY_PLUGIN_CATALOG_URL = 'off';
+ return {
+ home,
+ restore: () => {
+ if (prev === undefined) delete process.env.MERCURY_HOME;
+ else process.env.MERCURY_HOME = prev;
+ if (prevCatalog === undefined) delete process.env.MERCURY_PLUGIN_CATALOG_URL;
+ else process.env.MERCURY_PLUGIN_CATALOG_URL = prevCatalog;
+ rmSync(home, { recursive: true, force: true });
+ },
+ };
+}
+
+export interface FixtureOptions {
+ id?: string;
+ version?: string;
+ engines?: { mercury: string; pluginApi?: string };
+ manifest?: Record<string, unknown>;
+ /** Source of index.mjs for in-process plugins. */
+ code?: string;
+ tools?: Array<{ name: string; description?: string; readOnly?: boolean; timeoutMs?: number }>;
+ commands?: Array<{ name: string; description?: string }>;
+ network?: string[];
+ secrets?: string[];
+}
+
+/** An in-process plugin folder. Default code registers every declared tool as an echo. */
+export function inProcessPlugin(root: string, opts: FixtureOptions = {}): string {
+ const id = opts.id ?? 'echo-tools';
+ const dir = join(root, `${id}-${opts.version ?? '1.0.0'}`);
+ mkdirSync(dir, { recursive: true });
+ const tools = opts.tools ?? [{ name: 'echo', description: 'Echo the input back', readOnly: true }];
+ const manifest = {
+ manifestVersion: 1,
+ id,
+ name: `Fixture ${id}`,
+ version: opts.version ?? '1.0.0',
+ description: 'A test fixture plugin',
+ kind: 'in-process',
+ engines: opts.engines ?? { mercury: '>=1.0.0' },
+ entry: 'index.mjs',
+ contributes: {
+ tools: tools.map((t) => ({ description: 'fixture tool', ...t })),
+ commands: (opts.commands ?? []).map((c) => ({ description: 'fixture command', ...c })),
+ },
+ permissions: { network: opts.network ?? [], secrets: opts.secrets ?? [] },
+ ...opts.manifest,
+ };
+ writeFileSync(join(dir, 'mercury-plugin.json'), JSON.stringify(manifest, null, 2));
+ const code = opts.code ?? `
+export async function activate(ctx) {
+ for (const name of ${JSON.stringify(tools.map((t) => t.name))}) {
+ ctx.tools.register({
+ name,
+ inputSchema: { type: 'object', properties: { text: { type: 'string' } } },
+ execute: async (args) => \`\${name}: \${args.text ?? ''}\`,
+ });
+ }
+}`;
+ writeFileSync(join(dir, 'index.mjs'), code);
+ return dir;
+}
+
+/**
+ * A minimal MCP stdio server. Behaviour is controlled by env vars the test
+ * sets in the plugin's settings (passed as MERCURY_PLUGIN_SETTINGS):
+ * mode = "ok" | "crash-on-call" | "hang-on-call" | "crash-at-start" | "no-handshake"
+ */
+export const MCP_SERVER_SOURCE = `
+const settings = JSON.parse(process.env.MERCURY_PLUGIN_SETTINGS || '{}');
+const mode = settings.mode || 'ok';
+if (mode === 'crash-at-start') { process.stderr.write('boom at start\\n'); process.exit(3); }
+const rl = require('node:readline').createInterface({ input: process.stdin });
+const send = (m) => process.stdout.write(JSON.stringify(m) + '\\n');
+rl.on('line', (line) => {
+ let msg; try { msg = JSON.parse(line); } catch { return; }
+ if (msg.method === 'initialize') {
+ if (mode === 'no-handshake') return;
+ return send({ jsonrpc: '2.0', id: msg.id, result: { protocolVersion: '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'fixture', version: '1.0.0' } } });
+ }
+ if (msg.method === 'tools/list') {
+ return send({ jsonrpc: '2.0', id: msg.id, result: { tools: [
+ { name: 'add', description: 'add numbers', inputSchema: { type: 'object', properties: { a: { type: 'number' }, b: { type: 'number' } } } },
+ { name: 'secret', description: 'read a secret', inputSchema: { type: 'object', properties: {} } },
+ { name: 'undeclared', description: 'not in manifest', inputSchema: { type: 'object' } },
+ ] } });
+ }
+ if (msg.method === 'tools/call') {
+ if (mode === 'crash-on-call') process.exit(5);
+ if (mode === 'hang-on-call') return;
+ const { name, arguments: a } = msg.params;
+ if (name === 'add') return send({ jsonrpc: '2.0', id: msg.id, result: { content: [{ type: 'text', text: String((a.a || 0) + (a.b || 0)) }] } });
+ if (name === 'secret') return send({ jsonrpc: '2.0', id: msg.id, result: { content: [{ type: 'text', text: JSON.stringify({ declared: process.env.FIXTURE_TOKEN || null, leaked: process.env.OTHER_SECRET || null }) }] } });
+ return send({ jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'unknown tool' } });
+ }
+});
+`;
+
+export function outOfProcessPlugin(root: string, opts: FixtureOptions & { mode?: string } = {}): string {
+ const id = opts.id ?? 'mcp-math';
+ const dir = join(root, `${id}-${opts.version ?? '1.0.0'}`);
+ mkdirSync(dir, { recursive: true });
+ const manifest = {
+ manifestVersion: 1,
+ id,
+ name: `Fixture ${id}`,
+ version: opts.version ?? '1.0.0',
+ description: 'A test fixture MCP plugin',
+ kind: 'out-of-process',
+ engines: opts.engines ?? { mercury: '>=1.0.0' },
+ server: { command: 'node', args: ['server.cjs'] },
+ contributes: {
+ tools: (opts.tools ?? [
+ { name: 'add', description: 'Add two numbers', readOnly: true, timeoutMs: 2000 },
+ { name: 'secret', description: 'Read the declared secret', readOnly: true, timeoutMs: 2000 },
+ ]).map((t) => ({ description: 'fixture', ...t })),
+ commands: [],
+ },
+ permissions: { network: [], secrets: opts.secrets ?? ['FIXTURE_TOKEN'] },
+ settings: { version: 1, fields: { mode: { type: 'string', default: opts.mode ?? 'ok' } } },
+ ...opts.manifest,
+ };
+ writeFileSync(join(dir, 'mercury-plugin.json'), JSON.stringify(manifest, null, 2));
+ writeFileSync(join(dir, 'server.cjs'), MCP_SERVER_SOURCE);
+ return dir;
+}
+
+export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+export async function waitFor(check: () => boolean, timeoutMs = 5000, stepMs = 25): Promise<void> {
+ const start = Date.now();
+ while (!check()) {
+ if (Date.now() - start > timeoutMs) throw new Error('waitFor timed out');
+ await sleep(stepMs);
+ }
+}
diff --git a/src/plugins/tool-bridge.ts b/src/plugins/tool-bridge.ts
new file mode 100644
index 00000000..8a8250b2
--- /dev/null
+++ b/src/plugins/tool-bridge.ts
@@ -0,0 +1,187 @@
+/**
+ * The bridge between running plugins and Mercury's tool loop.
+ *
+ * Runtimes (in-process and out-of-process) publish their tools here; every
+ * CapabilityRegistry (the main agent's, sub-agents', and each bot's) reads
+ * them on every turn through `getPluginTools()`. Each call is wrapped:
+ * approval → timeout + cancellation → error capture → result size cap,
+ * and the outcome is reported to the plugin manager's circuit breaker.
+ *
+ * Tool names are namespaced as `<plugin-id>__<tool>`. Built-in tools never
+ * contain "__", so the name alone identifies a plugin tool.
+ */
+import { jsonSchema, tool, type Tool } from 'ai';
+import type { PermissionManager } from '../capabilities/permissions.js';
+import { logger } from '../utils/logger.js';
+
+export interface LiveTool {
+ pluginId: string;
+ pluginName: string;
+ /** Name declared in the manifest (without namespace). */
+ name: string;
+ description: string;
+ inputSchema: Record<string, unknown>;
+ readOnly: boolean;
+ timeoutMs: number;
+ invoke(args: Record<string, unknown>, signal: AbortSignal): Promise<unknown>;
+}
+
+export interface PluginCommandHandler {
+ pluginId: string;
+ pluginName: string;
+ name: string;
+ description: string;
+ run(args: string, io: { reply(text: string): Promise<void>; signal: AbortSignal }): Promise<void>;
+}
+
+const MAX_RESULT_CHARS = 100_000;
+const TOOL_NAME_RE = /^([a-z][a-z0-9-]{1,30}[a-z0-9])__([a-z][a-z0-9_]{0,29})$/;
+
+const liveTools = new Map<string, LiveTool>();
+const liveCommands = new Map<string, PluginCommandHandler>();
+
+type OutcomeSink = (pluginId: string, outcome: { ok: true } | { ok: false; error: string; timeout: boolean }) => void;
+let outcomeSink: OutcomeSink = () => {};
+
+export function setToolOutcomeSink(sink: OutcomeSink): void {
+ outcomeSink = sink;
+}
+
+export function pluginToolName(pluginId: string, name: string): string {
+ return `${pluginId}__${name}`;
+}
+
+/** True for any name shaped like a plugin tool, live or not. */
+export function isPluginToolName(name: string): boolean {
+ return TOOL_NAME_RE.test(name);
+}
+
+/** A bot may use a plugin tool only when its allow list names it, or the whole plugin ("<id>__*"). */
+export function pluginToolAllowed(name: string, allow: readonly string[]): boolean {
+ const m = TOOL_NAME_RE.exec(name);
+ if (!m) return false;
+ return allow.includes(name) || allow.includes(`${m[1]}__*`);
+}
+
+/** Publish a tool; returns its removal. A later registration with the same name replaces it. */
+export function publishTool(t: LiveTool): () => void {
+ const full = pluginToolName(t.pluginId, t.name);
+ liveTools.set(full, t);
+ return () => {
+ if (liveTools.get(full) === t) liveTools.delete(full);
+ };
+}
+
+export function publishCommand(c: PluginCommandHandler): () => void {
+ liveCommands.set(c.name, c);
+ return () => {
+ if (liveCommands.get(c.name) === c) liveCommands.delete(c.name);
+ };
+}
+
+/** Remove everything a plugin published (used when it stops, however it stops). */
+export function unpublishPlugin(pluginId: string): void {
+ for (const [name, t] of liveTools) if (t.pluginId === pluginId) liveTools.delete(name);
+ for (const [name, c] of liveCommands) if (c.pluginId === pluginId) liveCommands.delete(name);
+}
+
+export function listLiveTools(): LiveTool[] {
+ return [...liveTools.values()];
+}
+
+export function getPluginCommand(name: string): PluginCommandHandler | undefined {
+ return liveCommands.get(name);
+}
+
+export function listPluginCommands(): PluginCommandHandler[] {
+ return [...liveCommands.values()];
+}
+
+function stringifyResult(value: unknown): string {
+ let text: string;
+ if (typeof value === 'string') text = value;
+ else if (value === undefined || value === null) text = 'Done.';
+ else {
+ try {
+ text = JSON.stringify(value, null, 2);
+ } catch {
+ text = String(value);
+ }
+ }
+ return text.length > MAX_RESULT_CHARS ? `${text.slice(0, MAX_RESULT_CHARS)}\n[…truncated ${text.length - MAX_RESULT_CHARS} characters]` : text;
+}
+
+function describeArgs(args: Record<string, unknown>): string {
+ let s: string;
+ try {
+ s = JSON.stringify(args);
+ } catch {
+ s = '[unserialisable arguments]';
+ }
+ return s.length > 400 ? `${s.slice(0, 400)}…` : s;
+}
+
+/**
+ * Wrap a live tool for the AI SDK. The returned tool never throws: errors,
+ * timeouts and denials come back as text the model can act on.
+ */
+function wrap(t: LiveTool, permissions: PermissionManager): Tool {
+ const full = pluginToolName(t.pluginId, t.name);
+ return tool<Record<string, unknown>, string>({
+ description: `[Plugin: ${t.pluginName}] ${t.description}`,
+ inputSchema: jsonSchema<Record<string, unknown>>(t.inputSchema as Parameters<typeof jsonSchema>[0]),
+ execute: async (input, options) => {
+ const args = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;
+ if (!t.readOnly) {
+ const approved = await permissions.approvePluginTool(full, `Run plugin tool ${t.pluginName} → ${t.name} with ${describeArgs(args)}`);
+ if (!approved) return `Not run: the plugin tool ${full} was not approved.`;
+ }
+ const ac = new AbortController();
+ const onOuterAbort = () => ac.abort(new Error('cancelled'));
+ options?.abortSignal?.addEventListener('abort', onOuterAbort, { once: true });
+ let timedOut = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ timedOut = true;
+ ac.abort(new Error('timeout'));
+ reject(new Error(`timed out after ${Math.round(t.timeoutMs / 1000)}s`));
+ }, t.timeoutMs);
+ });
+ try {
+ const result = await Promise.race([Promise.resolve().then(() => t.invoke(args, ac.signal)), timeout]);
+ outcomeSink(t.pluginId, { ok: true });
+ return stringifyResult(result);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ if (!options?.abortSignal?.aborted) outcomeSink(t.pluginId, { ok: false, error: message, timeout: timedOut });
+ logger.warn({ plugin: t.pluginId, tool: t.name, err: message, timedOut }, 'Plugin tool failed');
+ return `Error from plugin tool ${full}: ${message}`;
+ } finally {
+ if (timer) clearTimeout(timer);
+ options?.abortSignal?.removeEventListener('abort', onOuterAbort);
+ }
+ },
+ });
+}
+
+/** Live plugin tools as AI SDK tools, wired to this registry's permission manager. */
+export function getPluginTools(permissions: PermissionManager, opts: { readOnlyOnly?: boolean } = {}): Record<string, Tool> {
+ const out: Record<string, Tool> = {};
+ for (const [full, t] of liveTools) {
+ if (opts.readOnlyOnly && !t.readOnly) continue;
+ try {
+ out[full] = wrap(t, permissions);
+ } catch (err) {
+ logger.warn({ plugin: t.pluginId, tool: t.name, err }, 'Plugin tool has an unusable input schema; skipped');
+ }
+ }
+ return out;
+}
+
+/** Test hook. */
+export function resetToolBridge(): void {
+ liveTools.clear();
+ liveCommands.clear();
+ outcomeSink = () => {};
+}
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
new file mode 100644
index 00000000..3c27a8c4
--- /dev/null
+++ b/src/plugins/types.ts
@@ -0,0 +1,270 @@
+/**
+ * Mercury plugin system: manifest v1, plugin API v1 and on-disk state.
+ *
+ * A plugin is a folder with a `mercury-plugin.json` manifest. It is either
+ * - in-process: one self-contained ES module loaded into the daemon with
+ * `import()`, talking to Mercury only through the `PluginContext` it is
+ * given in `activate(ctx)`; or
+ * - out-of-process: a child process speaking MCP (JSON-RPC 2.0) over stdio.
+ * A crash or hang there can never take the daemon down.
+ *
+ * In-process plugins must be bundled into a single file: a compiled Mercury
+ * binary cannot resolve packages for them (verified: `import 'zod'` from a
+ * plugin fails inside `bun build --compile` output). Anything a plugin needs
+ * from Mercury comes through the context.
+ */
+import { z } from 'zod';
+import semver from 'semver';
+
+/** Manifest format version this Mercury understands. */
+export const MANIFEST_VERSION = 1 as const;
+
+/**
+ * Plugin API (the PluginContext / MCP contract) this Mercury implements.
+ * 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_ID_RE = /^[a-z][a-z0-9-]{1,30}[a-z0-9]$/;
+/** Tool and command names a plugin declares (before namespacing). */
+export const PLUGIN_TOOL_NAME_RE = /^[a-z][a-z0-9_]{0,29}$/;
+/**
+ * Built-in command names a plugin can never take. Kept in sync with the
+ * TUI's SLASH_COMMANDS by src/plugins/commands.test.ts.
+ */
+export const RESERVED_COMMANDS: ReadonlySet<string> = new Set([
+ 'agents', 'bg', 'bot', 'bots', 'budget', 'chat', 'cloud', 'code', 'halt', 'help', 'log', 'memory', 'menu', 'models', 'model',
+ 'permissions', 'plugin', 'plugins', 'progress', 'research', 'reset', 'saver', 'session', 'sessions', 'skills', 'spotify',
+ 'status', 'stop', 'stream', 'tools', 'update', 'view', 'whatsnew', 'ws', 'start', 'skip', 'new', 'compact', 'clear',
+ 'approve', 'deny', 'yes', 'no', 'cancel', 'pair', 'unpair', 'telegram', 'discord', 'slack', 'signal', 'web', 'exit', 'quit',
+ 'usage', 'cost', 'doctor', 'settings', 'config', 'login', 'logout', 'upgrade', 'version', 'about',
+]);
+
+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',
+] as const;
+export type PlatformKey = (typeof PLATFORM_KEYS)[number];
+
+/** Relative path inside the plugin folder: no absolute paths, no `..`. */
+const relPath = z.string().min(1).max(200).refine(
+ (p) => !p.startsWith('/') && !/^[a-zA-Z]:/.test(p) && !p.split(/[\\/]/).includes('..') && !p.includes('\0'),
+ 'must be a relative path inside the plugin folder',
+);
+
+const strictSemver = z.string().refine((v) => semver.valid(v) !== null && semver.clean(v) === v, 'must be a semver version like 1.2.3');
+const semverRange = z.string().min(1).max(100).refine((r) => semver.validRange(r) !== null, 'must be a semver range like ">=1.4.0 <2.0.0"');
+
+const toolDecl = z.object({
+ name: z.string().regex(PLUGIN_TOOL_NAME_RE, 'lowercase letters, digits and underscores, max 30 characters'),
+ description: z.string().min(1).max(1024),
+ /** Read-only tools skip approval and are available in plan mode. */
+ readOnly: z.boolean().default(false),
+ /** Per-call timeout; capped by Mercury at 300s. */
+ timeoutMs: z.number().int().min(1000).max(300_000).default(60_000),
+}).strict();
+
+const commandDecl = z.object({
+ name: z.string().regex(PLUGIN_TOOL_NAME_RE),
+ description: z.string().min(1).max(200),
+}).strict();
+
+const settingField = z.object({
+ type: z.enum(['string', 'number', 'boolean', 'enum']),
+ description: z.string().max(300).default(''),
+ default: z.union([z.string(), z.number(), z.boolean()]).optional(),
+ options: z.array(z.string()).max(50).optional(),
+}).strict();
+
+const settingKey = z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,40}$/);
+
+const settingsMigration = z.object({
+ /** The settings version this step produces. */
+ to: z.number().int().min(2).max(1000),
+ /** old key → new key; the value moves over. */
+ rename: z.record(settingKey, settingKey).default({}),
+ /** Keys that no longer exist. */
+ remove: z.array(settingKey).max(100).default([]),
+ /** Values that change, old → new, per key (e.g. an enum option renamed). */
+ mapValues: z.record(settingKey, z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))).default({}),
+}).strict();
+
+const serverSpec = z.object({
+ /** `node` (Mercury's own runtime) or a path inside the plugin folder. */
+ command: z.union([z.literal('node'), relPath]),
+ args: z.array(z.string().max(500)).max(32).default([]),
+}).strict();
+
+export const manifestSchema = z.object({
+ manifestVersion: z.literal(MANIFEST_VERSION),
+ id: z.string().regex(PLUGIN_ID_RE, '3-32 characters: lowercase letters, digits and hyphens, starting with a letter'),
+ name: z.string().min(1).max(60),
+ version: strictSemver,
+ description: z.string().min(1).max(280),
+ kind: z.enum(['in-process', 'out-of-process']),
+ author: z.string().max(100).optional(),
+ homepage: z.string().url().max(300).optional(),
+ license: z.string().max(60).optional(),
+ engines: z.object({
+ mercury: semverRange,
+ pluginApi: semverRange.default('^1.0.0'),
+ }).strict(),
+ /** Omit to support every platform Mercury runs on. */
+ platforms: z.array(z.enum(PLATFORM_KEYS)).min(1).optional(),
+ /** In-process: the bundled ES module that exports `activate`. */
+ entry: relPath.optional(),
+ /** Out-of-process: how to start the MCP server, optionally per platform. */
+ server: serverSpec.extend({
+ platforms: z.record(z.enum(PLATFORM_KEYS), serverSpec).optional(),
+ }).optional(),
+ contributes: z.object({
+ tools: z.array(toolDecl).max(64).default([]),
+ commands: z.array(commandDecl).max(32).default([]),
+ }).strict().default({ tools: [], commands: [] }),
+ /** What the plugin needs. Shown to the owner before install. */
+ permissions: z.object({
+ /** Hosts the plugin may reach through ctx.fetch, e.g. "api.example.com" or "*.example.com". */
+ network: z.array(z.string().min(1).max(253)).max(32).default([]),
+ /** Secret names from ~/.mercury/.env the plugin may read. Nothing else is visible to it. */
+ secrets: z.array(z.string().regex(SECRET_NAME_RE)).max(16).default([]),
+ }).strict().default({ network: [], secrets: [] }),
+ settings: z.object({
+ /** Bump when a field is renamed, removed or changes meaning, and add a migration. */
+ version: z.number().int().min(1).max(1000).default(1),
+ fields: z.record(settingKey, settingField).default({}),
+ /**
+ * Declarative upgrades for saved settings, applied in order when the saved
+ * version is older. No code runs: an out-of-process plugin can migrate
+ * too, and a bad migration can't touch anything but its own settings.
+ */
+ migrations: z.array(settingsMigration).max(100).default([]),
+ }).strict().optional(),
+ /** Native files inside the package whose SHA-256 is checked at install and before every start. */
+ checksums: z.record(relPath, z.string().regex(/^[a-f0-9]{64}$/)).optional(),
+}).strict().superRefine((m, ctx) => {
+ if (m.kind === 'in-process' && !m.entry) ctx.addIssue({ code: 'custom', path: ['entry'], message: 'in-process plugins need an "entry" module' });
+ if (m.kind === 'in-process' && m.server) ctx.addIssue({ code: 'custom', path: ['server'], message: 'in-process plugins cannot declare a "server"' });
+ if (m.kind === 'out-of-process' && !m.server) ctx.addIssue({ code: 'custom', path: ['server'], message: 'out-of-process plugins need a "server"' });
+ 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' });
+ }
+ 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` });
+ }
+ if (m.settings) {
+ let prev = 1;
+ for (const step of m.settings.migrations) {
+ if (step.to <= prev || step.to > m.settings.version) {
+ ctx.addIssue({ code: 'custom', path: ['settings', 'migrations'], message: `migrations must go up in order and end at settings.version (${m.settings.version})` });
+ break;
+ }
+ prev = step.to;
+ }
+ }
+ const names = new Set<string>();
+ for (const t of [...m.contributes.tools, ...m.contributes.commands]) {
+ if (names.has(t.name)) ctx.addIssue({ code: 'custom', path: ['contributes'], message: `duplicate name "${t.name}"` });
+ names.add(t.name);
+ }
+});
+
+export type PluginManifest = z.infer<typeof manifestSchema>;
+export type PluginToolDecl = PluginManifest['contributes']['tools'][number];
+
+// ── state ────────────────────────────────────────────────────────────────
+
+export type DisabledCode =
+ | 'user' // the owner disabled it
+ | 'activation' // activate() threw, timed out, or the server failed to start
+ | 'errors' // circuit breaker: too many failures in a row
+ | 'crashed' // out-of-process: crashed too often
+ | 'incompatible' // Mercury or plugin API version, or platform
+ | 'boot-guard' // the daemon failed to start twice right after this changed
+ | 'integrity'; // files changed since install (checksum mismatch)
+
+export interface PluginStateEntry {
+ version: string;
+ previousVersion?: string;
+ enabled: boolean;
+ kind: PluginManifest['kind'];
+ source: { type: 'catalog' | 'path' | 'url' | 'github'; ref: string };
+ /** True when installed from the catalog with a pinned checksum. */
+ verified: boolean;
+ installedAt: string;
+ updatedAt: string;
+ disabled?: { code: DisabledCode; message: string; at: string };
+}
+
+export interface PluginsState {
+ stateVersion: 1;
+ plugins: Record<string, PluginStateEntry>;
+ boot: {
+ /** True from daemon start until the plugins have run healthily for a while. */
+ inProgress: boolean;
+ failedBoots: number;
+ lastChange?: { id: string; at: string };
+ };
+}
+
+/** One row of `/plugins`: the merged view of the catalog and what is installed. */
+export type PluginStatus = 'available' | 'installed' | 'enabled' | 'disabled' | 'update-available' | 'incompatible' | 'error';
+
+export interface PluginListItem {
+ id: string;
+ name: string;
+ description: string;
+ kind: PluginManifest['kind'];
+ tier: 'official' | 'community' | 'local';
+ status: PluginStatus;
+ installedVersion?: string;
+ latestVersion?: string;
+ sizeBytes?: number;
+ enabled: boolean;
+ running: boolean;
+ verified: boolean;
+ tools: string[];
+ commands: string[];
+ permissions?: PluginManifest['permissions'];
+ disabled?: PluginStateEntry['disabled'];
+ 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 }>;
+}
+
+// ── catalog ──────────────────────────────────────────────────────────────
+
+const catalogArtifact = z.object({
+ url: z.string().url().refine((u) => u.startsWith('https://'), 'artifacts must be served over HTTPS'),
+ sha256: z.string().regex(/^[a-f0-9]{64}$/),
+ size: z.number().int().positive(),
+}).strict();
+
+export const catalogEntrySchema = z.object({
+ id: z.string().regex(PLUGIN_ID_RE),
+ name: z.string().min(1).max(60),
+ description: z.string().min(1).max(280),
+ version: strictSemver,
+ kind: z.enum(['in-process', 'out-of-process']),
+ tier: z.enum(['official', 'community']),
+ homepage: z.string().url().optional(),
+ engines: z.object({ mercury: semverRange, pluginApi: semverRange.default('^1.0.0') }).strict(),
+ /** Either one artifact for every platform, or one per platform. */
+ artifact: catalogArtifact.optional(),
+ artifacts: z.record(z.enum(PLATFORM_KEYS), catalogArtifact).optional(),
+ tools: z.array(z.string()).default([]),
+ permissions: z.object({
+ network: z.array(z.string()).default([]),
+ secrets: z.array(z.string()).default([]),
+ }).default({ network: [], secrets: [] }),
+}).strict().refine((e) => !!e.artifact || !!e.artifacts, 'needs "artifact" or "artifacts"');
+
+export const catalogSchema = z.object({
+ catalogVersion: z.literal(1),
+ updatedAt: z.string(),
+ plugins: z.array(catalogEntrySchema).max(500),
+}).strict();
+
+export type CatalogEntry = z.infer<typeof catalogEntrySchema>;
+export type Catalog = z.infer<typeof catalogSchema>;
diff --git a/src/ui/input-composer.tsx b/src/ui/input-composer.tsx
index af0a9cef..3ac091d0 100644
--- a/src/ui/input-composer.tsx
+++ b/src/ui/input-composer.tsx
@@ -125,6 +125,17 @@ export const SLASH_COMMANDS: readonly string[] = [
'/skills install ',
'/skills remove ',
'/skills help',
+ '/plugins',
+ '/plugins search ',
+ '/plugins info ',
+ '/plugins install ',
+ '/plugins enable ',
+ '/plugins disable ',
+ '/plugins update',
+ '/plugins rollback ',
+ '/plugins uninstall ',
+ '/plugins set ',
+ '/plugins help',
'/stream',
'/saver',
'/saver on',
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index 5478da4e..a46b7a2f 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -151,6 +151,12 @@ export function getManual(): string {
['/skills view <id>', 'Show details + registry URL for a skill'],
['/skills install <id|url>', 'Install from the registry or a raw SKILL.md URL'],
['/skills remove <id>', 'Uninstall a skill'],
+ ['/plugins', 'Installed and available plugins, with status'],
+ ['/plugins install <id|path|url>', 'Install a plugin (shows what it needs first)'],
+ ['/plugins enable|disable <id>', 'Turn a plugin on or off'],
+ ['/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)'],
['/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)'],
@@ -297,6 +303,7 @@ export function getManual(): string {
['~/.mercury/permissions.yaml', 'Capabilities and approval rules'],
['~/.mercury/soul/*.md', 'Agent personality (soul, persona, taste, heartbeat)'],
['~/.mercury/skills/', 'Installed skills'],
+ ['~/.mercury/plugins/', 'Installed plugins, their data and settings'],
['~/.mercury/schedules.yaml', 'Scheduled tasks'],
['~/.mercury/token-usage.json', 'Daily token usage tracking'],
['~/.mercury/memory/', 'Short-term, long-term, episodic memory'],
@@ -345,6 +352,13 @@ export function getTelegramHelp(): string {
lines.push('/bg cancel <id> — Cancel a background task');
lines.push('');
+ lines.push('**Plugins**');
+ lines.push('/plugins — Installed and available plugins, with buttons');
+ lines.push('/plugins install <id> — Install (shows what it needs first)');
+ lines.push('/plugins enable|disable <id> — Turn a plugin on or off');
+ lines.push('/plugins uninstall <id> — Remove (keeps data unless --purge)');
+ lines.push('');
+
lines.push('**Budget**');
lines.push('/budget — Show token budget status');
lines.push('/budget override — Allow one request past budget');
@@ -452,6 +466,13 @@ export function getDiscordHelp(): string {
lines.push('/bg cancel <id> \u2014 Cancel a background task');
lines.push('');
+ lines.push('**Plugins**');
+ lines.push('/plugins \u2014 Installed and available plugins');
+ lines.push('/plugins install <id> \u2014 Install (shows what it needs first)');
+ lines.push('/plugins enable|disable <id> \u2014 Turn a plugin on or off');
+ lines.push('/plugins uninstall <id> \u2014 Remove (keeps data unless --purge)');
+ lines.push('');
+
lines.push('**Budget**');
lines.push('/budget \u2014 Show token budget status');
lines.push('/budget override \u2014 Allow one request past budget');
diff --git a/src/web/api/plugins.ts b/src/web/api/plugins.ts
new file mode 100644
index 00000000..06cd7aeb
--- /dev/null
+++ b/src/web/api/plugins.ts
@@ -0,0 +1,123 @@
+/**
+ * Plugin API for the dashboard and for `mercury plugins …` / attached
+ * terminals (which forward here so only the runtime owner runs plugins).
+ *
+ * Reading (list, info, health) is open to any authenticated session.
+ * Anything that installs or changes plugins runs new code on this machine,
+ * so it is accepted from this machine only (like /api/restart), never from
+ * a LAN or Cloud-relayed session.
+ */
+import { Hono, type Context } from 'hono';
+import { isLoopbackRequest } from '../middleware.js';
+import { getPluginManager } from '../../plugins/manager.js';
+import { localService } from '../../plugins/service.js';
+
+const plugins = new Hono();
+
+function svc() {
+ return localService(getPluginManager());
+}
+
+function localOnly(c: Context): Response | null {
+ if (isLoopbackRequest(c)) return null;
+ return c.json({ error: 'Plugins can only be installed or changed from this machine.' }, 403);
+}
+
+function fail(c: Context, err: unknown) {
+ const message = err instanceof Error ? err.message : String(err);
+ const status = /not installed|No plugin called|no setting/i.test(message) ? 404 : 400;
+ return c.json({ error: message }, status);
+}
+
+plugins.get('/api/plugins', async (c) => {
+ try {
+ return c.json(await svc().list(c.req.query('refresh') === '1'));
+ } catch (err) {
+ return fail(c, err);
+ }
+});
+
+plugins.get('/api/plugins/health', (c) => c.json(getPluginManager().health()));
+
+plugins.get('/api/plugins/:id', async (c) => {
+ try {
+ return c.json({ plugin: await svc().info(c.req.param('id')) });
+ } catch (err) {
+ return fail(c, err);
+ }
+});
+
+plugins.post('/api/plugins/install', async (c) => {
+ const denied = localOnly(c);
+ if (denied) return denied;
+ const body = (await c.req.json().catch(() => ({}))) as { source?: unknown; enable?: unknown; force?: unknown };
+ if (typeof body.source !== 'string' || !body.source.trim() || body.source.length > 500) {
+ return c.json({ error: 'source must be a plugin id, path, https URL or github:owner/repo' }, 400);
+ }
+ try {
+ return c.json(await svc().install(body.source.trim(), { enable: body.enable !== false, force: body.force === true }));
+ } catch (err) {
+ return fail(c, err);
+ }
+});
+
+plugins.post('/api/plugins/update', async (c) => {
+ const denied = localOnly(c);
+ if (denied) return denied;
+ try {
+ return c.json({ changed: await svc().update() });
+ } catch (err) {
+ return fail(c, err);
+ }
+});
+
+plugins.post('/api/plugins/reconcile', async (c) => {
+ const denied = localOnly(c);
+ if (denied) return denied;
+ await getPluginManager().reconcile();
+ return c.json({ ok: true });
+});
+
+for (const action of ['enable', 'disable', 'update', 'rollback'] as const) {
+ plugins.post(`/api/plugins/:id/${action}`, async (c) => {
+ const denied = localOnly(c);
+ if (denied) return denied;
+ const id = c.req.param('id');
+ try {
+ const s = svc();
+ if (action === 'enable') await s.enable(id);
+ else if (action === 'disable') await s.disable(id);
+ else if (action === 'rollback') return c.json(await s.rollback(id));
+ else return c.json({ changed: await s.update(id) });
+ return c.json({ ok: true, plugin: await s.info(id) });
+ } catch (err) {
+ return fail(c, err);
+ }
+ });
+}
+
+plugins.post('/api/plugins/:id/settings', async (c) => {
+ const denied = localOnly(c);
+ if (denied) return denied;
+ const body = (await c.req.json().catch(() => ({}))) as { key?: unknown; value?: unknown };
+ if (typeof body.key !== 'string' || !/^[a-zA-Z][a-zA-Z0-9_]{0,40}$/.test(body.key)) return c.json({ error: 'key is required' }, 400);
+ try {
+ await svc().setSetting(c.req.param('id'), body.key, body.value);
+ 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;
+ try {
+ await svc().uninstall(c.req.param('id'), c.req.query('purge') === '1');
+ return c.json({ ok: true });
+ } catch (err) {
+ return fail(c, err);
+ }
+});
+
+export default plugins;
diff --git a/src/web/api/status.ts b/src/web/api/status.ts
index 5b47969e..9d93edf0 100644
--- a/src/web/api/status.ts
+++ b/src/web/api/status.ts
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { isLoopbackRequest } from '../middleware.js';
+import { peekPluginManager } from '../../plugins/manager.js';
import { getLoopLag } from '../../utils/loop-lag.js';
export interface AgentStatus {
@@ -61,7 +62,8 @@ function versionString(): string {
status.get('/api/health', (c) => {
if (!isLoopbackRequest(c)) return c.json({ error: 'Not found' }, 404);
const lag = getLoopLag();
- return c.json({ ok: true, pid: process.pid, version: versionString(), state: currentStatus.state, booting: currentStatus.state === 'booting', loopLag: { p99Ms: Math.round(lag.p99Ms), maxMs: Math.round(lag.maxMs) } });
+ const plugins = peekPluginManager()?.health();
+ return c.json({ ok: true, pid: process.pid, version: versionString(), state: currentStatus.state, booting: currentStatus.state === 'booting', loopLag: { p99Ms: Math.round(lag.p99Ms), maxMs: Math.round(lag.maxMs) }, ...(plugins ? { plugins: { safeMode: plugins.safeMode, running: plugins.running, tools: plugins.tools } } : {}) });
});
status.get('/api/status', (c) => {
diff --git a/src/web/server.ts b/src/web/server.ts
index 0a40892e..1fb09dbc 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -20,6 +20,7 @@ import spotifyRoutes, { setSpotifyClient } from './api/spotify.js';
import kanbanRoutes, { setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders } from './api/kanban.js';
import ideRoutes, { setIDEProviders } from './api/workspace-ide.js';
import lifecycleRoutes, { setShutdownHandler } from './api/lifecycle.js';
+import pluginRoutes from './api/plugins.js';
import { BoardManager } from '../core/board-manager.js';
import { isBetterSqlite3Available } from '../memory/second-brain-db.js';
@@ -83,6 +84,7 @@ app.route('/', spotifyRoutes);
app.route('/', kanbanRoutes);
app.route('/', ideRoutes);
app.route('/', lifecycleRoutes);
+app.route('/', pluginRoutes);
// ── Legacy static assets (vendor fonts, icons, wasm — still needed by React SPA) ──
app.get('/vendor/*', (c) => {
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 29f5b5f9..57721791 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -16,6 +16,7 @@ const GoalsPage = lazy(() => import("./pages/brain/Goals").then((m) => ({ defaul
const GraphPage = lazy(() => import("./pages/brain/Graph").then((m) => ({ default: m.GraphPage })));
const ProvidersPage = lazy(() => import("./pages/Providers").then((m) => ({ default: m.ProvidersPage })));
const SkillsPage = lazy(() => import("./pages/Skills").then((m) => ({ default: m.SkillsPage })));
+const PluginsPage = lazy(() => import("./pages/Plugins").then((m) => ({ default: m.PluginsPage })));
const PermissionsPage = lazy(() => import("./pages/Permissions").then((m) => ({ default: m.PermissionsPage })));
const SchedulesPage = lazy(() => import("./pages/Schedules").then((m) => ({ default: m.SchedulesPage })));
const BotsPage = lazy(() => import("./pages/Bots").then((m) => ({ default: m.BotsPage })));
@@ -78,6 +79,7 @@ function AnimatedRoutes() {
<Route path="second-brain/graph" element={<AnimatedPage><GraphPage /></AnimatedPage>} />
<Route path="providers" element={<AnimatedPage><ProvidersPage /></AnimatedPage>} />
<Route path="skills" element={<AnimatedPage><SkillsPage /></AnimatedPage>} />
+ <Route path="plugins" element={<AnimatedPage><PluginsPage /></AnimatedPage>} />
<Route path="permissions" element={<AnimatedPage><PermissionsPage /></AnimatedPage>} />
<Route path="schedules" element={<AnimatedPage><SchedulesPage /></AnimatedPage>} />
<Route path="bots" element={<AnimatedPage><BotsPage /></AnimatedPage>} />
diff --git a/ui/src/components/layout/Sidebar.tsx b/ui/src/components/layout/Sidebar.tsx
index 38d32c83..77b01f67 100644
--- a/ui/src/components/layout/Sidebar.tsx
+++ b/ui/src/components/layout/Sidebar.tsx
@@ -16,6 +16,7 @@ import {
Cpu,
Bot,
Puzzle,
+ Blocks,
Shield,
Clock,
BarChart3,
@@ -63,6 +64,7 @@ const NAV_SECTIONS = [
items: [
{ to: "/providers", icon: Cpu, label: "Providers" },
{ to: "/skills", icon: Puzzle, label: "Skills" },
+ { to: "/plugins", icon: Blocks, label: "Plugins" },
{ to: "/permissions", icon: Shield, label: "Permissions" },
{ to: "/schedules", icon: Clock, label: "Schedules" },
{ to: "/usage", icon: BarChart3, label: "Usage" },
diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts
index c47d965d..a9c57f39 100644
--- a/ui/src/lib/api.ts
+++ b/ui/src/lib/api.ts
@@ -266,6 +266,54 @@ export const skills = {
delete: (name: string) => del<{ success: boolean }>(`/api/skills/${name}`),
};
+// ── Plugins ──
+export type PluginStatus = "available" | "installed" | "enabled" | "disabled" | "update-available" | "incompatible" | "error";
+
+export interface PluginSetting {
+ key: string;
+ type: "string" | "number" | "boolean" | "enum";
+ description: string;
+ options?: string[];
+ value: unknown;
+}
+
+export interface PluginItem {
+ id: string;
+ name: string;
+ description: string;
+ kind: "in-process" | "out-of-process";
+ tier: "official" | "community" | "local";
+ status: PluginStatus;
+ installedVersion?: string;
+ latestVersion?: string;
+ sizeBytes?: number;
+ enabled: boolean;
+ running: boolean;
+ verified: boolean;
+ tools: string[];
+ commands: string[];
+ permissions?: { network: string[]; secrets: string[] };
+ disabled?: { code: string; message: string; at: string };
+ lastError?: string;
+ incompatibleReason?: string;
+ settings?: PluginSetting[];
+}
+
+export const plugins = {
+ list: (refresh = false) =>
+ get<{ items: PluginItem[]; catalogError?: string; stale: boolean; safeMode: boolean }>(`/api/plugins${refresh ? "?refresh=1" : ""}`),
+ info: (id: string) => get<{ plugin: PluginItem | null }>(`/api/plugins/${encodeURIComponent(id)}`),
+ install: (source: string) =>
+ post<{ id: string; name: string; version: string; previousVersion?: string; verified: boolean; unchanged: boolean; tier: string }>("/api/plugins/install", { source }),
+ enable: (id: string) => post<{ ok: boolean }>(`/api/plugins/${encodeURIComponent(id)}/enable`),
+ disable: (id: string) => post<{ ok: boolean }>(`/api/plugins/${encodeURIComponent(id)}/disable`),
+ update: (id: string) => post<{ changed: Array<{ id: string; from: string; to: string }> }>(`/api/plugins/${encodeURIComponent(id)}/update`),
+ rollback: (id: string) => post<{ from: string; to: string }>(`/api/plugins/${encodeURIComponent(id)}/rollback`),
+ uninstall: (id: string, purge = false) => del<{ ok: boolean }>(`/api/plugins/${encodeURIComponent(id)}${purge ? "?purge=1" : ""}`),
+ setSetting: (id: string, key: string, value: unknown) =>
+ post<{ ok: boolean }>(`/api/plugins/${encodeURIComponent(id)}/settings`, { key, value }),
+};
+
// ── Permissions ──
export const permissions = {
get: () => get<{ manifest: PermissionManifest }>("/api/permissions"),
@@ -908,6 +956,7 @@ const api = {
agents,
bgTasks,
skills,
+ plugins,
permissions,
usage,
schedules,
diff --git a/ui/src/pages/Plugins.tsx b/ui/src/pages/Plugins.tsx
new file mode 100644
index 00000000..5937c24a
--- /dev/null
+++ b/ui/src/pages/Plugins.tsx
@@ -0,0 +1,555 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { motion, AnimatePresence } from "framer-motion";
+import {
+ Blocks,
+ Loader2,
+ CheckCircle2,
+ XCircle,
+ RefreshCw,
+ ArrowUpCircle,
+ Undo2,
+ Trash2,
+ ShieldCheck,
+ ShieldAlert,
+ Globe,
+ KeyRound,
+ Wrench,
+ TerminalSquare,
+ LifeBuoy,
+ Search,
+ Cpu,
+ Boxes,
+} from "lucide-react";
+import { Card, CardContent } from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Badge } from "@/components/ui/badge";
+import { Switch } from "@/components/ui/switch";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { cn } from "@/lib/utils";
+import api, { type PluginItem, type PluginSetting } from "@/lib/api";
+
+/* ── Helpers ────────────────────────────────────────────────── */
+
+interface Toast {
+ id: number;
+ type: "success" | "error";
+ message: string;
+}
+
+function ToastBar({ toasts }: { toasts: Toast[] }) {
+ return (
+ <div className="fixed bottom-6 right-6 z-50 flex flex-col gap-2">
+ <AnimatePresence>
+ {toasts.map((t) => (
+ <motion.div
+ key={t.id}
+ initial={{ opacity: 0, x: 40 }}
+ animate={{ opacity: 1, x: 0 }}
+ exit={{ opacity: 0, x: 40 }}
+ className={cn(
+ "flex items-center gap-2 rounded-lg border px-4 py-3 text-sm shadow-lg backdrop-blur-sm",
+ t.type === "success"
+ ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-400"
+ : "border-destructive/30 bg-destructive/10 text-destructive"
+ )}
+ >
+ {t.type === "success" ? <CheckCircle2 className="h-4 w-4" /> : <XCircle className="h-4 w-4" />}
+ {t.message}
+ </motion.div>
+ ))}
+ </AnimatePresence>
+ </div>
+ );
+}
+
+function size(bytes?: number): string {
+ if (!bytes) return "";
+ return bytes >= 1048576 ? `${(bytes / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
+}
+
+function errorText(err: unknown, fallback: string): string {
+ return err instanceof Error ? err.message : fallback;
+}
+
+const STATUS: Record<PluginItem["status"], { label: string; variant: "success" | "warning" | "secondary" | "destructive" | "outline" }> = {
+ enabled: { label: "Enabled", variant: "success" },
+ disabled: { label: "Disabled", variant: "secondary" },
+ "update-available": { label: "Update available", variant: "warning" },
+ available: { label: "Available", variant: "outline" },
+ installed: { label: "Installed", variant: "secondary" },
+ incompatible: { label: "Incompatible", variant: "destructive" },
+ error: { label: "Not running", variant: "destructive" },
+};
+
+function statusNote(p: PluginItem): string | null {
+ if (p.status === "incompatible") return p.incompatibleReason ?? null;
+ if (p.status === "error") return p.lastError ?? "Enabled but not running.";
+ if (p.disabled && p.disabled.code !== "user") return `Turned off automatically: ${p.disabled.message}`;
+ return null;
+}
+
+/* ── Page ───────────────────────────────────────────────────── */
+
+export function PluginsPage() {
+ const [items, setItems] = useState<PluginItem[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [refreshing, setRefreshing] = useState(false);
+ const [safeMode, setSafeMode] = useState(false);
+ const [catalogError, setCatalogError] = useState<string | undefined>();
+ const [tab, setTab] = useState<"installed" | "browse">("installed");
+ const [query, setQuery] = useState("");
+ const [busy, setBusy] = useState<Record<string, boolean>>({});
+ const [source, setSource] = useState("");
+ const [confirmInstall, setConfirmInstall] = useState<string | null>(null);
+ const [details, setDetails] = useState<PluginItem | null>(null);
+ const [toasts, setToasts] = useState<Toast[]>([]);
+
+ const toast = useCallback((type: Toast["type"], message: string) => {
+ const id = Date.now() + Math.random();
+ setToasts((prev) => [...prev, { id, type, message }]);
+ setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 4000);
+ }, []);
+
+ const load = useCallback(async (refresh = false) => {
+ if (refresh) setRefreshing(true);
+ try {
+ const res = await api.plugins.list(refresh);
+ setItems(res.items);
+ setSafeMode(res.safeMode);
+ setCatalogError(res.catalogError);
+ } catch (err) {
+ toast("error", errorText(err, "Could not load plugins"));
+ } finally {
+ setLoading(false);
+ setRefreshing(false);
+ }
+ }, [toast]);
+
+ useEffect(() => { void load(); }, [load]);
+
+ const installed = useMemo(() => items.filter((i) => i.installedVersion), [items]);
+ const available = useMemo(() => items.filter((i) => !i.installedVersion), [items]);
+ const shown = useMemo(() => {
+ const list = tab === "installed" ? installed : available;
+ const q = query.trim().toLowerCase();
+ return q ? list.filter((i) => `${i.id} ${i.name} ${i.description}`.toLowerCase().includes(q)) : list;
+ }, [tab, installed, available, query]);
+
+ async function act(id: string, label: string, fn: () => Promise<unknown>) {
+ setBusy((b) => ({ ...b, [id]: true }));
+ try {
+ await fn();
+ toast("success", label);
+ await load();
+ if (details?.id === id) {
+ const fresh = await api.plugins.info(id).catch(() => null);
+ setDetails(fresh?.plugin ?? null);
+ }
+ } catch (err) {
+ toast("error", errorText(err, "That didn't work"));
+ } finally {
+ setBusy((b) => ({ ...b, [id]: false }));
+ }
+ }
+
+ async function install(src: string) {
+ setConfirmInstall(null);
+ setBusy((b) => ({ ...b, [src]: true }));
+ try {
+ const r = await api.plugins.install(src);
+ toast("success", r.unchanged ? `${r.name} ${r.version} is already installed` : `Installed ${r.name} ${r.version}`);
+ setSource("");
+ setTab("installed");
+ await load();
+ } catch (err) {
+ toast("error", errorText(err, "Install failed"));
+ } finally {
+ setBusy((b) => ({ ...b, [src]: false }));
+ }
+ }
+
+ async function openDetails(id: string) {
+ try {
+ const r = await api.plugins.info(id);
+ setDetails(r.plugin);
+ } catch (err) {
+ toast("error", errorText(err, "Could not load plugin"));
+ }
+ }
+
+ const fromCatalog = confirmInstall ? available.find((i) => i.id === confirmInstall) : undefined;
+
+ return (
+ <div className="space-y-6 p-4 sm:p-6">
+ {/* Header */}
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex items-center gap-3">
+ <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-[#00d4ff]/10">
+ <Blocks className="h-5 w-5 text-[#00d4ff]" />
+ </div>
+ <div>
+ <h1 className="text-2xl font-semibold text-foreground">Plugins</h1>
+ <p className="text-sm text-muted-foreground">Add only what you use. Each plugin can be turned off or removed at any time.</p>
+ </div>
+ </div>
+ <Button variant="outline" size="sm" onClick={() => load(true)} disabled={refreshing}>
+ <RefreshCw className={cn("h-4 w-4", refreshing && "animate-spin")} />
+ Refresh
+ </Button>
+ </div>
+
+ {safeMode && (
+ <Card className="border-amber-500/30 bg-amber-500/5">
+ <CardContent className="flex items-start gap-3 p-4 text-sm">
+ <LifeBuoy className="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />
+ <div>
+ <p className="font-medium text-foreground">Safe mode: every plugin is off for this run.</p>
+ <p className="text-muted-foreground">Restart Mercury without <code>--safe-mode</code> (or <code>MERCURY_PLUGINS=off</code>) to turn them back on. You can still uninstall here.</p>
+ </div>
+ </CardContent>
+ </Card>
+ )}
+
+ {/* Install from source */}
+ <Card>
+ <CardContent className="space-y-2 p-4 sm:p-5">
+ <form
+ className="flex flex-col gap-3 sm:flex-row"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (source.trim()) setConfirmInstall(source.trim());
+ }}
+ >
+ <Input
+ value={source}
+ onChange={(e) => setSource(e.target.value)}
+ placeholder="Plugin id, folder, .tgz, https URL or github:owner/repo"
+ className="flex-1 font-mono text-sm"
+ disabled={!!busy[source.trim()]}
+ />
+ <Button type="submit" disabled={!source.trim() || !!busy[source.trim()]}>
+ {busy[source.trim()] ? <><Loader2 className="h-4 w-4 animate-spin" />Installing</> : "Install"}
+ </Button>
+ </form>
+ <p className="text-xs text-muted-foreground">
+ Plugins can only be installed or changed from the computer Mercury runs on.
+ </p>
+ </CardContent>
+ </Card>
+
+ {/* Tabs + search */}
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="inline-flex rounded-lg border border-border p-1">
+ {([
+ ["installed", `Installed (${installed.length})`],
+ ["browse", `Browse (${available.length})`],
+ ] as const).map(([key, label]) => (
+ <button
+ key={key}
+ type="button"
+ onClick={() => setTab(key)}
+ className={cn(
+ "rounded-md px-3 py-1.5 text-sm transition-colors",
+ tab === key ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground"
+ )}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ <div className="relative sm:w-72">
+ <Search className="pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
+ <Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search plugins" className="pl-8" />
+ </div>
+ </div>
+
+ {catalogError && tab === "browse" && (
+ <p className="text-sm text-muted-foreground">Catalog unavailable: {catalogError}</p>
+ )}
+
+ {/* List */}
+ {loading ? (
+ <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
+ {[0, 1, 2].map((i) => <div key={i} className="h-40 animate-pulse rounded-xl bg-muted" />)}
+ </div>
+ ) : shown.length === 0 ? (
+ <Card>
+ <CardContent className="flex flex-col items-center py-14 text-center">
+ <Boxes className="mb-3 h-8 w-8 text-muted-foreground" />
+ <p className="font-medium text-foreground">
+ {query ? "No plugins match your search." : tab === "installed" ? "No plugins installed yet." : "Nothing new in the catalog right now."}
+ </p>
+ {tab === "installed" && !query && (
+ <Button variant="link" onClick={() => setTab("browse")}>Browse the catalog</Button>
+ )}
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
+ {shown.map((p) => {
+ const s = STATUS[p.status];
+ const note = statusNote(p);
+ const isBusy = !!busy[p.id];
+ return (
+ <Card key={p.id} className="h-full">
+ <CardContent className="flex h-full flex-col gap-3 p-5">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <button type="button" onClick={() => openDetails(p.id)} className="truncate text-left text-sm font-semibold text-foreground hover:underline">
+ {p.name}
+ </button>
+ <p className="font-mono text-xs text-muted-foreground">
+ {p.id} · {p.installedVersion ?? p.latestVersion}
+ {p.status === "update-available" && p.latestVersion ? ` → ${p.latestVersion}` : ""}
+ </p>
+ </div>
+ {p.installedVersion ? (
+ <Switch
+ checked={p.enabled}
+ disabled={isBusy || safeMode || (p.status === "incompatible" && !p.enabled)}
+ onCheckedChange={(on) =>
+ act(p.id, on ? `Enabled ${p.name}` : `Disabled ${p.name}`, () => (on ? api.plugins.enable(p.id) : api.plugins.disable(p.id)))
+ }
+ aria-label={p.enabled ? `Disable ${p.name}` : `Enable ${p.name}`}
+ />
+ ) : null}
+ </div>
+ <p className="line-clamp-3 text-sm text-muted-foreground">{p.description}</p>
+ <div className="flex flex-wrap gap-1.5">
+ <Badge variant={s.variant}>{s.label}</Badge>
+ <Badge variant="outline" className="capitalize">{p.tier}</Badge>
+ {p.kind === "out-of-process" && <Badge variant="outline">Own process</Badge>}
+ {p.tools.length > 0 && <Badge variant="outline">{p.tools.length} tool{p.tools.length === 1 ? "" : "s"}</Badge>}
+ {size(p.sizeBytes) && <Badge variant="outline">{size(p.sizeBytes)}</Badge>}
+ </div>
+ {note && <p className="text-xs text-destructive">{note}</p>}
+ <div className="mt-auto flex flex-wrap gap-2 pt-1">
+ {!p.installedVersion ? (
+ <Button size="sm" disabled={isBusy || p.status === "incompatible"} onClick={() => setConfirmInstall(p.id)}>
+ {busy[p.id] ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
+ Install
+ </Button>
+ ) : p.status === "update-available" ? (
+ <Button size="sm" disabled={isBusy} onClick={() => act(p.id, `Updated ${p.name}`, () => api.plugins.update(p.id))}>
+ {isBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <ArrowUpCircle className="h-4 w-4" />}
+ Update
+ </Button>
+ ) : null}
+ <Button size="sm" variant="outline" onClick={() => openDetails(p.id)}>Details</Button>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Install confirmation */}
+ <AlertDialog open={!!confirmInstall} onOpenChange={(o) => !o && setConfirmInstall(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Install {fromCatalog?.name ?? confirmInstall}?</AlertDialogTitle>
+ <AlertDialogDescription asChild>
+ <div className="space-y-3 text-sm">
+ {fromCatalog ? (
+ <>
+ <p>{fromCatalog.description}</p>
+ <PermissionList p={fromCatalog} />
+ <p className="flex items-center gap-1.5 text-emerald-500"><ShieldCheck className="h-4 w-4" /> From the {fromCatalog.tier} catalog, checksum verified on download.</p>
+ </>
+ ) : (
+ <p className="flex items-start gap-1.5 text-amber-500">
+ <ShieldAlert className="mt-0.5 h-4 w-4 shrink-0" />
+ This isn't from the catalog, so Mercury can't verify it. Only install plugins from sources you trust: an in-process plugin runs inside Mercury with your permissions.
+ </p>
+ )}
+ </div>
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction onClick={() => confirmInstall && install(confirmInstall)}>Install</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
+ {/* Details */}
+ <Dialog open={!!details} onOpenChange={(o) => !o && setDetails(null)}>
+ <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg">
+ {details && (
+ <PluginDetails
+ p={details}
+ busy={!!busy[details.id]}
+ safeMode={safeMode}
+ onAct={act}
+ onInstall={() => setConfirmInstall(details.id)}
+ onClose={() => setDetails(null)}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
+
+ <ToastBar toasts={toasts} />
+ </div>
+ );
+}
+
+/* ── Details dialog ─────────────────────────────────────────── */
+
+function PermissionList({ p }: { p: PluginItem }) {
+ const network = p.permissions?.network ?? [];
+ const secrets = p.permissions?.secrets ?? [];
+ return (
+ <ul className="space-y-1.5 text-sm">
+ <li className="flex items-start gap-2"><Cpu className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{p.kind === "out-of-process" ? "Runs in its own process: a crash can't affect Mercury" : "Runs inside Mercury"}</li>
+ <li className="flex items-start gap-2"><Globe className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />Network: {network.length ? network.join(", ") : "none"}</li>
+ <li className="flex items-start gap-2"><KeyRound className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />Secrets it can read: {secrets.length ? secrets.join(", ") : "none"}</li>
+ {p.tools.length > 0 && <li className="flex items-start gap-2"><Wrench className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span className="break-all">Tools: {p.tools.join(", ")}</span></li>}
+ {p.commands.length > 0 && <li className="flex items-start gap-2"><TerminalSquare className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />Commands: {p.commands.join(", ")}</li>}
+ </ul>
+ );
+}
+
+function SettingField({ s, disabled, onSave }: { s: PluginSetting; disabled: boolean; onSave: (v: unknown) => void }) {
+ const [draft, setDraft] = useState(s.value === undefined ? "" : String(s.value));
+ useEffect(() => setDraft(s.value === undefined ? "" : String(s.value)), [s.value]);
+ 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>
+ {s.type === "boolean" && (
+ <Switch id={`setting-${s.key}`} checked={s.value === true} disabled={disabled} onCheckedChange={(v) => onSave(v)} />
+ )}
+ </div>
+ {s.description && <p className="text-xs text-muted-foreground">{s.description}</p>}
+ {s.type === "enum" ? (
+ <select
+ id={`setting-${s.key}`}
+ className="h-9 w-full rounded-md border border-input bg-background px-2 text-sm"
+ value={String(s.value ?? "")}
+ disabled={disabled}
+ onChange={(e) => onSave(e.target.value)}
+ >
+ {(s.options ?? []).map((o) => <option key={o} value={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" />
+ <Button size="sm" variant="outline" type="submit" disabled={disabled || draft === String(s.value ?? "")}>Save</Button>
+ </form>
+ ) : null}
+ </div>
+ );
+}
+
+function PluginDetails({ p, busy, safeMode, onAct, onInstall, onClose }: {
+ p: PluginItem;
+ busy: boolean;
+ safeMode: boolean;
+ onAct: (id: string, label: string, fn: () => Promise<unknown>) => Promise<void>;
+ onInstall: () => void;
+ onClose: () => void;
+}) {
+ const [purge, setPurge] = useState(false);
+ const [confirmRemove, setConfirmRemove] = useState(false);
+ const s = STATUS[p.status];
+ const note = statusNote(p);
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">{p.name}<Badge variant={s.variant}>{s.label}</Badge></DialogTitle>
+ <DialogDescription>{p.description}</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4 text-sm">
+ <p className="font-mono text-xs text-muted-foreground">
+ {p.id} · {p.installedVersion ? `installed ${p.installedVersion}` : `latest ${p.latestVersion}`}
+ {p.installedVersion && p.latestVersion && p.latestVersion !== p.installedVersion ? ` · catalog ${p.latestVersion}` : ""}
+ {" · "}{p.tier === "local" ? "local source (unverified)" : `${p.tier} catalog${p.verified ? ", verified" : ""}`}
+ </p>
+ {note && <p className="rounded-md border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive">{note}</p>}
+ <PermissionList p={p} />
+ {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) => (
+ <SettingField
+ key={setting.key}
+ s={setting}
+ disabled={busy}
+ onSave={(v) => onAct(p.id, `Saved ${setting.key}`, () => api.plugins.setSetting(p.id, setting.key, v))}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ <DialogFooter className="flex-wrap gap-2 sm:justify-between">
+ {p.installedVersion ? (
+ <>
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" variant="outline" disabled={busy} onClick={() => onAct(p.id, `Rolled back ${p.name}`, () => api.plugins.rollback(p.id))}>
+ <Undo2 className="h-4 w-4" />Roll back
+ </Button>
+ <Button size="sm" variant="outline" className="text-destructive" disabled={busy} onClick={() => setConfirmRemove(true)}>
+ <Trash2 className="h-4 w-4" />Uninstall
+ </Button>
+ </div>
+ <Button
+ size="sm"
+ disabled={busy || safeMode}
+ onClick={() => onAct(p.id, p.enabled ? `Disabled ${p.name}` : `Enabled ${p.name}`, () => (p.enabled ? api.plugins.disable(p.id) : api.plugins.enable(p.id)))}
+ >
+ {busy && <Loader2 className="h-4 w-4 animate-spin" />}
+ {p.enabled ? "Disable" : "Enable"}
+ </Button>
+ </>
+ ) : (
+ <Button size="sm" disabled={busy || p.status === "incompatible"} onClick={onInstall}>Install</Button>
+ )}
+ </DialogFooter>
+
+ <AlertDialog open={confirmRemove} onOpenChange={setConfirmRemove}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Uninstall {p.name}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Its code is removed and its tools disappear right away. {purge ? "Its data and settings are deleted too." : "Its data and settings are kept, so reinstalling picks up where it left off."}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <label className="flex items-center gap-2 text-sm">
+ <input type="checkbox" checked={purge} onChange={(e) => setPurge(e.target.checked)} />
+ Also delete its data and settings
+ </label>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ onClick={() => {
+ void onAct(p.id, `Uninstalled ${p.name}`, () => api.plugins.uninstall(p.id, purge)).then(onClose);
+ }}
+ >
+ Uninstall
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
diff --git a/website/docs/cli-commands/plugins.mdx b/website/docs/cli-commands/plugins.mdx
new file mode 100644
index 00000000..6c9cb5a2
--- /dev/null
+++ b/website/docs/cli-commands/plugins.mdx
@@ -0,0 +1,95 @@
+---
+id: plugins
+title: Plugins (install, enable, disable, remove)
+sidebar_label: Plugins
+---
+
+Plugins add features to Mercury that not everyone needs, without making the
+Mercury download bigger for everyone. You install the ones you want; the rest
+never touch your machine.
+
+A plugin can add **tools** the agent can use and, for some plugins, **slash
+commands** you can type. Every plugin can be turned off or removed at any
+time, and Mercury keeps running if a plugin breaks.
+
+## Four ways to manage plugins
+
+| Where | Example |
+|-------|---------|
+| Any chat (terminal, Telegram, web, Discord, Slack) | `/plugins` |
+| Shell | `mercury plugins list` |
+| Web dashboard | **Configure → Plugins** |
+| Telegram buttons | `/plugins`, then tap **Install**, **Disable** or **Uninstall** |
+
+They all do the same thing. If Mercury is running in the background, the
+shell commands ask it to make the change, so plugins start and stop right
+away without a restart.
+
+## Commands
+
+| Chat | Shell | What it does |
+|------|-------|--------------|
+| `/plugins` | `mercury plugins` | Installed and available plugins, with status |
+| `/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 |
+| `/plugins enable ID` | `mercury plugins enable ID` | Turn it on |
+| `/plugins disable ID` | `mercury plugins disable ID` | Turn it off. Its data and settings are kept |
+| `/plugins update` | `mercury plugins update` | Update catalog plugins (or one: `update ID`) |
+| `/plugins rollback ID` | `mercury plugins rollback ID` | Go back to the version you had before |
+| `/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 |
+
+`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.
+
+Only the owner (and admins on Telegram, Discord and Slack) can install or
+change plugins. In the web dashboard, changes are accepted only from the
+computer Mercury runs on.
+
+## What keeps Mercury safe from a bad plugin
+
+- **Two kinds of plugin.** *Own process* plugins run as a separate program:
+ if they crash, Mercury restarts them, and after repeated crashes turns them
+ off. *In-process* plugins run inside Mercury, with timeouts on everything
+ they do.
+- **Only what it declared.** A plugin can reach only the websites and read
+ only the secrets listed in its manifest. `/plugins info` shows both, and
+ install shows them before you confirm.
+- **Tools ask first.** A plugin tool that changes anything asks for your
+ approval like any built-in tool. Bots never see plugin tools unless you
+ allow them in the bot's tool list (`weather__forecast`, or `weather__*` for
+ all of one plugin's tools).
+- **Automatic turn-off.** A plugin is turned off, and you get a message
+ saying why, when:
+ - it fails 5 times in a row;
+ - it crashes too often;
+ - its files changed since install;
+ - it isn't compatible with your Mercury version;
+ - Mercury failed to start twice right after it was installed or updated.
+- **Clean removal.** Disable or uninstall stops its timers, network requests
+ and tools straight away. No restart needed.
+- **Updates you can undo.** The previous version is kept, so
+ `/plugins rollback ID` brings it back, with its settings.
+
+## Safe mode
+
+If Mercury won't start after a plugin change, start it with every plugin off:
+
+```sh
+mercury start --safe-mode # or: MERCURY_PLUGINS=off mercury start
+mercury doctor --plugins # what's installed, what's off and why
+```
+
+## Where things live
+
+```
+~/.mercury/plugins/
+ state.json installed / enabled
+ ID/versions/VERSION/ the plugin (current + previous)
+ ID/data/ the plugin's own data (kept on uninstall unless --purge)
+ ID/settings.json your settings for it
+```
+
+Writing a plugin? See [Reference → Writing plugins](../reference/plugins).
diff --git a/website/docs/reference/plugins.mdx b/website/docs/reference/plugins.mdx
new file mode 100644
index 00000000..e3c26050
--- /dev/null
+++ b/website/docs/reference/plugins.mdx
@@ -0,0 +1,156 @@
+---
+id: plugins
+title: Writing plugins
+sidebar_label: Writing plugins
+---
+
+A Mercury plugin is a folder with a `mercury-plugin.json` manifest and code.
+Start from a working one:
+
+```sh
+mercury plugins init my-plugin # runs inside Mercury
+mercury plugins init my-plugin --out-of-process # an MCP server in its own process
+cd my-plugin
+mercury plugins validate . # check it the way Mercury will run it
+mercury plugins install . --yes # try it in your Mercury
+mercury plugins pack . # .tgz + checksum + catalog entry
+```
+
+No npm package is needed: `init` writes the API types next to your code as
+`mercury-plugin.d.ts`.
+
+## Which kind?
+
+| | In-process | Out-of-process |
+|---|---|---|
+| Runs | Inside Mercury, loaded with `import()` | As a child process speaking MCP over stdio |
+| Good for | Small, fast tools; slash commands | Native code, heavy work, existing MCP servers, other languages |
+| If it crashes | Errors are contained and counted; repeated failures turn it off | Mercury restarts it; repeated crashes turn it off |
+| Slash commands | Yes | Not in plugin API 1.0 |
+
+## The manifest
+
+```json
+{
+ "manifestVersion": 1,
+ "id": "weather",
+ "name": "Weather",
+ "version": "1.2.0",
+ "description": "Forecasts and alerts.",
+ "kind": "in-process",
+ "engines": { "mercury": ">=1.4.0 <2.0.0", "pluginApi": "^1.0.0" },
+ "entry": "index.mjs",
+ "contributes": {
+ "tools": [{ "name": "forecast", "description": "Get the forecast for a city.", "readOnly": true, "timeoutMs": 20000 }],
+ "commands": [{ "name": "weather", "description": "Today's weather" }]
+ },
+ "permissions": { "network": ["api.weather.example"], "secrets": ["WEATHER_API_KEY"] },
+ "settings": {
+ "version": 2,
+ "fields": { "unit": { "type": "enum", "options": ["c", "f"], "default": "c" } },
+ "migrations": [{ "to": 2, "rename": { "units": "unit" }, "mapValues": { "unit": { "celsius": "c", "fahrenheit": "f" } } }]
+ }
+}
+```
+
+- **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.
+- **Commands** can't use a built-in name (`/help`, `/stop`, `/bots` and so on).
+- **permissions.network** lists the hosts `ctx.fetch` may reach (`*.example.com`
+ works). Private and loopback addresses are always blocked.
+- **permissions.secrets** lists the names from `~/.mercury/.env` the plugin
+ may read. Nothing else is visible to it.
+- Out-of-process plugins use `"server": { "command": "node", "args": ["server.mjs"] }`.
+ `node` means Mercury's own runtime, so users don't need Node installed.
+ It can also be a binary inside the package, with per-platform variants
+ under `server.platforms` and their SHA-256 in `checksums`.
+
+## In-process API
+
+```js
+/** @param {import('./mercury-plugin').PluginContext} ctx */
+export async function activate(ctx) {
+ ctx.tools.register({
+ name: 'forecast',
+ inputSchema: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] },
+ execute: async ({ city }, { signal }) => {
+ const res = await ctx.fetch(`https://api.weather.example/v1?q=${encodeURIComponent(city)}`, {
+ headers: { authorization: `Bearer ${ctx.secrets.get('WEATHER_API_KEY')}` },
+ signal,
+ });
+ return await res.json();
+ },
+ });
+ ctx.timers.setInterval(() => ctx.log.debug('tick'), 60_000);
+}
+```
+
+The context provides:
+
+- `ctx.tools`, `ctx.commands`
+- `ctx.settings`, `ctx.secrets`
+- `ctx.fetch`
+- `ctx.timers`
+- `ctx.log`
+- `ctx.plugin.dataDir`, a folder kept across updates
+- `ctx.signal`, aborted when the plugin stops
+- `ctx.onDispose`
+
+Everything registered or scheduled through `ctx` is cleaned up automatically
+when the plugin is turned off, updated or removed.
+
+## Rules for a stable plugin
+
+These are checked by `mercury plugins validate`:
+
+1. **One self-contained file.** Bundle your dependencies
+ (`esbuild src/index.ts --bundle --format=esm --platform=node --outfile=index.mjs`).
+ A compiled Mercury can't resolve npm packages for you; only `node:`
+ builtins and files in your package load.
+2. **Hot plug.** Your plugin must start, stop and start again cleanly, with
+ no restart of Mercury. Use `ctx.timers` and `ctx.signal`, not globals.
+3. **Clean up.** Anything you start outside `ctx`, stop in `ctx.onDispose`.
+4. **Versioned contract.** Declare `engines.pluginApi`. Plugin API minor
+ versions only add. A breaking change is a new major, and the previous one
+ stays supported for at least two Mercury minor releases.
+5. **Settings migrations.** If you rename or remove a setting, or change its
+ meaning, do two things:
+ - bump `settings.version`;
+ - add a `migrations` step (`rename`, `remove`, `mapValues`).
+
+ Saved values then carry over on update. Rolling back restores the older
+ version's settings.
+6. **No plugin-to-plugin dependencies** in plugin API 1.0. Each plugin stands
+ alone.
+
+## Out-of-process (MCP)
+
+Mercury starts the server and runs the handshake:
+
+1. `initialize`, then `notifications/initialized`
+2. `tools/list`, which exposes only the tools your manifest declares
+3. `tools/call` for each tool use
+
+It also handles `ping` and `notifications/tools/list_changed`. It cancels
+calls with `notifications/cancelled` when a turn stops.
+
+What your server receives:
+
+- **Settings:** JSON in the `MERCURY_PLUGIN_SETTINGS` environment variable.
+- **Data folder:** `MERCURY_PLUGIN_DATA_DIR`.
+- **Secrets:** the declared secrets, as environment variables.
+
+Write logs to stderr. Stdout is the protocol channel.
+
+## Publishing
+
+`mercury plugins pack .` writes `ID-VERSION.tgz` and prints its SHA-256 and
+a catalog entry. Then:
+
+- **Share it from GitHub.** Attach the file to a GitHub release as
+ `mercury-plugin.tgz` (or `mercury-plugin-PLATFORM.tgz` per platform).
+ Anyone can then install it with `mercury plugins install github:owner/repo`.
+- **List it in `/plugins`.** Open a pull request adding the entry to the
+ catalog at `website/static/plugins/catalog.json`. Catalog installs are
+ checksum-verified.
diff --git a/website/sidebars.ts b/website/sidebars.ts
index a19054f9..902411de 100644
--- a/website/sidebars.ts
+++ b/website/sidebars.ts
@@ -26,6 +26,7 @@ const sidebars: SidebarsConfig = {
'cli-commands/cli-commands',
'cli-commands/doctor',
'cli-commands/skills',
+ 'cli-commands/plugins',
'cli-commands/in-chat-commands',
],
},
@@ -66,6 +67,7 @@ const sidebars: SidebarsConfig = {
'reference/completion-architecture',
'reference/configuration',
'reference/permissions',
+ 'reference/plugins',
'reference/second-brain',
'reference/provider-fallback',
'reference/scheduling',
diff --git a/website/static/plugins/catalog.json b/website/static/plugins/catalog.json
new file mode 100644
index 00000000..28320741
--- /dev/null
+++ b/website/static/plugins/catalog.json
@@ -0,0 +1,5 @@
+{
+ "catalogVersion": 1,
+ "updatedAt": "2026-10-20T00:00:00Z",
+ "plugins": []
+}