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/mercury skills (#67)

Salman Qureshi4ca6a086c7ad
diff --git a/README.md b/README.md
index ce7736c2..89a25c99 100644
--- a/README.md
+++ b/README.md
@@ -193,6 +193,41 @@ Type these during a conversation — they don't consume API tokens. Work on both
| **Scheduler** | `schedule_task`, `list_scheduled_tasks`, `cancel_scheduled_task` |
| **System** | `budget_status` |
+## Installing Skills
+
+Mercury can pull community-contributed skills from the registry at
+**[skills.mercuryagent.sh](https://skills.mercuryagent.sh)** (126+ skills, no auth required).
+
+```bash
+mercury skills search prompt # search the registry
+mercury skills browse ai-ml # browse by category
+mercury skills view ai-ml/prompt-engineering # render SKILL.md in the terminal
+mercury skills view ai-ml/prompt-engineering --web # open the registry page
+mercury skills install ai-ml/prompt-engineering # install to ~/.mercury/skills/
+mercury skills list # show installed skills
+mercury skills update # refresh all installed skills
+mercury skills remove ai-ml/prompt-engineering
+mercury skills doctor # check install root + registry
+```
+
+Installed skills land at `~/.mercury/skills/<category>/<slug>/SKILL.md` and are
+picked up by the agent on the next boot — they're treated identically to
+built-in skills.
+
+> **Review before you ship.** Skills are community-contributed and unaudited.
+> Run `mercury skills view <id>` before installing.
+
+Overrides: `--registry <url>` (or `MERCURY_SKILLS_REGISTRY`) for self-hosted
+registries, `MERCURY_SKILLS_INSTALL_ROOT` for an alternate install path,
+`--json` for machine-readable output.
+
+**Also installable from:**
+
+- **Web dashboard** — `http://127.0.0.1:6174/skills` has a registry installer (paste `category/slug`) and a URL installer side by side.
+- **Telegram** — `/skills`, `/skills search <q>`, `/skills view <id>`, `/skills install <id>` (admin-only). Every result includes the registry URL so you can review before installing.
+
+See the [Skills reference](https://mercuryagent.sh/docs/reference/skills) for the full command surface, frontmatter spec, and API endpoints.
+
## Web Dashboard
Mercury includes a built-in web UI at `http://127.0.0.1:6174`:
diff --git a/src/channels/telegram.ts b/src/channels/telegram.ts
index d6c65cb2..0a66f150 100644
--- a/src/channels/telegram.ts
+++ b/src/channels/telegram.ts
@@ -22,6 +22,9 @@ import {
import { logger } from '../utils/logger.js';
import { mdToTelegram } from '../utils/markdown.js';
import { formatToolStep, formatToolResult } from '../utils/tool-label.js';
+import { RegistryClient, isValidSkillId, searchFeed, type RegistrySkillSummary } from '../skills/registry.js';
+import { SkillStore } from '../skills/store.js';
+import { SkillLoader } from '../skills/loader.js';
const MAX_MESSAGE_LENGTH = 4096;
const ACCESS_ACTION_PREFIX = 'tg_access';
@@ -180,6 +183,11 @@ export class TelegramChannel extends BaseChannel {
return;
}
+ if (command === '/skills') {
+ await this.handleSkillsCommand(chatId, userId, text);
+ return;
+ }
+
if (command === '/permissions') {
this.askPermissionMode(`telegram:${chatId}`).then((mode) => {
this.permissionModes.set(chatId, mode);
@@ -269,6 +277,7 @@ export class TelegramChannel extends BaseChannel {
{ command: 'agents', description: 'List and manage sub-agents' },
{ 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: 'unpair', description: 'Reset all Telegram access (admin only)' },
];
@@ -1050,6 +1059,189 @@ export class TelegramChannel extends BaseChannel {
return text.trim().split(/\s+/)[0]?.toLowerCase() || '';
}
+ private async handleSkillsCommand(chatId: number, userId: number, text: string): Promise<void> {
+ const parts = text.trim().split(/\s+/).slice(1);
+ const sub = (parts[0] || 'list').toLowerCase();
+ const args = parts.slice(1);
+ const arg = args.join(' ').trim();
+
+ const registry = new RegistryClient();
+ const store = new SkillStore({ registry });
+ const loader = new SkillLoader();
+
+ try {
+ switch (sub) {
+ case 'help':
+ case '-h':
+ case '--help': {
+ await this.sendDirectMessage(
+ chatId,
+ [
+ '*Mercury Skills — Telegram*',
+ '',
+ '`/skills` — list installed skills',
+ '`/skills search <query>` — search the registry',
+ '`/skills view <id>` — show details + registry URL',
+ '`/skills install <id>` — admin only',
+ '`/skills remove <id>` — admin only',
+ '',
+ 'Registry: https://skills.mercuryagent.sh',
+ ].join('\n'),
+ );
+ return;
+ }
+
+ case 'list': {
+ const installed = loader.getAllSkills();
+ if (installed.length === 0) {
+ await this.sendDirectMessage(
+ chatId,
+ 'No skills installed.\n\nTry `/skills search <query>` to browse https://skills.mercuryagent.sh.',
+ );
+ return;
+ }
+ const lines = installed
+ .slice(0, 25)
+ .map((s) => `• \`${s.name}\` — ${s.active ? 'active' : 'inactive'}${s.description ? ` — ${s.description}` : ''}`);
+ const more = installed.length > 25 ? `\n\n_…and ${installed.length - 25} more. Run \`mercury skills list\` for the full set._` : '';
+ await this.sendDirectMessage(
+ chatId,
+ `*Installed skills (${installed.length})*\n\n${lines.join('\n')}${more}`,
+ );
+ return;
+ }
+
+ case 'search':
+ case 'find': {
+ if (!arg) {
+ await this.sendDirectMessage(chatId, 'Usage: `/skills search <query>`');
+ return;
+ }
+ const feed = await registry.getFeed();
+ const scored = searchFeed(feed, arg, 5);
+ if (scored.length === 0) {
+ await this.sendDirectMessage(chatId, `No results for "${arg}".`);
+ return;
+ }
+ const results = scored.map((s) => s.skill);
+ const lines = results.map(
+ (r: RegistrySkillSummary) =>
+ `• \`${r.id}\` (v${r.version})\n ${r.description}\n ${registry.webUrl(r.id)}`,
+ );
+ await this.sendDirectMessage(
+ chatId,
+ `*Top ${results.length} matches for "${arg}"*\n\n${lines.join('\n\n')}\n\nReview a skill before installing: \`/skills view <id>\``,
+ );
+ return;
+ }
+
+ case 'view':
+ case 'show':
+ case 'info': {
+ if (!arg) {
+ await this.sendDirectMessage(chatId, 'Usage: `/skills view <category/slug>`');
+ return;
+ }
+ if (!isValidSkillId(arg)) {
+ await this.sendDirectMessage(chatId, 'Invalid skill id. Expected `<category>/<slug>`.');
+ return;
+ }
+ const detail = await registry.getSkill(arg);
+ const tags = detail.tags?.length ? `\n*Tags:* ${detail.tags.join(', ')}` : '';
+ const author = detail.author ? `\n*Author:* ${detail.author}` : '';
+ await this.sendDirectMessage(
+ chatId,
+ [
+ `*${detail.title}* (\`${detail.id}\`)`,
+ `*Version:* ${detail.version}`,
+ `*Category:* ${detail.category}`,
+ author,
+ tags,
+ '',
+ detail.description,
+ '',
+ `🔗 ${registry.webUrl(detail.id)}`,
+ '',
+ this.isAdminUser(userId)
+ ? 'Install with: `/skills install ' + detail.id + '`'
+ : 'Ask an admin to install: `/skills install ' + detail.id + '`',
+ ]
+ .filter(Boolean)
+ .join('\n'),
+ );
+ return;
+ }
+
+ case 'install':
+ case 'add': {
+ if (!this.isAdminUser(userId)) {
+ await this.sendDirectMessage(chatId, '🔒 Only Telegram admins can install skills.');
+ return;
+ }
+ if (!arg) {
+ await this.sendDirectMessage(chatId, 'Usage: `/skills install <category/slug>`');
+ return;
+ }
+ if (!isValidSkillId(arg)) {
+ await this.sendDirectMessage(chatId, 'Invalid skill id. Expected `<category>/<slug>`.');
+ return;
+ }
+ await this.sendDirectMessage(chatId, `Installing \`${arg}\`…`);
+ const result = await store.install(arg);
+ const verb =
+ result.status === 'already-installed'
+ ? 'Already installed'
+ : result.status === 'updated'
+ ? 'Updated'
+ : result.status === 'reinstalled'
+ ? 'Reinstalled'
+ : 'Installed';
+ await this.sendDirectMessage(
+ chatId,
+ `✅ ${verb} \`${result.id}\` (v${result.version})\n\n🔗 ${registry.webUrl(result.id)}`,
+ );
+ return;
+ }
+
+ case 'remove':
+ case 'rm':
+ case 'delete':
+ case 'uninstall': {
+ if (!this.isAdminUser(userId)) {
+ await this.sendDirectMessage(chatId, '🔒 Only Telegram admins can remove skills.');
+ return;
+ }
+ if (!arg) {
+ await this.sendDirectMessage(chatId, 'Usage: `/skills remove <category/slug>`');
+ return;
+ }
+ if (!isValidSkillId(arg)) {
+ await this.sendDirectMessage(chatId, 'Invalid skill id. Expected `<category>/<slug>`.');
+ return;
+ }
+ const removed = store.remove(arg);
+ if (!removed) {
+ await this.sendDirectMessage(chatId, `Skill \`${arg}\` is not installed.`);
+ return;
+ }
+ await this.sendDirectMessage(chatId, `🗑 Removed \`${arg}\`.`);
+ return;
+ }
+
+ default: {
+ await this.sendDirectMessage(
+ chatId,
+ `Unknown subcommand \`${sub}\`. Try \`/skills help\`.`,
+ );
+ }
+ }
+ } catch (err: any) {
+ const msg = err?.message || 'Skill registry request failed';
+ logger.warn({ err: msg, sub, arg }, 'Telegram /skills command failed');
+ await this.sendDirectMessage(chatId, `⚠️ ${msg}`);
+ }
+ }
+
private getPendingStatusMessage(request?: TelegramPendingRequest): string {
if (!hasTelegramAdmins(this.config)) {
const pairingCode = request?.pairingCode ?? 'unknown';
diff --git a/src/core/agent.ts b/src/core/agent.ts
index a1287d76..29189891 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -2249,6 +2249,200 @@ Is this productive iteration or a stuck loop?`,
}
}
+ private async handleSkillsSlashCommand(
+ trimmed: string,
+ channel: any,
+ channelId: string,
+ ctx: { skillNames: () => string[] },
+ ): Promise<void> {
+ const parts = trimmed.split(/\s+/).slice(1);
+ const sub = (parts[0] || 'list').toLowerCase();
+ const args = parts.slice(1);
+ const arg = args.join(' ').trim();
+
+ const { RegistryClient, isValidSkillId, searchFeed } = await import('../skills/registry.js');
+ const { SkillStore } = await import('../skills/store.js');
+ const registry = new RegistryClient();
+ const store = new SkillStore({ registry });
+
+ try {
+ switch (sub) {
+ case 'help':
+ case '-h':
+ case '--help': {
+ await channel.send(
+ [
+ '**Mercury Skills — in-chat commands**',
+ '',
+ '`/skills` — list installed skills',
+ '`/skills search <query>` — search the registry',
+ '`/skills view <id>` — show details + registry URL',
+ '`/skills install <id>` — install from the registry',
+ '`/skills install <url>` — install raw SKILL.md from a URL',
+ '`/skills remove <id>` — uninstall',
+ '',
+ 'Browse the full catalog at https://skills.mercuryagent.sh',
+ ].join('\n'),
+ channelId,
+ );
+ return;
+ }
+
+ case 'list': {
+ const names = ctx.skillNames();
+ if (names.length === 0) {
+ await channel.send(
+ 'No skills installed. Try `/skills search <query>` to browse https://skills.mercuryagent.sh.',
+ channelId,
+ );
+ return;
+ }
+ const lines = [
+ `**${names.length} skill${names.length > 1 ? 's' : ''} installed:**`,
+ '',
+ ...names.map((n) => `• ${n}`),
+ '',
+ '_Run `/skills search <query>` to find more on the registry._',
+ ];
+ await channel.send(lines.join('\n'), channelId);
+ return;
+ }
+
+ case 'search':
+ case 'find': {
+ if (!arg) {
+ await channel.send('Usage: `/skills search <query>`', channelId);
+ return;
+ }
+ await channel.send(`🔍 Searching the registry for "${arg}"…`, channelId);
+ const feed = await registry.getFeed();
+ const scored = searchFeed(feed, arg, 5);
+ if (scored.length === 0) {
+ await channel.send(`No matches for "${arg}".`, channelId);
+ return;
+ }
+ const lines = scored.map(({ skill }) =>
+ [
+ `• \`${skill.id}\` (v${skill.version})`,
+ ` ${skill.description}`,
+ ` ${registry.webUrl(skill.id)}`,
+ ].join('\n'),
+ );
+ await channel.send(
+ [
+ `**Top ${scored.length} matches for "${arg}":**`,
+ '',
+ lines.join('\n\n'),
+ '',
+ 'Inspect one with `/skills view <id>`, install with `/skills install <id>`.',
+ ].join('\n'),
+ channelId,
+ );
+ return;
+ }
+
+ case 'view':
+ case 'show':
+ case 'info': {
+ if (!arg) {
+ await channel.send('Usage: `/skills view <category/slug>`', channelId);
+ return;
+ }
+ if (!isValidSkillId(arg)) {
+ await channel.send('Invalid skill id. Expected `<category>/<slug>`.', channelId);
+ return;
+ }
+ const detail = await registry.getSkill(arg);
+ const author = detail.author ? `\n**Author:** ${detail.author}` : '';
+ const tags = detail.tags?.length ? `\n**Tags:** ${detail.tags.join(', ')}` : '';
+ await channel.send(
+ [
+ `**${detail.title}** (\`${detail.id}\`)`,
+ `**Version:** ${detail.version}`,
+ `**Category:** ${detail.category}${author}${tags}`,
+ '',
+ detail.description,
+ '',
+ `🔗 ${registry.webUrl(detail.id)}`,
+ '',
+ `Install with \`/skills install ${detail.id}\``,
+ ].join('\n'),
+ channelId,
+ );
+ return;
+ }
+
+ case 'install':
+ case 'add': {
+ if (!arg) {
+ await channel.send('Usage: `/skills install <category/slug>` or `/skills install <url>`', channelId);
+ return;
+ }
+ // URL install → delegate to the existing capability path
+ if (/^https?:\/\//i.test(arg)) {
+ const { SkillLoader } = await import('../skills/loader.js');
+ const loader = new SkillLoader();
+ await channel.send(`📦 Installing from \`${arg}\`…`, channelId);
+ const installed = await loader.installFromUrl(arg);
+ await channel.send(
+ `✅ Installed \`${installed.name}\` from URL.\n${installed.skillDir}`,
+ channelId,
+ );
+ return;
+ }
+ if (!isValidSkillId(arg)) {
+ await channel.send('Invalid skill id. Expected `<category>/<slug>` or a `https://` URL.', channelId);
+ return;
+ }
+ await channel.send(`📦 Installing \`${arg}\` from the registry…`, channelId);
+ const result = await store.install(arg);
+ const verb =
+ result.status === 'already-installed'
+ ? 'Already installed'
+ : result.status === 'updated'
+ ? 'Updated'
+ : result.status === 'reinstalled'
+ ? 'Reinstalled'
+ : 'Installed';
+ await channel.send(
+ `✅ ${verb} \`${result.id}\` (v${result.version})\n🔗 ${registry.webUrl(result.id)}`,
+ channelId,
+ );
+ return;
+ }
+
+ case 'remove':
+ case 'rm':
+ case 'delete':
+ case 'uninstall': {
+ if (!arg) {
+ await channel.send('Usage: `/skills remove <category/slug>`', channelId);
+ return;
+ }
+ if (!isValidSkillId(arg)) {
+ await channel.send('Invalid skill id. Expected `<category>/<slug>`.', channelId);
+ return;
+ }
+ const removed = store.remove(arg);
+ await channel.send(
+ removed ? `🗑 Removed \`${arg}\`.` : `Skill \`${arg}\` is not installed.`,
+ channelId,
+ );
+ return;
+ }
+
+ default:
+ await channel.send(
+ `Unknown subcommand \`${sub}\`. Try \`/skills help\`.`,
+ channelId,
+ );
+ }
+ } catch (err: any) {
+ const msg = err?.message || 'Skill registry request failed';
+ await channel.send(`⚠️ ${msg}`, channelId);
+ }
+ }
+
private async handleChatCommand(content: string, channelType: string, channelId: string): Promise<boolean> {
const trimmed = content.trim();
const cmd = trimmed.toLowerCase();
@@ -2614,18 +2808,8 @@ Is this productive iteration or a stuck loop?`,
return true;
}
- if (cmd === '/skills') {
- const names = ctx.skillNames();
- if (names.length === 0) {
- await channel.send('No skills installed. Ask me to "install skill from <url>" to add one.', channelId);
- } else {
- const lines = [
- `**${names.length} skill${names.length > 1 ? 's' : ''} installed:**`,
- '',
- ...names.map(n => `• ${n}`),
- ];
- await channel.send(lines.join('\n'), channelId);
- }
+ if (cmd === '/skills' || cmd.startsWith('/skills ')) {
+ await this.handleSkillsSlashCommand(trimmed, channel, channelId, ctx);
return true;
}
diff --git a/src/index.ts b/src/index.ts
index 844dafee..1117984d 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -44,6 +44,7 @@ import { WebChannel } from './channels/web.js';
import { TokenBudget } from './utils/tokens.js';
import { CapabilityRegistry } from './capabilities/registry.js';
import { SkillLoader } from './skills/loader.js';
+import { registerSkillsCommand } from './skills/cli.js';
import { getManual } from './utils/manual.js';
import { startBackground, stopDaemon, showLogs, getDaemonStatus, restartDaemon, tryAutoDaemonize } from './cli/daemon.js';
import { installService, uninstallService, showServiceStatus, isServiceInstalled } from './cli/service.js';
@@ -2286,4 +2287,6 @@ program
console.log('');
});
+registerSkillsCommand(program);
+
program.parse();
diff --git a/src/skills/cli.ts b/src/skills/cli.ts
new file mode 100644
index 00000000..4057f2f3
--- /dev/null
+++ b/src/skills/cli.ts
@@ -0,0 +1,448 @@
+/**
+ * `mercury skills ...` CLI command handlers.
+ *
+ * Wired in src/index.ts via registerSkillsCommand(program). All handlers
+ * print human-readable, chalk-colored output by default and structured JSON
+ * when `--json` is passed.
+ */
+import { spawn } from 'node:child_process';
+import { existsSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { homedir, platform } from 'node:os';
+import { Command } from 'commander';
+import chalk from 'chalk';
+import { RegistryClient, RegistryError, searchFeed, type RegistrySkillSummary, type ScoredSkill } from './registry.js';
+import { SkillStore, isValidSkillId } from './store.js';
+import { renderMarkdown } from '../utils/markdown.js';
+import { getMercuryHome } from '../utils/config.js';
+
+interface GlobalSkillFlags {
+ json?: boolean;
+ registry?: string;
+ quiet?: boolean;
+ yes?: boolean;
+}
+
+function inheritedFlags(cmd: Command): GlobalSkillFlags {
+ // Walk up to gather shared flags from the `skills` parent.
+ const opts: Record<string, unknown> = {};
+ let c: Command | null = cmd;
+ while (c) {
+ Object.assign(opts, c.opts());
+ c = c.parent;
+ }
+ return opts as GlobalSkillFlags;
+}
+
+function makeRegistry(flags: GlobalSkillFlags): RegistryClient {
+ const url =
+ flags.registry ||
+ process.env.MERCURY_SKILLS_REGISTRY ||
+ 'https://skills.mercuryagent.sh';
+ return new RegistryClient({ registry: url });
+}
+
+function makeStore(): SkillStore {
+ const installRoot =
+ process.env.MERCURY_SKILLS_INSTALL_ROOT ||
+ `${getMercuryHome()}/skills`;
+ return new SkillStore({ installRoot });
+}
+
+function out(flags: GlobalSkillFlags, ...args: unknown[]): void {
+ if (flags.quiet) return;
+ console.log(...args);
+}
+
+function emitJson(value: unknown): void {
+ process.stdout.write(JSON.stringify(value, null, 2) + '\n');
+}
+
+function fail(flags: GlobalSkillFlags, message: string, extra: Record<string, unknown> = {}): never {
+ if (flags.json) {
+ process.stderr.write(JSON.stringify({ ok: false, error: message, ...extra }) + '\n');
+ } else {
+ console.error(chalk.red(`error: ${message}`));
+ }
+ process.exit(1);
+}
+
+function categoryLabel(skill: Pick<RegistrySkillSummary, 'category' | 'categorySlug'>): string {
+ return skill.category || skill.categorySlug || '';
+}
+
+// ---------- subcommands ----------
+
+async function cmdInfo(_args: unknown, cmd: Command): Promise<void> {
+ const flags = inheritedFlags(cmd);
+ const registry = makeRegistry(flags);
+ const store = makeStore();
+ const installed = store.list();
+ if (flags.json) {
+ emitJson({
+ registry: registry.registryUrl,
+ installRoot: store.installRoot,
+ cacheDir: registry.cacheDir,
+ cacheTtlSeconds: registry.cacheTtlMs / 1000,
+ installed: installed.length,
+ });
+ return;
+ }
+ out(flags, chalk.bold('Mercury skills'));
+ out(flags, ` Registry: ${chalk.cyan(registry.registryUrl)}`);
+ out(flags, ` Install root: ${chalk.cyan(store.installRoot)}`);
+ out(flags, ` Cache dir: ${chalk.cyan(registry.cacheDir)}`);
+ out(flags, ` Cache TTL: ${registry.cacheTtlMs / 1000}s`);
+ out(flags, ` Installed: ${chalk.bold(String(installed.length))} skill${installed.length === 1 ? '' : 's'}`);
+}
+
+async function cmdList(_args: unknown, cmd: Command): Promise<void> {
+ const flags = inheritedFlags(cmd);
+ const store = makeStore();
+ const installed = store.list();
+ if (flags.json) {
+ emitJson({ skills: installed });
+ return;
+ }
+ if (installed.length === 0) {
+ out(flags, chalk.dim('No skills installed. Try:'));
+ out(flags, chalk.dim(' mercury skills search <query>'));
+ out(flags, chalk.dim(' mercury skills browse'));
+ return;
+ }
+ out(flags, chalk.bold(`Installed skills (${installed.length}):`));
+ for (const s of installed) {
+ out(
+ flags,
+ ` ${chalk.cyan(s.id)} ${chalk.dim('·')} v${s.version} ${chalk.dim('·')} ${chalk.dim(new Date(s.installedAt).toISOString().slice(0, 10))}`,
+ );
+ if (s.description) out(flags, ` ${chalk.dim(s.description)}`);
+ }
+}
+
+async function cmdCategories(_args: unknown, cmd: Command): Promise<void> {
+ const flags = inheritedFlags(cmd);
+ const registry = makeRegistry(flags);
+ try {
+ const feed = await registry.getFeed();
+ if (flags.json) { emitJson({ categories: feed.categories }); return; }
+ out(flags, chalk.bold(`Categories (${feed.categories.length}):`));
+ for (const c of [...feed.categories].sort((a, b) => b.count - a.count)) {
+ out(flags, ` ${chalk.cyan(c.slug.padEnd(24))} ${String(c.count).padStart(4)} ${chalk.dim(c.name)}`);
+ }
+ } catch (err: any) {
+ fail(flags, err?.message || String(err));
+ }
+}
+
+async function cmdBrowse(category: string | undefined, _opts: unknown, cmd: Command): Promise<void> {
+ const flags = inheritedFlags(cmd);
+ const opts = cmd.opts<{ page?: string; limit?: string }>();
+ const registry = makeRegistry(flags);
+ try {
+ const feed = await registry.getFeed();
+ let skills = feed.skills;
+ if (category) {
+ const want = category.toLowerCase();
+ skills = skills.filter((s) => s.categorySlug?.toLowerCase() === want || s.category?.toLowerCase() === want);
+ }
+ const page = Math.max(1, parseInt(opts.page || '1', 10));
+ const limit = Math.max(1, parseInt(opts.limit || '20', 10));
+ const start = (page - 1) * limit;
+ const slice = skills.slice(start, start + limit);
+
+ if (flags.json) {
+ emitJson({ total: skills.length, page, limit, skills: slice });
+ return;
+ }
+ if (skills.length === 0) {
+ out(flags, chalk.dim(`No skills${category ? ` in category "${category}"` : ''}.`));
+ return;
+ }
+ out(flags, chalk.bold(`${skills.length} skill${skills.length === 1 ? '' : 's'}${category ? ` in ${category}` : ''} — page ${page}/${Math.ceil(skills.length / limit)}`));
+ for (const s of slice) printSkillRow(s);
+ out(flags, chalk.dim(`\nInstall with: mercury skills install <id>`));
+ if (start + limit < skills.length) {
+ out(flags, chalk.dim(`Next page: mercury skills browse${category ? ` ${category}` : ''} --page ${page + 1}`));
+ }
+ } catch (err: any) {
+ fail(flags, err?.message || String(err));
+ }
+}
+
+async function cmdSearch(query: string, _opts: unknown, cmd: Command): Promise<void> {
+ const flags = inheritedFlags(cmd);
+ const opts = cmd.opts<{ limit?: string }>();
+ const registry = makeRegistry(flags);
+ const limit = Math.max(1, parseInt(opts.limit || '10', 10));
+ try {
+ const feed = await registry.getFeed();
+ const results = searchFeed(feed, query, limit);
+ if (flags.json) {
+ emitJson({ query, results: results.map((r) => ({ score: r.score, ...r.skill })) });
+ return;
+ }
+ if (results.length === 0) {
+ out(flags, chalk.dim(`No matches for "${query}".`));
+ return;
+ }
+ for (const r of results) printSkillRow(r.skill);
+ out(flags, chalk.dim(`\nInstall with: mercury skills install <id>`));
+ } catch (err: any) {
+ fail(flags, err?.message || String(err));
+ }
+}
+
+function printSkillRow(s: RegistrySkillSummary): void {
+ console.log(
+ `${chalk.cyan(s.id)} ${chalk.dim('·')} v${s.version} ${chalk.dim('·')} ${chalk.dim(categoryLabel(s))}`,
+ );
+ if (s.description) console.log(` ${s.description}`);
+}
+
+async function cmdView(id: string, _opts: unknown, cmd: Command): Promise<void> {
+ const flags = inheritedFlags(cmd);
+ const opts = cmd.opts<{ web?: boolean; raw?: boolean }>();
+ const registry = makeRegistry(flags);
+
+ if (opts.web) {
+ await openInBrowser(registry.webUrl(id));
+ out(flags, chalk.dim(`Opened ${registry.webUrl(id)}`));
+ return;
+ }
+
+ // Prefer the installed copy if present.
+ const store = makeStore();
+ let body: string | null = null;
+ if (isValidSkillId(id)) {
+ try {
+ const local = store.pathFor(id);
+ if (existsSync(local)) body = readFileSync(local, 'utf-8');
+ } catch { /* ignore */ }
+ }
+ if (!body) {
+ try {
+ const fetched = await registry.fetchSkillMarkdown(id);
+ body = fetched.body;
+ } catch (err: any) {
+ if (err instanceof RegistryError) fail(flags, err.message, { id, status: err.status });
+ fail(flags, err?.message || String(err), { id });
+ }
+ }
+ if (flags.json) {
+ emitJson({ id, body });
+ return;
+ }
+ if (opts.raw) {
+ process.stdout.write(body!);
+ return;
+ }
+ process.stdout.write(renderMarkdown(body!));
+ if (!body!.endsWith('\n')) process.stdout.write('\n');
+}
+
+async function cmdInstall(ids: string[], _opts: unknown, cmd: Command): Promise<void> {
+ const flags = inheritedFlags(cmd);
+ const opts = cmd.opts<{ from?: string; force?: boolean }>();
+ const registry = makeRegistry(flags);
+ const store = makeStore();
+ store.ensureRoot();
+
+ // --from <url|path>: install a SKILL.md from a URL or local file (no registry lookup)
+ if (opts.from) {
+ if (ids.length > 0) fail(flags, 'Cannot combine --from with positional ids.');
+ try {
+ const body = await loadBodyFromSource(opts.from);
+ const result = store.installFromBody(body, { source: opts.from });
+ if (flags.json) { emitJson({ ok: true, ...result }); return; }
+ out(flags, chalk.green(`✓ ${result.id} (v${result.version}) — installed from ${opts.from}`));
+ } catch (err: any) {
+ fail(flags, err?.message || String(err));
+ }
+ return;
+ }
+
+ if (ids.length === 0) fail(flags, 'No skill id provided. Usage: mercury skills install <id> [<id>...]');
+
+ const results: Array<{ id: string; ok: boolean; status?: string; version?: string; error?: string }> = [];
+ let hadError = false;
+ for (const id of ids) {
+ if (!isValidSkillId(id)) {
+ hadError = true;
+ results.push({ id, ok: false, error: 'invalid id (expected <category-slug>/<skill-slug>)' });
+ if (!flags.json) console.error(chalk.red(`✗ ${id} — invalid id`));
+ continue;
+ }
+ try {
+ const r = await store.install(id, { force: opts.force, registry });
+ results.push({ id: r.id, ok: true, status: r.status, version: r.version });
+ if (!flags.json) {
+ if (r.status === 'already-installed') {
+ out(flags, chalk.yellow(`• ${r.id} already installed (v${r.version}); use --force to re-download`));
+ } else {
+ out(flags, chalk.green(`✓ ${r.id} (v${r.version})`));
+ }
+ }
+ } catch (err: any) {
+ hadError = true;
+ const status = err instanceof RegistryError ? err.status : undefined;
+ results.push({ id, ok: false, error: err?.message || String(err) });
+ if (!flags.json) console.error(chalk.red(`✗ ${id} — ${err?.message || err}${status ? ` (HTTP ${status})` : ''}`));
+ }
+ }
+ if (flags.json) emitJson({ ok: !hadError, results });
+ if (hadError) process.exit(1);
+}
+
+async function cmdRemove(id: string, _opts: unknown, cmd: Command): Promise<void> {
+ const flags = inheritedFlags(cmd);
+ const store = makeStore();
+ try {
+ if (!isValidSkillId(id)) fail(flags, `Invalid skill id "${id}".`, { id });
+ const ok = store.remove(id);
+ if (flags.json) { emitJson({ ok, id }); return; }
+ if (ok) out(flags, chalk.green(`✓ removed ${id}`));
+ else out(flags, chalk.yellow(`• ${id} was not installed`));
+ if (!ok) process.exit(1);
+ } catch (err: any) {
+ fail(flags, err?.message || String(err), { id });
+ }
+}
+
+async function cmdUpdate(id: string | undefined, _opts: unknown, cmd: Command): Promise<void> {
+ const flags = inheritedFlags(cmd);
+ const registry = makeRegistry(flags);
+ const store = makeStore();
+ const targets = id ? [id] : store.list().map((s) => s.id);
+ if (targets.length === 0) {
+ if (flags.json) { emitJson({ ok: true, updated: [] }); return; }
+ out(flags, chalk.dim('No installed skills to update.'));
+ return;
+ }
+ const results: Array<{ id: string; ok: boolean; status?: string; version?: string; error?: string }> = [];
+ let hadError = false;
+ for (const t of targets) {
+ try {
+ const r = await store.install(t, { force: true, registry });
+ results.push({ id: r.id, ok: true, status: r.status, version: r.version });
+ if (!flags.json) out(flags, chalk.green(`✓ ${r.id} (v${r.version})`));
+ } catch (err: any) {
+ hadError = true;
+ results.push({ id: t, ok: false, error: err?.message || String(err) });
+ if (!flags.json) console.error(chalk.red(`✗ ${t} — ${err?.message || err}`));
+ }
+ }
+ if (flags.json) emitJson({ ok: !hadError, updated: results });
+ if (hadError) process.exit(1);
+}
+
+async function cmdDoctor(_args: unknown, cmd: Command): Promise<void> {
+ const flags = inheritedFlags(cmd);
+ const registry = makeRegistry(flags);
+ const store = makeStore();
+ const h = store.health();
+ const ping = await registry.ping();
+
+ const ok = h.indexValid && h.orphaned.length === 0 && ping.ok;
+
+ if (flags.json) {
+ emitJson({ ok, store: h, registry: { url: registry.registryUrl, ...ping } });
+ process.exit(ok ? 0 : 1);
+ }
+
+ out(flags, chalk.bold('Skills doctor'));
+ out(flags, ` Install root: ${h.installRoot} ${h.rootExists ? chalk.green('[ok]') : chalk.yellow('[will be created on install]')}`);
+ out(flags, ` Index: ${h.indexExists ? (h.indexValid ? chalk.green('[ok]') : chalk.red('[invalid]')) : chalk.dim('[empty]')}`);
+ out(flags, ` Installed: ${h.installed}`);
+ if (h.orphaned.length > 0) out(flags, ` Orphaned: ${chalk.red(h.orphaned.join(', '))}`);
+ out(flags, ` Registry: ${registry.registryUrl} ${ping.ok ? chalk.green(`[ok ${ping.status}]`) : chalk.red(`[unreachable${ping.error ? ': ' + ping.error : ''}]`)}`);
+ process.exit(ok ? 0 : 1);
+}
+
+// ---------- helpers ----------
+
+async function loadBodyFromSource(source: string): Promise<string> {
+ if (/^https?:\/\//i.test(source)) {
+ const res = await fetch(source);
+ if (!res.ok) throw new Error(`Fetch failed: ${res.status} ${res.statusText}`);
+ return await res.text();
+ }
+ const abs = resolve(source.replace(/^~/, homedir()));
+ if (!existsSync(abs)) throw new Error(`File not found: ${abs}`);
+ return readFileSync(abs, 'utf-8');
+}
+
+async function openInBrowser(url: string): Promise<void> {
+ const cmd = platform() === 'darwin' ? 'open' : platform() === 'win32' ? 'start' : 'xdg-open';
+ const args = platform() === 'win32' ? ['', url] : [url];
+ spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();
+}
+
+// ---------- public registration ----------
+
+export function registerSkillsCommand(program: Command): void {
+ const skills = program
+ .command('skills')
+ .description('Discover, install, and manage Mercury skills from skills.mercuryagent.sh')
+ .option('--json', 'Emit machine-readable JSON (no colors, no spinners)')
+ .option('--registry <url>', 'Override registry URL (default: https://skills.mercuryagent.sh)')
+ .option('-q, --quiet', 'Suppress non-error output')
+ .option('-y, --yes', 'Skip confirmation prompts');
+
+ skills
+ .command('info')
+ .description('Print registry URL, install root, cache location, and installed count')
+ .action(cmdInfo);
+
+ skills
+ .command('list')
+ .description('Show locally installed skills')
+ .action(cmdList);
+
+ skills
+ .command('categories')
+ .description('List registry categories with skill counts')
+ .action(cmdCategories);
+
+ skills
+ .command('browse [category]')
+ .description('Browse all available skills in the registry, optionally filtered by category slug')
+ .option('--page <n>', 'Page number (default: 1)', '1')
+ .option('--limit <n>', 'Skills per page (default: 20)', '20')
+ .action(cmdBrowse);
+
+ skills
+ .command('search <query>')
+ .description('Search the registry by title, tags, description, and category')
+ .option('--limit <n>', 'Max results (default: 10)', '10')
+ .action(cmdSearch);
+
+ skills
+ .command('view <id>')
+ .description('Render a skill\'s SKILL.md to the terminal (prefers local copy if installed)')
+ .option('--web', 'Open the skill\'s page on skills.mercuryagent.sh in your default browser')
+ .option('--raw', 'Print raw SKILL.md without terminal formatting')
+ .action(cmdView);
+
+ skills
+ .command('install [ids...]')
+ .description('Install one or more skills by id (e.g. ai-ml/prompt-engineering)')
+ .option('--from <urlOrPath>', 'Install a SKILL.md from a URL or local path (advanced)')
+ .option('-f, --force', 'Re-download even if already installed at the same version')
+ .action(cmdInstall);
+
+ skills
+ .command('remove <id>')
+ .description('Delete an installed skill')
+ .action(cmdRemove);
+
+ skills
+ .command('update [id]')
+ .description('Re-fetch one or all installed skills from the registry')
+ .action(cmdUpdate);
+
+ skills
+ .command('doctor')
+ .description('Check install root, index, and registry reachability')
+ .action(cmdDoctor);
+}
diff --git a/src/skills/loader.ts b/src/skills/loader.ts
index 290309eb..f58bcb6c 100644
--- a/src/skills/loader.ts
+++ b/src/skills/loader.ts
@@ -49,13 +49,12 @@ export class SkillLoader {
this.ensureDefaultSkills();
- const entries = readdirSync(this.skillsDir, { withFileTypes: true });
- for (const entry of entries) {
- if (!entry.isDirectory() || entry.name.startsWith('_')) continue;
- const skillDir = join(this.skillsDir, entry.name);
- if (existsSync(join(skillDir, DISABLED_FILE))) continue;
- const skillPath = join(this.skillsDir, entry.name, SKILL_FILE);
- if (!existsSync(skillPath)) continue;
+ // Walk both layouts:
+ // - flat: <skillsDir>/<name>/SKILL.md (legacy + user-authored)
+ // - nested: <skillsDir>/<category>/<slug>/SKILL.md (mercury skills install)
+ // User-installed nested skills win over flat ones on name collision (registered last).
+ const skillPaths = this.findSkillFiles();
+ for (const skillPath of skillPaths) {
try {
const raw = readFileSync(skillPath, 'utf-8');
const parsed = parseSkillMd(raw);
@@ -64,11 +63,10 @@ export class SkillLoader {
name: parsed.meta.name,
description: parsed.meta.description,
});
- // Register full meta with IntentRouter for intent/tag/category matching
this.intentRouter.registerSkillMeta(parsed.meta);
- logger.info({ skill: parsed.meta.name, category: parsed.meta.category, intents: parsed.meta.intents?.length }, 'Skill discovered');
+ logger.info({ skill: parsed.meta.name, path: skillPath, category: parsed.meta.category, intents: parsed.meta.intents?.length }, 'Skill discovered');
} catch (err) {
- logger.warn({ dir: entry.name, err }, 'Failed to load skill');
+ logger.warn({ path: skillPath, err }, 'Failed to load skill');
}
}
@@ -82,34 +80,70 @@ export class SkillLoader {
const cached = this.loaded.get(name);
if (cached) return cached;
- for (const entry of readdirSync(this.skillsDir, { withFileTypes: true })) {
- if (!entry.isDirectory() || entry.name.startsWith('_')) continue;
- const skillDir = join(this.skillsDir, entry.name);
- if (existsSync(join(skillDir, DISABLED_FILE))) continue;
- const skillPath = join(this.skillsDir, entry.name, SKILL_FILE);
- if (!existsSync(skillPath)) continue;
+ const skillPaths = this.findSkillFiles();
+ let lastMatch: Skill | null = null;
+ for (const skillPath of skillPaths) {
try {
const raw = readFileSync(skillPath, 'utf-8');
const parsed = parseSkillMd(raw);
if (!parsed || parsed.meta.name !== name) continue;
+ const skillDir = join(skillPath, '..');
const skill: Skill = {
...parsed.meta,
instructions: parsed.instructions,
scriptsDir: existsSync(join(skillDir, 'scripts')) ? join(skillDir, 'scripts') : undefined,
referencesDir: existsSync(join(skillDir, 'references')) ? join(skillDir, 'references') : undefined,
};
- this.loaded.set(name, skill);
- return skill;
+ // Nested wins over flat — keep walking and prefer the deepest match.
+ lastMatch = skill;
} catch (err) {
logger.warn({ err, name }, 'Failed to load skill');
- return null;
}
}
-
+ if (lastMatch) {
+ this.loaded.set(name, lastMatch);
+ return lastMatch;
+ }
return null;
}
+ /**
+ * Walk the skills directory and return absolute paths to every SKILL.md found,
+ * supporting both flat (<dir>/SKILL.md) and nested (<category>/<slug>/SKILL.md)
+ * layouts. Skips directories starting with "_" and any tree containing a
+ * `.disabled` marker.
+ */
+ private findSkillFiles(): string[] {
+ const out: string[] = [];
+ if (!existsSync(this.skillsDir)) return out;
+
+ for (const entry of readdirSync(this.skillsDir, { withFileTypes: true })) {
+ if (!entry.isDirectory() || entry.name.startsWith('_') || entry.name.startsWith('.')) continue;
+ const dir = join(this.skillsDir, entry.name);
+ if (existsSync(join(dir, DISABLED_FILE))) continue;
+
+ const flat = join(dir, SKILL_FILE);
+ if (existsSync(flat)) {
+ out.push(flat);
+ continue;
+ }
+ // Treat as category folder: look one level deeper for <slug>/SKILL.md.
+ let children: import('node:fs').Dirent[] = [];
+ try {
+ children = readdirSync(dir, { withFileTypes: true });
+ } catch { continue; }
+ for (const child of children) {
+ if (!child.isDirectory() || child.name.startsWith('_') || child.name.startsWith('.')) continue;
+ const childDir = join(dir, child.name);
+ if (existsSync(join(childDir, DISABLED_FILE))) continue;
+ const nested = join(childDir, SKILL_FILE);
+ if (existsSync(nested)) out.push(nested);
+ }
+ }
+ return out;
+ }
+
getDiscovered(): SkillDiscovery[] {
return [...this.discovered.values()];
}
@@ -188,11 +222,9 @@ export class SkillLoader {
const list: Array<SkillDiscovery & { active: boolean }> = [];
if (!existsSync(this.skillsDir)) return list;
- for (const entry of readdirSync(this.skillsDir, { withFileTypes: true })) {
- if (!entry.isDirectory() || entry.name.startsWith('_')) continue;
- const skillDir = join(this.skillsDir, entry.name);
- const skillPath = join(skillDir, SKILL_FILE);
- if (!existsSync(skillPath)) continue;
+ // Include disabled too — walk both layouts but don't honor .disabled here.
+ const candidates = this.walkAllSkillPaths();
+ for (const { skillPath, disabled } of candidates) {
try {
const raw = readFileSync(skillPath, 'utf-8');
const parsed = parseSkillMd(raw);
@@ -200,10 +232,10 @@ export class SkillLoader {
list.push({
name: parsed.meta.name,
description: parsed.meta.description,
- active: !existsSync(join(skillDir, DISABLED_FILE)),
+ active: !disabled,
});
} catch (err) {
- logger.warn({ err, dir: entry.name }, 'Failed to read skill metadata');
+ logger.warn({ err, path: skillPath }, 'Failed to read skill metadata');
}
}
@@ -252,22 +284,46 @@ export class SkillLoader {
private findSkillEntryByName(name: string): { skillDir: string } | null {
if (!existsSync(this.skillsDir)) return null;
- for (const entry of readdirSync(this.skillsDir, { withFileTypes: true })) {
- if (!entry.isDirectory() || entry.name.startsWith('_')) continue;
- const skillDir = join(this.skillsDir, entry.name);
- const skillPath = join(skillDir, SKILL_FILE);
- if (!existsSync(skillPath)) continue;
+ const candidates = this.walkAllSkillPaths();
+ let lastMatch: string | null = null;
+ for (const { skillPath } of candidates) {
try {
const raw = readFileSync(skillPath, 'utf-8');
const parsed = parseSkillMd(raw);
if (parsed?.meta.name === name) {
- return { skillDir };
+ lastMatch = join(skillPath, '..');
}
} catch {
continue;
}
}
- return null;
+ return lastMatch ? { skillDir: lastMatch } : null;
+ }
+
+ /** Like findSkillFiles, but also returns disabled entries (used by getAllSkills). */
+ private walkAllSkillPaths(): Array<{ skillPath: string; disabled: boolean }> {
+ const out: Array<{ skillPath: string; disabled: boolean }> = [];
+ if (!existsSync(this.skillsDir)) return out;
+ for (const entry of readdirSync(this.skillsDir, { withFileTypes: true })) {
+ if (!entry.isDirectory() || entry.name.startsWith('_') || entry.name.startsWith('.')) continue;
+ const dir = join(this.skillsDir, entry.name);
+ const flat = join(dir, SKILL_FILE);
+ if (existsSync(flat)) {
+ out.push({ skillPath: flat, disabled: existsSync(join(dir, DISABLED_FILE)) });
+ continue;
+ }
+ let children: import('node:fs').Dirent[] = [];
+ try { children = readdirSync(dir, { withFileTypes: true }); } catch { continue; }
+ for (const child of children) {
+ if (!child.isDirectory() || child.name.startsWith('_') || child.name.startsWith('.')) continue;
+ const childDir = join(dir, child.name);
+ const nested = join(childDir, SKILL_FILE);
+ if (existsSync(nested)) {
+ out.push({ skillPath: nested, disabled: existsSync(join(childDir, DISABLED_FILE)) });
+ }
+ }
+ }
+ return out;
}
private seedTemplate(): void {
diff --git a/src/skills/registry.ts b/src/skills/registry.ts
new file mode 100644
index 00000000..ac31da1d
--- /dev/null
+++ b/src/skills/registry.ts
@@ -0,0 +1,313 @@
+/**
+ * Registry client for skills.mercuryagent.sh.
+ *
+ * Read-only HTTP client; no auth. All endpoints are CDN-cached JSON / markdown.
+ * Pure functions where possible — the only state is the on-disk feed cache.
+ */
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { homedir } from 'node:os';
+import { logger } from '../utils/logger.js';
+
+export const DEFAULT_REGISTRY = 'https://skills.mercuryagent.sh';
+export const DEFAULT_CACHE_TTL_SECONDS = 600;
+
+export interface RegistrySkillSummary {
+ id: string; // "<category>/<slug>"
+ title: string;
+ description: string;
+ category: string; // human label, e.g. "AI / ML"
+ categorySlug: string;
+ tags: string[];
+ version: string;
+ author?: string;
+ githubUrl?: string;
+}
+
+export interface RegistryCategory {
+ slug: string;
+ name: string;
+ count: number;
+}
+
+export interface RegistryFeed {
+ skills: RegistrySkillSummary[];
+ categories: RegistryCategory[];
+ generatedAt?: string;
+}
+
+export interface RegistrySkillDetail extends RegistrySkillSummary {
+ /** Raw markdown body (no frontmatter). The registry returns this on the detail endpoint. */
+ body?: string;
+ /** Some metadata fields are only present on the detail payload. */
+ name?: string;
+ slug?: string;
+ installCommand?: string;
+ updatedAt?: string;
+}
+
+export class RegistryError extends Error {
+ constructor(
+ message: string,
+ public readonly status?: number,
+ public readonly id?: string,
+ ) {
+ super(message);
+ this.name = 'RegistryError';
+ }
+}
+
+export interface RegistryClientOptions {
+ registry?: string;
+ cacheDir?: string;
+ cacheTtlSeconds?: number;
+ fetchImpl?: typeof fetch;
+}
+
+interface CachedFeed {
+ fetchedAt: number; // epoch ms
+ etag?: string;
+ feed: RegistryFeed;
+}
+
+const ID_RE = /^[a-z0-9-]+\/[a-z0-9-]+$/;
+
+export function isValidSkillId(id: string): boolean {
+ return ID_RE.test(id);
+}
+
+export function assertValidSkillId(id: string): void {
+ if (!isValidSkillId(id)) {
+ throw new RegistryError(
+ `Invalid skill id "${id}". Expected "<category-slug>/<skill-slug>" (lowercase, hyphens, digits).`,
+ undefined,
+ id,
+ );
+ }
+}
+
+export class RegistryClient {
+ readonly registryUrl: string;
+ readonly cacheDir: string;
+ readonly cacheTtlMs: number;
+ private readonly fetchImpl: typeof fetch;
+ private readonly feedCachePath: string;
+
+ constructor(opts: RegistryClientOptions = {}) {
+ this.registryUrl = (opts.registry || DEFAULT_REGISTRY).replace(/\/$/, '');
+ this.cacheDir = opts.cacheDir || join(homedir(), '.mercury', 'cache');
+ this.cacheTtlMs = (opts.cacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS) * 1000;
+ this.fetchImpl = opts.fetchImpl || ((globalThis.fetch as typeof fetch));
+ this.feedCachePath = join(this.cacheDir, 'registry-feed.json');
+ }
+
+ /** Fetch (or read from cache) the full registry feed. */
+ async getFeed(force = false): Promise<RegistryFeed> {
+ const cached = this.readFeedCache();
+ const now = Date.now();
+ if (!force && cached && now - cached.fetchedAt < this.cacheTtlMs) {
+ return cached.feed;
+ }
+
+ const headers: Record<string, string> = { accept: 'application/json' };
+ if (cached?.etag) headers['if-none-match'] = cached.etag;
+
+ const url = `${this.registryUrl}/api/feed.json`;
+ let res: Response;
+ try {
+ res = await this.fetchImpl(url, { headers });
+ } catch (err: any) {
+ if (cached) {
+ logger.warn({ err: err?.message, url }, 'registry feed fetch failed; using stale cache');
+ return cached.feed;
+ }
+ throw new RegistryError(`Failed to reach registry at ${url}: ${err?.message || err}`);
+ }
+
+ if (res.status === 304 && cached) {
+ // refresh fetchedAt to extend TTL
+ this.writeFeedCache({ ...cached, fetchedAt: now });
+ return cached.feed;
+ }
+ if (!res.ok) {
+ if (cached) {
+ logger.warn({ status: res.status, url }, 'registry feed non-OK; using stale cache');
+ return cached.feed;
+ }
+ throw new RegistryError(`Registry feed request failed: ${res.status} ${res.statusText}`, res.status);
+ }
+
+ const feed = (await res.json()) as RegistryFeed;
+ if (!feed || !Array.isArray(feed.skills)) {
+ throw new RegistryError('Registry returned malformed feed (no skills array).');
+ }
+ this.writeFeedCache({
+ fetchedAt: now,
+ etag: res.headers.get('etag') || undefined,
+ feed,
+ });
+ return feed;
+ }
+
+ /** Fetch metadata + body for a single skill. 404 → RegistryError with status 404. */
+ async getSkill(id: string): Promise<RegistrySkillDetail> {
+ assertValidSkillId(id);
+ const url = `${this.registryUrl}/api/skills/${id}`;
+ const res = await this.fetchImpl(url, { headers: { accept: 'application/json' } });
+ if (res.status === 404) {
+ throw new RegistryError(`Skill not found in registry: ${id}`, 404, id);
+ }
+ if (!res.ok) {
+ throw new RegistryError(`Failed to fetch skill ${id}: ${res.status} ${res.statusText}`, res.status, id);
+ }
+ const data = (await res.json()) as RegistrySkillDetail;
+ if (!data || !data.id) {
+ throw new RegistryError(`Registry returned malformed payload for ${id}.`, undefined, id);
+ }
+ return data;
+ }
+
+ /**
+ * Reconstruct a canonical SKILL.md (frontmatter + body) for a given skill.
+ *
+ * The registry's `/install` endpoint serves a tar.gz archive — useful for
+ * mass-installs but not what we want for the single-file Mercury layout.
+ * Instead we synthesize the SKILL.md from the JSON detail payload, which
+ * exposes both the metadata and the raw markdown body. This produces a file
+ * byte-identical (modulo YAML key ordering) to the source SKILL.md in the
+ * skills repo.
+ */
+ async fetchSkillMarkdown(id: string): Promise<{ body: string; etag?: string }> {
+ assertValidSkillId(id);
+ const detail = await this.getSkill(id);
+ if (typeof detail.body !== 'string' || detail.body.length === 0) {
+ throw new RegistryError(`Registry returned no markdown body for ${id}.`, undefined, id);
+ }
+ const body = buildSkillMd(detail);
+ return { body, etag: undefined };
+ }
+
+ /** Quick reachability check used by `skills doctor`. */
+ async ping(): Promise<{ ok: boolean; status?: number; error?: string }> {
+ try {
+ const res = await this.fetchImpl(`${this.registryUrl}/api/feed.json`, {
+ method: 'HEAD',
+ });
+ return { ok: res.ok, status: res.status };
+ } catch (err: any) {
+ return { ok: false, error: err?.message || String(err) };
+ }
+ }
+
+ webUrl(id: string): string {
+ return `${this.registryUrl}/skills/${id}`;
+ }
+
+ private readFeedCache(): CachedFeed | null {
+ try {
+ if (!existsSync(this.feedCachePath)) return null;
+ const raw = readFileSync(this.feedCachePath, 'utf-8');
+ const parsed = JSON.parse(raw) as CachedFeed;
+ if (!parsed?.feed?.skills) return null;
+ return parsed;
+ } catch (err) {
+ logger.warn({ err }, 'failed to read registry feed cache');
+ return null;
+ }
+ }
+
+ private writeFeedCache(value: CachedFeed): void {
+ try {
+ if (!existsSync(this.cacheDir)) mkdirSync(this.cacheDir, { recursive: true });
+ writeFileSync(this.feedCachePath, JSON.stringify(value), 'utf-8');
+ } catch (err) {
+ logger.warn({ err }, 'failed to write registry feed cache');
+ }
+ }
+}
+
+/** Score a single feed entry against a query. Higher = better. 0 = no match. */
+export function scoreSkill(skill: RegistrySkillSummary, query: string): number {
+ const q = query.trim().toLowerCase();
+ if (!q) return 0;
+ const tokens = q.split(/\s+/).filter(Boolean);
+
+ const title = (skill.title || '').toLowerCase();
+ const desc = (skill.description || '').toLowerCase();
+ const tags = (skill.tags || []).map((t) => t.toLowerCase());
+ const category = (skill.category || '').toLowerCase();
+ const id = (skill.id || '').toLowerCase();
+
+ let score = 0;
+ // Whole-query substring boosts
+ if (title.includes(q)) score += 3;
+ if (id.includes(q)) score += 2.5;
+ if (tags.some((t) => t.includes(q))) score += 2;
+ if (desc.includes(q)) score += 1;
+ if (category.includes(q)) score += 0.5;
+
+ // Per-token matches (helps multi-word queries)
+ for (const tok of tokens) {
+ if (title.includes(tok)) score += 1.5;
+ if (tags.some((t) => t.includes(tok))) score += 1;
+ if (desc.includes(tok)) score += 0.5;
+ if (category.includes(tok)) score += 0.25;
+ }
+ return score;
+}
+
+export interface ScoredSkill {
+ skill: RegistrySkillSummary;
+ score: number;
+}
+
+export function searchFeed(feed: RegistryFeed, query: string, limit = 10): ScoredSkill[] {
+ return feed.skills
+ .map((skill) => ({ skill, score: scoreSkill(skill, query) }))
+ .filter((s) => s.score > 0)
+ .sort((a, b) => b.score - a.score || a.skill.id.localeCompare(b.skill.id))
+ .slice(0, Math.max(1, limit));
+}
+
+/**
+ * Render a canonical SKILL.md (YAML frontmatter + markdown body) from a
+ * registry detail payload. Output always starts with `---\n` so it passes the
+ * sentinel check enforced by SkillStore.
+ */
+export function buildSkillMd(detail: RegistrySkillDetail): string {
+ const frontmatter: Record<string, unknown> = {};
+ const name = detail.name || detail.slug || detail.id.split('/').pop();
+ if (name) frontmatter.name = name;
+ if (detail.title) frontmatter.title = detail.title;
+ if (detail.description) frontmatter.description = detail.description;
+ if (detail.categorySlug) frontmatter.category = detail.categorySlug;
+ if (detail.version) frontmatter.version = detail.version;
+ if (detail.author) frontmatter.author = detail.author;
+ if (detail.tags && detail.tags.length > 0) frontmatter.tags = detail.tags;
+ frontmatter.id = detail.id;
+
+ const lines: string[] = ['---'];
+ for (const [k, v] of Object.entries(frontmatter)) {
+ if (Array.isArray(v)) {
+ lines.push(`${k}:`);
+ for (const item of v) lines.push(` - ${yamlScalar(item)}`);
+ } else {
+ lines.push(`${k}: ${yamlScalar(v)}`);
+ }
+ }
+ lines.push('---');
+ lines.push('');
+ const body = detail.body!.replace(/\r\n/g, '\n');
+ lines.push(body.endsWith('\n') ? body.slice(0, -1) : body);
+ return lines.join('\n') + '\n';
+}
+
+function yamlScalar(v: unknown): string {
+ if (v == null) return '';
+ const s = String(v);
+ // Quote if it contains characters that would be ambiguous in YAML flow scalars.
+ if (/[:#\n\r"'\\]|^[\s-]|[\s]$/.test(s)) {
+ return JSON.stringify(s);
+ }
+ return s;
+}
diff --git a/src/skills/store.test.ts b/src/skills/store.test.ts
new file mode 100644
index 00000000..f124b9ed
--- /dev/null
+++ b/src/skills/store.test.ts
@@ -0,0 +1,219 @@
+import { describe, expect, it, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { SkillStore, INDEX_FILENAME } from './store.js';
+import { RegistryClient } from './registry.js';
+
+function makeFakeRegistry(opts: {
+ bodyById?: Record<string, string>;
+ detailById?: Record<string, any>;
+ notFound?: string[];
+} = {}): RegistryClient {
+ const defaultBody = '# Prompt Engineering\n\nBody content.\n';
+ const fakeFetch: typeof fetch = async (input: any) => {
+ const url = typeof input === 'string' ? input : input.url;
+ // Detail endpoint — we no longer hit /install at all (the live registry
+ // serves a tar.gz there). The detail JSON carries the raw markdown body
+ // and all frontmatter fields we need.
+ if (url.includes('/api/skills/') && !url.endsWith('/install')) {
+ const id = url.replace(/.*\/api\/skills\/([^/]+\/[^/]+)$/, '$1');
+ if (opts.notFound?.includes(id)) return new Response('', { status: 404 });
+ const body = opts.bodyById?.[id] ?? defaultBody;
+ const detail = opts.detailById?.[id] ?? {
+ id,
+ name: id.split('/')[1],
+ title: 'Prompt Engineering',
+ description: 'Patterns...',
+ category: 'AI / ML',
+ categorySlug: 'ai-ml',
+ tags: ['llm'],
+ version: '1.0.0',
+ body,
+ };
+ return new Response(JSON.stringify(detail), { status: 200, headers: { 'content-type': 'application/json' } });
+ }
+ return new Response('', { status: 404 });
+ };
+ return new RegistryClient({ registry: 'https://example.test', fetchImpl: fakeFetch, cacheDir: mkdtempSync(join(tmpdir(), 'mercury-cache-')) });
+}
+
+describe('SkillStore — path traversal guard', () => {
+ let dir: string;
+ let store: SkillStore;
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'mercury-skills-'));
+ store = new SkillStore({ installRoot: dir });
+ });
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
+
+ it('rejects ids without exactly one slash', () => {
+ expect(() => store.pathFor('foo')).toThrow();
+ expect(() => store.pathFor('foo/bar/baz')).toThrow();
+ });
+
+ it('rejects ids with traversal characters', () => {
+ expect(() => store.pathFor('../etc/passwd')).toThrow();
+ expect(() => store.pathFor('foo/..')).toThrow();
+ expect(() => store.pathFor('FOO/BAR')).toThrow(); // uppercase
+ expect(() => store.pathFor('foo bar/baz')).toThrow();
+ expect(() => store.pathFor('foo/bar.md')).toThrow();
+ });
+
+ it('accepts well-formed ids and pins them under installRoot', () => {
+ const p = store.pathFor('ai-ml/prompt-engineering');
+ expect(p.startsWith(dir)).toBe(true);
+ expect(p.endsWith('SKILL.md')).toBe(true);
+ });
+});
+
+describe('SkillStore — install lifecycle', () => {
+ let dir: string;
+ let store: SkillStore;
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'mercury-skills-'));
+ store = new SkillStore({ installRoot: dir });
+ });
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
+
+ it('installs a skill atomically and updates the index', async () => {
+ const reg = makeFakeRegistry();
+ const r = await store.install('ai-ml/prompt-engineering', { registry: reg });
+ expect(r.status).toBe('installed');
+ expect(existsSync(r.path)).toBe(true);
+ // The store reconstructs SKILL.md from the registry detail payload.
+ const written = readFileSync(r.path, 'utf-8');
+ expect(written.startsWith('---\n')).toBe(true);
+ expect(written).toMatch(/name: prompt-engineering/);
+ expect(written).toMatch(/# Prompt Engineering/);
+ const idx = JSON.parse(readFileSync(join(dir, INDEX_FILENAME), 'utf-8'));
+ expect(idx.skills['ai-ml/prompt-engineering'].version).toBe('1.0.0');
+ });
+
+ it('is a no-op when same version already installed', async () => {
+ const reg = makeFakeRegistry();
+ await store.install('ai-ml/prompt-engineering', { registry: reg });
+ const r2 = await store.install('ai-ml/prompt-engineering', { registry: reg });
+ expect(r2.status).toBe('already-installed');
+ });
+
+ it('re-downloads with force=true', async () => {
+ const reg = makeFakeRegistry();
+ await store.install('ai-ml/prompt-engineering', { registry: reg });
+ const r2 = await store.install('ai-ml/prompt-engineering', { registry: reg, force: true });
+ expect(r2.status).toBe('reinstalled');
+ });
+
+ it('rejects when the registry returns no markdown body', async () => {
+ const fakeFetch: typeof fetch = async (input: any) => {
+ const url = typeof input === 'string' ? input : input.url;
+ if (url.endsWith('/api/skills/ai-ml/prompt-engineering')) {
+ return new Response(JSON.stringify({
+ id: 'ai-ml/prompt-engineering',
+ name: 'prompt-engineering',
+ version: '1.0.0',
+ // body intentionally omitted
+ }), { status: 200, headers: { 'content-type': 'application/json' } });
+ }
+ return new Response('', { status: 404 });
+ };
+ const reg = new RegistryClient({ registry: 'https://example.test', fetchImpl: fakeFetch, cacheDir: mkdtempSync(join(tmpdir(), 'mercury-cache-')) });
+ await expect(store.install('ai-ml/prompt-engineering', { registry: reg })).rejects.toThrow(/no markdown body/i);
+ expect(store.isInstalled('ai-ml/prompt-engineering')).toBe(false);
+ });
+
+ it('returns a clear error for registry 404', async () => {
+ const reg = makeFakeRegistry({ notFound: ['ai-ml/does-not-exist'] });
+ await expect(store.install('ai-ml/does-not-exist', { registry: reg })).rejects.toThrow(/not found/i);
+ });
+
+ it('removes a skill and prunes the index', async () => {
+ const reg = makeFakeRegistry();
+ const r = await store.install('ai-ml/prompt-engineering', { registry: reg });
+ expect(existsSync(r.path)).toBe(true);
+ expect(store.remove('ai-ml/prompt-engineering')).toBe(true);
+ expect(existsSync(r.path)).toBe(false);
+ expect(store.isInstalled('ai-ml/prompt-engineering')).toBe(false);
+ });
+
+ it('remove() returns false for skills not in the index', () => {
+ expect(store.remove('ai-ml/nope')).toBe(false);
+ });
+
+ it('list() reads from the index', async () => {
+ const reg = makeFakeRegistry();
+ await store.install('ai-ml/prompt-engineering', { registry: reg });
+ const items = store.list();
+ expect(items.length).toBe(1);
+ expect(items[0].id).toBe('ai-ml/prompt-engineering');
+ expect(items[0].version).toBe('1.0.0');
+ });
+
+ it('installFromBody supports advanced --from installs', () => {
+ const body = `---
+name: prompt-engineering
+id: ai-ml/prompt-engineering
+title: Prompt Engineering
+description: Patterns for designing reliable LLM prompts.
+version: 1.0.0
+---
+
+# Prompt Engineering
+
+Body content.
+`;
+ const r = store.installFromBody(body, { source: 'file:/tmp/SKILL.md' });
+ expect(r.id).toBe('ai-ml/prompt-engineering');
+ expect(existsSync(r.path)).toBe(true);
+ });
+
+ it('health() reports orphans when files are missing under the index', async () => {
+ const reg = makeFakeRegistry();
+ const r = await store.install('ai-ml/prompt-engineering', { registry: reg });
+ rmSync(r.path);
+ const h = store.health();
+ expect(h.orphaned).toContain('ai-ml/prompt-engineering');
+ });
+});
+
+describe('SkillStore — index rollback', () => {
+ it('does not write index when frontmatter verification fails', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'mercury-skills-'));
+ try {
+ const store = new SkillStore({ installRoot: dir });
+ const fakeFetch: typeof fetch = async () => new Response(JSON.stringify({
+ id: 'ai-ml/prompt-engineering',
+ // name and body both missing → buildSkillMd will still try, body check will fail first
+ }), { status: 200, headers: { 'content-type': 'application/json' } });
+ const reg = new RegistryClient({ registry: 'https://example.test', fetchImpl: fakeFetch, cacheDir: mkdtempSync(join(tmpdir(), 'mercury-cache-')) });
+ await expect(store.install('ai-ml/prompt-engineering', { registry: reg })).rejects.toThrow();
+ expect(existsSync(join(dir, INDEX_FILENAME))).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('RegistryClient — feed caching', () => {
+ it('caches and reuses the feed within TTL', async () => {
+ let calls = 0;
+ const cacheDir = mkdtempSync(join(tmpdir(), 'mercury-cache-'));
+ const fakeFetch: typeof fetch = async () => {
+ calls++;
+ return new Response(JSON.stringify({ skills: [], categories: [] }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ };
+ const reg = new RegistryClient({
+ registry: 'https://example.test',
+ fetchImpl: fakeFetch,
+ cacheDir,
+ cacheTtlSeconds: 600,
+ });
+ await reg.getFeed();
+ await reg.getFeed();
+ expect(calls).toBe(1);
+ rmSync(cacheDir, { recursive: true, force: true });
+ });
+});
diff --git a/src/skills/store.ts b/src/skills/store.ts
new file mode 100644
index 00000000..2b2ddd1f
--- /dev/null
+++ b/src/skills/store.ts
@@ -0,0 +1,399 @@
+/**
+ * Local skill store. Owns the on-disk layout under <install-root>/<category>/<slug>/SKILL.md
+ * and the JSON index that tracks installed versions.
+ *
+ * Contract:
+ * - All writes are atomic (tmp file + rename).
+ * - All paths are constrained under install-root; ids are validated against the
+ * "<category-slug>/<skill-slug>" regex; we NEVER trust a remote-supplied path.
+ * - The index file (.index.json) is the source of truth for `list` and `update`.
+ */
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+ unlinkSync,
+} from 'node:fs';
+import { dirname, join, relative, resolve, sep } from 'node:path';
+import { homedir } from 'node:os';
+import { parse as parseYaml } from 'yaml';
+import { logger } from '../utils/logger.js';
+import {
+ RegistryClient,
+ RegistryError,
+ assertValidSkillId,
+ isValidSkillId,
+ type RegistrySkillDetail,
+} from './registry.js';
+
+export const SKILL_FILENAME = 'SKILL.md';
+export const INDEX_FILENAME = '.index.json';
+export const INDEX_VERSION = 1;
+
+export interface InstalledSkillEntry {
+ version: string;
+ installedAt: string; // ISO-8601
+ source: string; // registry URL or "file:..." / "url:..."
+ etag?: string;
+ title?: string;
+ description?: string;
+ category?: string;
+}
+
+export interface SkillsIndex {
+ version: number;
+ skills: Record<string, InstalledSkillEntry>;
+}
+
+export interface InstallResult {
+ id: string;
+ version: string;
+ path: string;
+ status: 'installed' | 'updated' | 'already-installed' | 'reinstalled';
+ previousVersion?: string;
+}
+
+export interface SkillStoreOptions {
+ installRoot?: string;
+ registry?: RegistryClient;
+}
+
+function emptyIndex(): SkillsIndex {
+ return { version: INDEX_VERSION, skills: {} };
+}
+
+export class SkillStore {
+ readonly installRoot: string;
+ private readonly indexPath: string;
+ private readonly registry: RegistryClient | undefined;
+
+ constructor(opts: SkillStoreOptions = {}) {
+ this.installRoot = opts.installRoot || join(homedir(), '.mercury', 'skills');
+ this.indexPath = join(this.installRoot, INDEX_FILENAME);
+ this.registry = opts.registry;
+ }
+
+ // ---------- Index ----------
+
+ readIndex(): SkillsIndex {
+ if (!existsSync(this.indexPath)) return emptyIndex();
+ try {
+ const raw = readFileSync(this.indexPath, 'utf-8');
+ const parsed = JSON.parse(raw) as SkillsIndex;
+ if (!parsed || typeof parsed !== 'object' || !parsed.skills) return emptyIndex();
+ if (parsed.version !== INDEX_VERSION) {
+ logger.warn({ have: parsed.version, want: INDEX_VERSION }, 'skills index version mismatch; treating as empty');
+ return emptyIndex();
+ }
+ return parsed;
+ } catch (err) {
+ logger.warn({ err }, 'failed to parse skills index; starting fresh');
+ return emptyIndex();
+ }
+ }
+
+ private writeIndex(index: SkillsIndex): void {
+ this.ensureRoot();
+ atomicWriteFile(this.indexPath, JSON.stringify(index, null, 2));
+ }
+
+ list(): Array<{ id: string } & InstalledSkillEntry> {
+ const index = this.readIndex();
+ return Object.entries(index.skills)
+ .map(([id, entry]) => ({ id, ...entry }))
+ .sort((a, b) => a.id.localeCompare(b.id));
+ }
+
+ isInstalled(id: string): boolean {
+ return !!this.readIndex().skills[id];
+ }
+
+ // ---------- Paths (with traversal guard) ----------
+
+ pathFor(id: string): string {
+ assertValidSkillId(id);
+ const full = resolve(this.installRoot, id, SKILL_FILENAME);
+ const root = resolve(this.installRoot);
+ const rel = relative(root, full);
+ if (rel.startsWith('..') || rel.includes(`..${sep}`)) {
+ throw new RegistryError(`Refusing to write outside install root: ${id}`, undefined, id);
+ }
+ return full;
+ }
+
+ // ---------- Install / Remove ----------
+
+ /**
+ * Install a single skill from the registry.
+ *
+ * - force=false + same version: returns { status: "already-installed" }
+ * - force=true: always re-download
+ */
+ async install(
+ id: string,
+ opts: { force?: boolean; registry?: RegistryClient } = {},
+ ): Promise<InstallResult> {
+ assertValidSkillId(id);
+ const registry = opts.registry || this.registry;
+ if (!registry) throw new Error('SkillStore.install requires a RegistryClient');
+
+ const detail = await registry.getSkill(id);
+ const desired = detail.version || '0.0.0';
+ const index = this.readIndex();
+ const existing = index.skills[id];
+
+ if (existing && existing.version === desired && !opts.force) {
+ return {
+ id,
+ version: desired,
+ path: this.pathFor(id),
+ status: 'already-installed',
+ previousVersion: existing.version,
+ };
+ }
+
+ const { body, etag } = await registry.fetchSkillMarkdown(id);
+ // Verify frontmatter parses and contains required fields
+ this.verifyBody(body, id);
+
+ const target = this.pathFor(id);
+ const previousBody = existing && existsSync(target) ? readFileSync(target, 'utf-8') : null;
+
+ mkdirSync(dirname(target), { recursive: true });
+ atomicWriteFile(target, body);
+
+ // Verification read — defend against disk-full / TOCTOU
+ const verify = readFileSync(target, 'utf-8');
+ if (verify !== body) {
+ // Roll back
+ if (previousBody != null) {
+ atomicWriteFile(target, previousBody);
+ } else {
+ try { unlinkSync(target); } catch { /* ignore */ }
+ }
+ throw new Error(`Post-install verification failed for ${id} (disk write mismatch)`);
+ }
+
+ const entry: InstalledSkillEntry = {
+ version: desired,
+ installedAt: new Date().toISOString(),
+ source: registry.registryUrl,
+ etag,
+ title: detail.title,
+ description: detail.description,
+ category: detail.category,
+ };
+
+ try {
+ index.skills[id] = entry;
+ this.writeIndex(index);
+ } catch (err) {
+ // Roll back the file write — index is the source of truth, we must keep them consistent
+ if (previousBody != null) {
+ try { atomicWriteFile(target, previousBody); } catch { /* ignore */ }
+ } else {
+ try { unlinkSync(target); } catch { /* ignore */ }
+ }
+ throw err;
+ }
+
+ return {
+ id,
+ version: desired,
+ path: target,
+ status: existing ? (opts.force ? 'reinstalled' : 'updated') : 'installed',
+ previousVersion: existing?.version,
+ };
+ }
+
+ /** Install from a raw SKILL.md body fetched out-of-band (e.g. --from). */
+ installFromBody(
+ body: string,
+ opts: { id?: string; source: string },
+ ): InstallResult {
+ this.verifyBody(body, opts.id || '<from>');
+ const meta = parseFrontmatter(body);
+ const id = opts.id || meta.id;
+ if (!id) {
+ throw new RegistryError(
+ 'Cannot determine skill id from SKILL.md frontmatter. Add `id: <category>/<slug>` or pass an explicit id.',
+ );
+ }
+ assertValidSkillId(id);
+ const target = this.pathFor(id);
+ const index = this.readIndex();
+ const existing = index.skills[id];
+ const previousBody = existing && existsSync(target) ? readFileSync(target, 'utf-8') : null;
+
+ mkdirSync(dirname(target), { recursive: true });
+ atomicWriteFile(target, body);
+ const verify = readFileSync(target, 'utf-8');
+ if (verify !== body) {
+ if (previousBody != null) atomicWriteFile(target, previousBody);
+ throw new Error(`Post-install verification failed for ${id}`);
+ }
+
+ const entry: InstalledSkillEntry = {
+ version: meta.version || '0.0.0',
+ installedAt: new Date().toISOString(),
+ source: opts.source,
+ title: meta.title,
+ description: meta.description,
+ category: meta.category,
+ };
+ try {
+ index.skills[id] = entry;
+ this.writeIndex(index);
+ } catch (err) {
+ if (previousBody != null) atomicWriteFile(target, previousBody);
+ else try { unlinkSync(target); } catch { /* ignore */ }
+ throw err;
+ }
+
+ return {
+ id,
+ version: entry.version,
+ path: target,
+ status: existing ? 'reinstalled' : 'installed',
+ previousVersion: existing?.version,
+ };
+ }
+
+ remove(id: string): boolean {
+ assertValidSkillId(id);
+ const index = this.readIndex();
+ const had = !!index.skills[id];
+ const skillFile = this.pathFor(id);
+ const skillDir = dirname(skillFile);
+ const root = resolve(this.installRoot);
+
+ // Remove the file and the skill dir (only if non-empty paths are clearly under root)
+ if (existsSync(skillFile)) {
+ try { unlinkSync(skillFile); } catch (err) { logger.warn({ err, id }, 'remove: unlink failed'); }
+ }
+ // Try removing the skill dir, then the (possibly empty) category dir.
+ if (existsSync(skillDir) && resolve(skillDir).startsWith(root + sep)) {
+ try { rmSync(skillDir, { recursive: true, force: true }); } catch { /* ignore */ }
+ const categoryDir = dirname(skillDir);
+ if (categoryDir !== root && existsSync(categoryDir) && resolve(categoryDir).startsWith(root + sep)) {
+ try {
+ if (readdirSync(categoryDir).length === 0) rmSync(categoryDir, { recursive: false });
+ } catch { /* ignore */ }
+ }
+ }
+
+ if (had) {
+ delete index.skills[id];
+ this.writeIndex(index);
+ }
+ return had;
+ }
+
+ // ---------- Helpers ----------
+
+ ensureRoot(): void {
+ if (!existsSync(this.installRoot)) mkdirSync(this.installRoot, { recursive: true });
+ }
+
+ private verifyBody(body: string, id: string): void {
+ if (!body.startsWith('---\n') && !body.startsWith('---\r\n')) {
+ throw new RegistryError(
+ `Refusing to install ${id}: SKILL.md is missing YAML frontmatter.`,
+ undefined,
+ id,
+ );
+ }
+ const meta = parseFrontmatter(body);
+ if (!meta.name && !meta.title) {
+ throw new RegistryError(
+ `Refusing to install ${id}: SKILL.md frontmatter missing "name" / "title".`,
+ undefined,
+ id,
+ );
+ }
+ }
+
+ /** Health check: returns details for `skills doctor`. */
+ health(): {
+ installRoot: string;
+ rootExists: boolean;
+ indexExists: boolean;
+ indexValid: boolean;
+ installed: number;
+ orphaned: string[];
+ } {
+ const rootExists = existsSync(this.installRoot);
+ const indexExists = existsSync(this.indexPath);
+ let indexValid = true;
+ let index: SkillsIndex = emptyIndex();
+ try {
+ if (indexExists) index = this.readIndex();
+ } catch {
+ indexValid = false;
+ }
+ const orphaned: string[] = [];
+ for (const id of Object.keys(index.skills)) {
+ try {
+ if (!existsSync(this.pathFor(id))) orphaned.push(id);
+ } catch {
+ orphaned.push(id);
+ }
+ }
+ return {
+ installRoot: this.installRoot,
+ rootExists,
+ indexExists,
+ indexValid,
+ installed: Object.keys(index.skills).length,
+ orphaned,
+ };
+ }
+}
+
+// ---------- Module-level helpers ----------
+
+interface ParsedFrontmatter {
+ id?: string;
+ name?: string;
+ title?: string;
+ description?: string;
+ version?: string;
+ category?: string;
+}
+
+function parseFrontmatter(body: string): ParsedFrontmatter {
+ const m = body.match(/^---\s*\n([\s\S]*?)\n---\s*\n?/);
+ if (!m) return {};
+ try {
+ const obj = parseYaml(m[1]) as Record<string, unknown>;
+ if (!obj || typeof obj !== 'object') return {};
+ return {
+ id: typeof obj.id === 'string' ? obj.id : undefined,
+ name: typeof obj.name === 'string' ? obj.name : undefined,
+ title: typeof obj.title === 'string' ? obj.title : undefined,
+ description: typeof obj.description === 'string' ? obj.description : undefined,
+ version: typeof obj.version === 'string' ? obj.version : undefined,
+ category: typeof obj.category === 'string' ? obj.category : undefined,
+ };
+ } catch {
+ return {};
+ }
+}
+
+function atomicWriteFile(target: string, content: string): void {
+ mkdirSync(dirname(target), { recursive: true });
+ const tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
+ writeFileSync(tmp, content, 'utf-8');
+ try {
+ renameSync(tmp, target);
+ } catch (err) {
+ try { unlinkSync(tmp); } catch { /* ignore */ }
+ throw err;
+ }
+}
+
+export { isValidSkillId, assertValidSkillId, parseFrontmatter };
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 99f1468c..dc795d9e 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -138,6 +138,11 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli
'/reset',
'/tools',
'/skills',
+ '/skills search ',
+ '/skills view ',
+ '/skills install ',
+ '/skills remove ',
+ '/skills help',
'/stream',
'/view',
'/view balanced',
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index 9c0e1038..233f3af4 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -120,6 +120,10 @@ export function getManual(): string {
['/telegram reset', 'CLI chat only: reset all Telegram access'],
['/tools', 'List currently loaded tools'],
['/skills', 'List installed skills'],
+ ['/skills search <query>', 'Search skills.mercuryagent.sh'],
+ ['/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'],
['/permissions', 'Change permission mode (Ask Me / Allow All)'],
['/view', 'Toggle progress view (balanced/detailed)'],
['/view balanced', 'Set compact progress view'],
diff --git a/src/web/api/system.ts b/src/web/api/system.ts
index 0a2e1742..c8f8fc79 100644
--- a/src/web/api/system.ts
+++ b/src/web/api/system.ts
@@ -2,6 +2,8 @@ import { Hono } from 'hono';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { SkillLoader } from '../../skills/loader.js';
+import { RegistryClient, isValidSkillId } from '../../skills/registry.js';
+import { SkillStore } from '../../skills/store.js';
import { PermissionManager, type PermissionsManifest } from '../../capabilities/permissions.js';
import { getMercuryHome } from '../../utils/config.js';
import type { Scheduler } from '../../core/scheduler.js';
@@ -54,6 +56,36 @@ system.post('/api/skills/install', async (c) => {
}
});
+system.post('/api/skills/install-from-registry', async (c) => {
+ const body = await c.req.json().catch(() => ({}));
+ const id = String(body?.id || '').trim();
+ if (!id) return c.json({ success: false, error: 'id is required' }, 400);
+
+ if (!isValidSkillId(id)) {
+ return c.json(
+ { success: false, error: 'Invalid skill id (expected "<category>/<slug>")' },
+ 400,
+ );
+ }
+
+ try {
+ const registry = new RegistryClient();
+ const store = new SkillStore({ registry });
+ const result = await store.install(id, { force: Boolean(body?.force) });
+ return c.json({
+ success: true,
+ id: result.id,
+ version: result.version,
+ status: result.status,
+ path: result.path,
+ webUrl: registry.webUrl(id),
+ });
+ } catch (err: any) {
+ const status = err?.status === 404 ? 404 : 400;
+ return c.json({ success: false, error: err?.message || 'Failed to install skill' }, status);
+ }
+});
+
system.post('/api/skills/:name/activate', (c) => {
const name = decodeURIComponent(c.req.param('name'));
const loader = new SkillLoader();
diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts
index f82f4cc8..0f54746f 100644
--- a/ui/src/lib/api.ts
+++ b/ui/src/lib/api.ts
@@ -243,6 +243,15 @@ export const skills = {
list: () => get<{ skills: Skill[]; total: number }>("/api/skills"),
install: (url: string) =>
post<{ success: boolean; name: string }>("/api/skills/install", { url }),
+ installFromRegistry: (id: string, force = false) =>
+ post<{
+ success: boolean;
+ id: string;
+ version: string;
+ status: "installed" | "updated" | "reinstalled" | "already-installed";
+ path: string;
+ webUrl: string;
+ }>("/api/skills/install-from-registry", { id, force }),
activate: (name: string) =>
post<{ success: boolean }>(`/api/skills/${name}/activate`),
deactivate: (name: string) =>
diff --git a/ui/src/pages/Skills.tsx b/ui/src/pages/Skills.tsx
index 3270958d..8a23910f 100644
--- a/ui/src/pages/Skills.tsx
+++ b/ui/src/pages/Skills.tsx
@@ -11,6 +11,8 @@ import {
FolderOpen,
CheckCircle2,
XCircle,
+ ExternalLink,
+ Store,
} from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
@@ -118,6 +120,8 @@ export function SkillsPage() {
const [loading, setLoading] = useState(true);
const [installUrl, setInstallUrl] = useState("");
const [installing, setInstalling] = useState(false);
+ const [registryId, setRegistryId] = useState("");
+ const [installingRegistry, setInstallingRegistry] = useState(false);
const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({});
const [toasts, setToasts] = useState<Toast[]>([]);
@@ -159,6 +163,30 @@ export function SkillsPage() {
}
};
+ const handleRegistryInstall = async () => {
+ const id = registryId.trim();
+ if (!id) return;
+ setInstallingRegistry(true);
+ try {
+ const res = await api.skills.installFromRegistry(id);
+ const verb =
+ res.status === "already-installed"
+ ? "Already installed"
+ : res.status === "updated"
+ ? "Updated"
+ : res.status === "reinstalled"
+ ? "Reinstalled"
+ : "Installed";
+ toast("success", `${verb} "${res.id}" (v${res.version})`);
+ setRegistryId("");
+ await fetchSkills();
+ } catch (err: unknown) {
+ toast("error", err instanceof Error ? err.message : "Registry install failed");
+ } finally {
+ setInstallingRegistry(false);
+ }
+ };
+
const handleToggle = async (skill: Skill) => {
setActionLoading((prev) => ({ ...prev, [skill.name]: true }));
try {
@@ -218,38 +246,100 @@ export function SkillsPage() {
transition={{ delay: 0.1, duration: 0.3 }}
>
<Card>
- <CardContent className="p-5">
- <div className="flex items-center gap-2 mb-3">
- <Download className="h-4 w-4 text-muted-foreground" />
- <span className="text-sm font-medium text-foreground">
- Install a Skill
- </span>
+ <CardContent className="p-5 space-y-5">
+ {/* Registry install */}
+ <div>
+ <div className="flex items-center justify-between gap-3 mb-3">
+ <div className="flex items-center gap-2">
+ <Store className="h-4 w-4 text-muted-foreground" />
+ <span className="text-sm font-medium text-foreground">
+ Install from registry
+ </span>
+ </div>
+ <a
+ href="https://skills.mercuryagent.sh"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-[#00d4ff] transition-colors"
+ >
+ Browse skills.mercuryagent.sh
+ <ExternalLink className="h-3 w-3" />
+ </a>
+ </div>
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ handleRegistryInstall();
+ }}
+ className="flex gap-3"
+ >
+ <Input
+ placeholder="category/skill-slug e.g. finance-legal/contract-review"
+ value={registryId}
+ onChange={(e) => setRegistryId(e.target.value)}
+ disabled={installingRegistry}
+ className="flex-1 font-mono text-sm"
+ />
+ <Button
+ type="submit"
+ disabled={installingRegistry || !registryId.trim()}
+ >
+ {installingRegistry ? (
+ <>
+ <Loader2 className="h-4 w-4 animate-spin" />
+ Installing
+ </>
+ ) : (
+ "Install"
+ )}
+ </Button>
+ </form>
+ <p className="mt-2 text-xs text-muted-foreground">
+ Review any skill on the registry before installing — they execute
+ with your agent&apos;s privileges.
+ </p>
+ </div>
+
+ <div className="h-px bg-border" />
+
+ {/* URL install */}
+ <div>
+ <div className="flex items-center gap-2 mb-3">
+ <Download className="h-4 w-4 text-muted-foreground" />
+ <span className="text-sm font-medium text-foreground">
+ Install from URL
+ </span>
+ </div>
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ handleInstall();
+ }}
+ className="flex gap-3"
+ >
+ <Input
+ placeholder="https://github.com/user/skill-package"
+ value={installUrl}
+ onChange={(e) => setInstallUrl(e.target.value)}
+ disabled={installing}
+ className="flex-1"
+ />
+ <Button
+ type="submit"
+ variant="outline"
+ disabled={installing || !installUrl.trim()}
+ >
+ {installing ? (
+ <>
+ <Loader2 className="h-4 w-4 animate-spin" />
+ Installing
+ </>
+ ) : (
+ "Install"
+ )}
+ </Button>
+ </form>
</div>
- <form
- onSubmit={(e) => {
- e.preventDefault();
- handleInstall();
- }}
- className="flex gap-3"
- >
- <Input
- placeholder="https://github.com/user/skill-package"
- value={installUrl}
- onChange={(e) => setInstallUrl(e.target.value)}
- disabled={installing}
- className="flex-1"
- />
- <Button type="submit" disabled={installing || !installUrl.trim()}>
- {installing ? (
- <>
- <Loader2 className="h-4 w-4 animate-spin" />
- Installing
- </>
- ) : (
- "Install"
- )}
- </Button>
- </form>
</CardContent>
</Card>
</motion.div>
diff --git a/website/docs/cli-commands/commands.mdx b/website/docs/cli-commands/commands.mdx
index a7d33f3e..37d71e79 100644
--- a/website/docs/cli-commands/commands.mdx
+++ b/website/docs/cli-commands/commands.mdx
@@ -21,3 +21,23 @@ title: Full Command Reference
| `mercury service uninstall` | Uninstall the system service |
| `mercury service status` | Show system service status |
| `mercury --verbose` | Start with debug logging on stderr |
+
+## Skills registry
+
+The `mercury skills` command tree talks to [skills.mercuryagent.sh](https://skills.mercuryagent.sh) directly. See the dedicated [Skills page](./skills) for the full surface, examples, and the in-chat / dashboard / Telegram equivalents.
+
+| Command | Description |
+|---------|-------------|
+| `mercury skills info` | Registry stats and reachability |
+| `mercury skills list` | Show locally installed skills (from `~/.mercury/skills/.index.json`) |
+| `mercury skills categories` | List all registry categories |
+| `mercury skills browse [category] [--page N --limit N]` | Paginated catalog browse |
+| `mercury skills search <query> [--limit N]` | Full-text search |
+| `mercury skills view <id> [--web] [--raw]` | Render `SKILL.md`; `--web` opens the registry page |
+| `mercury skills install <ids...> [--force]` | Install one or many; `--force` reinstalls same version |
+| `mercury skills install --from <urlOrPath>` | Install from a local file or arbitrary URL |
+| `mercury skills update [id]` | Update all installed skills, or just one |
+| `mercury skills remove <id>` | Uninstall a skill |
+| `mercury skills doctor` | Check install root, registry connectivity, cache |
+
+Shared flags: `--json`, `--registry <url>`, `-q`, `-y`. Environment overrides: `MERCURY_SKILLS_REGISTRY`, `MERCURY_SKILLS_INSTALL_ROOT`.
diff --git a/website/docs/cli-commands/in-chat-commands.mdx b/website/docs/cli-commands/in-chat-commands.mdx
index 126920ed..4cb9300b 100644
--- a/website/docs/cli-commands/in-chat-commands.mdx
+++ b/website/docs/cli-commands/in-chat-commands.mdx
@@ -17,7 +17,12 @@ Type these during a conversation with Mercury. Most work in both CLI and Telegra
| `/models` | List configured models/providers for this session |
| `/models use <provider>` | Switch the current session model/provider |
| `/tools` | List all currently loaded tools |
-| `/skills` | List installed skills |
+| `/skills` | List installed skills · see [dedicated page](./skills) for the full surface |
+| `/skills search <query>` | Search the registry at [skills.mercuryagent.sh](https://skills.mercuryagent.sh) |
+| `/skills view <id>` | Show title, version, description, and registry URL for `<category>/<slug>` |
+| `/skills install <id>` | Install a skill from the registry into `~/.mercury/skills/` |
+| `/skills install <url>` | Install raw `SKILL.md` from a URL |
+| `/skills remove <id>` | Uninstall a skill |
| `/memory` | View and manage second brain memory |
| `/tasks` | List scheduled tasks |
| `/stream` | Toggle Telegram text streaming (on/off) |
diff --git a/website/docs/cli-commands/skills.mdx b/website/docs/cli-commands/skills.mdx
new file mode 100644
index 00000000..fbc2a3bd
--- /dev/null
+++ b/website/docs/cli-commands/skills.mdx
@@ -0,0 +1,237 @@
+---
+id: skills
+title: Skills (CLI, in-chat, dashboard, Telegram)
+sidebar_label: Skills
+---
+
+Mercury skills are Markdown-based extensions (`SKILL.md` files) that teach the
+agent how to do a specific task. The registry at
+[**skills.mercuryagent.sh**](https://skills.mercuryagent.sh) hosts 126+
+community-contributed skills across 23 categories, and Mercury can install
+them from four surfaces — they all share the same install path under the hood.
+
+> **Review before you ship.** Skills run with elevated permissions when
+> invoked. Open the registry page (`mercury skills view <id> --web`) and read
+> the `SKILL.md` body before installing.
+
+For the file format, frontmatter spec, and runtime behavior, see
+[Reference → Skills](../reference/skills).
+
+## The four surfaces
+
+| Surface | Best for | Entry point |
+|---------|----------|-------------|
+| CLI subcommand (`mercury skills …`) | Scripting, batch installs, JSON output | `mercury skills install <id>` |
+| In-chat slash command (`/skills …`) | Quick browse while chatting with the agent | `/skills search <q>` |
+| Web dashboard | Visual browse + activate/deactivate toggle | `http://127.0.0.1:6174/skills` |
+| Telegram bot | Browse and install while away from the machine | `/skills install <id>` (admin-only) |
+
+All four hit the same `SkillStore.install(id)` code path, write to the same
+`~/.mercury/skills/<category>/<slug>/SKILL.md` location, and update the same
+`~/.mercury/skills/.index.json`.
+
+---
+
+## CLI: `mercury skills …`
+
+The fastest surface, available before or after starting the agent. No browser
+required.
+
+### Discover
+
+```bash
+mercury skills info # registry stats + reachability
+mercury skills categories # all 23 categories
+mercury skills browse finance-legal # paginated list
+mercury skills browse --page 2 --limit 20
+mercury skills search "contract review" # full-text search
+mercury skills search --limit 3 prompt
+```
+
+### Inspect before installing
+
+```bash
+mercury skills view finance-legal/contract-review
+mercury skills view finance-legal/contract-review --web # opens registry page
+mercury skills view finance-legal/contract-review --raw # prints raw SKILL.md
+```
+
+### Install, update, remove
+
+```bash
+# From the registry
+mercury skills install finance-legal/contract-review
+mercury skills install ai-ml/prompt-engineering finance-legal/contract-review # batch
+mercury skills install finance-legal/contract-review --force # reinstall same version
+
+# From a local file or arbitrary URL
+mercury skills install --from ./SKILL.md
+mercury skills install --from https://example.com/my-skill.md
+
+# Update
+mercury skills update # all installed
+mercury skills update finance-legal/contract-review # just one
+
+# Remove
+mercury skills remove finance-legal/contract-review
+
+# Observability
+mercury skills list # what's installed locally
+mercury skills doctor # install root + registry + cache
+```
+
+### Shared flags and environment variables
+
+| Flag | Purpose |
+|------|---------|
+| `--json` | Machine-readable output (useful for scripting / piping). |
+| `--registry <url>` | Use a different registry; also accepts `MERCURY_SKILLS_REGISTRY`. |
+| `-q`, `--quiet` | Suppress progress output. |
+| `-y`, `--yes` | Skip interactive confirmations. |
+
+| Environment variable | Purpose |
+|----------------------|---------|
+| `MERCURY_SKILLS_REGISTRY` | Default registry URL (overridden by `--registry`). |
+| `MERCURY_SKILLS_INSTALL_ROOT` | Alternate install root (defaults to `~/.mercury/skills`). |
+
+---
+
+## In-chat: `/skills …`
+
+Available in **every channel** — the CLI TUI, the web dashboard chat, and
+Telegram (subject to the Telegram-specific gating below). The slash command
+list autocompletes when you type `/skills` and press <kbd>Tab</kbd> in the
+CLI.
+
+```
+/skills # list installed skills
+/skills search <query> # top 5 registry matches with URLs
+/skills view <id> # title, version, description, registry URL
+/skills install <id> # install from the registry
+/skills install <url> # install raw SKILL.md from a URL
+/skills remove <id> # uninstall
+/skills help # subcommand list
+```
+
+Every `search` hit and every `view` response prints the
+`https://skills.mercuryagent.sh/skills/<id>` URL so you can review on the web
+before installing.
+
+Examples in a real chat session:
+
+```
+> /skills search contract
+🔍 Searching the registry for "contract"…
+
+Top 3 matches for "contract":
+
+• `finance-legal/contract-review` (v1.0.0)
+ Review contracts and surface risky clauses.
+ https://skills.mercuryagent.sh/skills/finance-legal/contract-review
+
+• `finance-legal/saas-agreement` (v0.2.1)
+ …
+
+> /skills install finance-legal/contract-review
+📦 Installing `finance-legal/contract-review` from the registry…
+✅ Installed `finance-legal/contract-review` (v1.0.0)
+🔗 https://skills.mercuryagent.sh/skills/finance-legal/contract-review
+```
+
+> Installs run **without a confirmation prompt** — same as the existing
+> in-chat URL-install behavior. The `view` step (or the registry URL printed
+> in `search` results) is where you should review before committing.
+
+---
+
+## Dashboard: `http://127.0.0.1:6174/skills`
+
+The Skills page in the web dashboard has two installers stacked in one card:
+
+1. **Install from registry** — paste a `category/slug` id and click Install.
+ The toast reports the install status (`installed`, `updated`,
+ `reinstalled`, `already-installed`) and the version.
+2. **Install from URL** — paste a URL pointing to a raw `SKILL.md`. Mercury
+ fetches it, validates the frontmatter, and saves it to disk.
+
+The page header has a **Browse skills.mercuryagent.sh** link that opens the
+registry in a new tab.
+
+Each installed skill card has:
+
+- A status badge (active / inactive).
+- A **toggle** to activate or deactivate without deleting.
+- A **trash** button to delete (with confirmation dialog).
+
+The dashboard talks to these endpoints:
+
+```
+GET /api/skills # list installed with active state
+POST /api/skills/install # { url } — fetch and install from a URL
+POST /api/skills/install-from-registry # { id, force? } — install by registry id
+POST /api/skills/:name/activate
+POST /api/skills/:name/deactivate
+DELETE /api/skills/:name
+```
+
+---
+
+## Telegram: `/skills …`
+
+Same subcommand surface as in-chat, with one extra rule:
+
+- `list`, `search`, `view` are available to **every approved user**.
+- `install` and `remove` are **admin-only** (same gate as `/unpair`).
+
+```
+/skills # list installed
+/skills search <query> # registry search
+/skills view <id> # details + URL
+/skills install <id> # admin only
+/skills remove <id> # admin only
+/skills help
+```
+
+The bot includes the `https://skills.mercuryagent.sh/skills/<id>` URL in every
+`search` result and every `view` response, so non-admin members can review a
+skill on a browser and then ask an admin to install it.
+
+`/skills` is registered in the Telegram command menu (between `/spotify` and
+`/unpair`), so it appears in autocomplete next to all the other bot commands.
+
+---
+
+## What happens on install (one paragraph)
+
+`SkillStore.install(id)` calls `GET /api/skills/<id>` for the JSON detail,
+short-circuits with `'already-installed'` if the local index already has the
+same version (unless `--force`), reconstructs the canonical `SKILL.md` from
+the JSON `frontmatter + body` fields, **atomically** writes it to
+`~/.mercury/skills/<category>/<slug>/SKILL.md` (tmp file + rename),
+verification-reads the file back, then updates
+`~/.mercury/skills/.index.json`. If either write fails, both the file and the
+index are rolled back so they never disagree. Skill ids must match
+`^[a-z0-9-]+/[a-z0-9-]+$` — that's the path-traversal guard.
+
+The agent picks up newly installed skills on its next discovery scan (next
+agent boot or `/skills` view in the dashboard).
+
+---
+
+## Troubleshooting
+
+| Symptom | Fix |
+|---------|-----|
+| `Invalid skill id` | The id must be `<category>/<slug>`, lowercase, hyphen-separated. Don't include the full URL. |
+| `Registry 404` | The id doesn't exist on the registry. Run `mercury skills search <q>` to find the right id. |
+| `Registry timeout` / `unreachable` | Run `mercury skills doctor` to confirm reachability and cache state. Pass `--registry` or set `MERCURY_SKILLS_REGISTRY` if you self-host. |
+| Install succeeded but the agent doesn't see the new skill | The skill loader scans on boot. Restart Mercury or open the dashboard's Skills page (it triggers a re-scan). |
+| `Post-install verification failed` | The disk write didn't round-trip. Usually disk-full or a permission issue under `~/.mercury/skills/`. The CLI rolls back automatically. |
+
+---
+
+## Related
+
+- [Reference → Skills](../reference/skills) — file format, frontmatter spec, runtime behavior, writing your own.
+- [CLI Commands](./cli-commands) — full `mercury` command reference.
+- [In-chat commands](./in-chat-commands) — all slash commands in chat.
diff --git a/website/docs/reference/skills.mdx b/website/docs/reference/skills.mdx
index 714e1a08..74f59096 100644
--- a/website/docs/reference/skills.mdx
+++ b/website/docs/reference/skills.mdx
@@ -78,20 +78,88 @@ Mercury uses **progressive disclosure**: only the frontmatter and a short summar
## Installing skills
+The fastest path is the [Mercury Skills registry](https://skills.mercuryagent.sh) — a community catalog of 126+ vetted skills across 23 categories. Every skill on the registry has a public detail page you should review before installing; skills run with elevated permissions when invoked.
+
+> See the [Skills command reference](../cli-commands/skills) for the complete CLI / in-chat / dashboard / Telegram surface in one place. The summary below is a quickstart.
+
+### From the CLI (recommended)
+
+The `mercury skills` command tree talks to the registry directly. No browser required.
+
+```bash
+# Discover
+mercury skills categories # 23 categories
+mercury skills browse finance-legal # paginated list, with --page / --limit
+mercury skills search "contract review" # full-text search
+
+# Inspect before installing
+mercury skills view finance-legal/contract-review
+mercury skills view finance-legal/contract-review --web # opens the registry page
+mercury skills view finance-legal/contract-review --raw # prints raw SKILL.md
+
+# Install / update / remove
+mercury skills install finance-legal/contract-review
+mercury skills install <id1> <id2> <id3> # batch
+mercury skills install <id> --force # reinstall same version
+mercury skills install --from ./local-skill.md # install from a local file or URL
+mercury skills update # update all installed
+mercury skills update finance-legal/contract-review # update one
+mercury skills remove finance-legal/contract-review
+
+# Observability
+mercury skills list # what's installed locally
+mercury skills info # registry stats
+mercury skills doctor # check registry reachability + cache
+```
+
+Shared flags:
+
+- `--json` — emit machine-readable output (useful for scripting).
+- `--registry <url>` — point at a different registry (also `MERCURY_SKILLS_REGISTRY`).
+- `-q, --quiet` — suppress progress output.
+- `-y, --yes` — skip confirmations.
+
+Registry skills install into a nested layout to avoid name collisions:
+
+```
+~/.mercury/skills/
+├── <category>/<slug>/SKILL.md # registry skills (new)
+├── _template/ # seeded template
+├── web-search/ # legacy flat layout still works
+└── .index.json # source of truth for `list` and `update`
+```
+
+The CLI never executes a skill's body during install — only writes the `SKILL.md` to disk after validating its frontmatter. Always review the registry page (`mercury skills view <id> --web`) before installing.
+
### From the web dashboard
-Open **Configure → Skills** (`/skills`) in the dashboard.
+Open **Skills** in the dashboard at `http://127.0.0.1:6174/skills`.
+
+- **Install from registry** — paste a `category/slug` id (e.g. `finance-legal/contract-review`) and click Install. The toast reports the install status (`installed`, `updated`, `reinstalled`, `already-installed`).
+- **Install from URL** — paste a URL pointing to a raw `SKILL.md`. Mercury fetches it, validates the frontmatter, and saves it to disk.
+- Use the **toggle** to activate or deactivate a skill without deleting it.
+- Use the **trash icon** to delete a skill (removes its directory and its index entry).
+- The header has a **Browse skills.mercuryagent.sh** link that opens the registry in a new tab.
+
+### From Telegram
+
+If you've paired a Telegram bot, the `/skills` command is available to every approved user. Install is admin-only.
+
+```
+/skills # list installed skills + counts
+/skills search <query> # top 5 registry matches with their URLs
+/skills view <id> # title, version, description, registry URL
+/skills install <id> # admin only — installs to ~/.mercury/skills/
+/skills remove <id> # admin only
+```
-- The page lists every installed skill with its description, version, active state, and `allowed-tools`.
-- Click **Install from URL** and paste a URL pointing to a raw `SKILL.md` file. Mercury fetches it (`http://` or `https://`), validates the frontmatter, and saves it to `~/.mercury/skills/<name>/SKILL.md`.
-- Use the **toggle** to activate or deactivate a skill without deleting it. Deactivated skills are not loaded into Mercury's intent router.
-- Use the **trash icon** to delete a skill (removes the directory from disk).
+Every result includes the `https://skills.mercuryagent.sh/skills/<id>` URL so you can review the skill on a real browser before installing it.
### From chat
-Tell Mercury in any channel:
+You can also tell Mercury in any channel:
-- "Install skill from https://example.com/my-skill.md"
+- "Install skill from `https://example.com/my-skill.md`"
- Or paste the SKILL.md content directly into a message and ask Mercury to install it.
### Manually
@@ -110,8 +178,9 @@ When invoked, Mercury injects the skill's Markdown body into context as guidance
The web dashboard talks to the skill loader through these endpoints:
```
-GET /api/skills # list installed skills with active state
-POST /api/skills/install # { url } — fetch and install from a URL
+GET /api/skills # list installed skills with active state
+POST /api/skills/install # { url } — fetch and install from a URL
+POST /api/skills/install-from-registry # { id, force? } — install by registry id
POST /api/skills/:name/activate
POST /api/skills/:name/deactivate
DELETE /api/skills/:name
diff --git a/website/sidebars.ts b/website/sidebars.ts
index 1859da94..0398e008 100644
--- a/website/sidebars.ts
+++ b/website/sidebars.ts
@@ -24,6 +24,7 @@ const sidebars: SidebarsConfig = {
items: [
'cli-commands/cli-commands',
'cli-commands/doctor',
+ 'cli-commands/skills',
'cli-commands/in-chat-commands',
],
},
diff --git a/website/src/pages/index.tsx b/website/src/pages/index.tsx
index e1c05cd9..b00597a5 100644
--- a/website/src/pages/index.tsx
+++ b/website/src/pages/index.tsx
@@ -438,6 +438,7 @@ export default function LandingPage(): React.ReactElement {
<Link to="/#pillars" onClick={() => setMobileMenuOpen(false)}>Features</Link>
<Link to="/#live-demo" onClick={() => setMobileMenuOpen(false)}>Demo</Link>
<Link to="/#channels" onClick={() => setMobileMenuOpen(false)}>Channels</Link>
+ <Link to="/#skills" onClick={() => setMobileMenuOpen(false)}>Skills</Link>
<Link to="/#agents" onClick={() => setMobileMenuOpen(false)}>Multi-Agent</Link>
<Link to="/#compare" onClick={() => setMobileMenuOpen(false)}>Compare</Link>
<Link to="/docs" onClick={() => setMobileMenuOpen(false)}>Docs</Link>
@@ -617,6 +618,72 @@ export default function LandingPage(): React.ReactElement {
</div>
</section>
+ {/* Skills Registry */}
+ <section id="skills" className="lp-section">
+ <div className="lp-container">
+ <h2 className="lp-section-title">Skills Registry</h2>
+ <p className="lp-section-sub">
+ Install vetted, single-purpose capabilities from <a href="https://skills.mercuryagent.sh" target="_blank" rel="noopener noreferrer">skills.mercuryagent.sh</a> — 126+ skills across 23 categories. Review the source, then install with one command.
+ </p>
+
+ <div className="lp-channels-grid lp-reveal" style={{ marginTop: '2rem' }}>
+ <div className="lp-channel-card">
+ <div className="lp-channel-header">
+ <span className="lp-channel-icon">{'>'}_</span>
+ <h3>From the CLI</h3>
+ </div>
+ <div className="lp-terminal-inline" style={{ marginBottom: '0.75rem' }}>
+ <code>mercury skills search contract</code>
+ </div>
+ <div className="lp-terminal-inline" style={{ marginBottom: '0.75rem' }}>
+ <code>mercury skills view finance-legal/contract-review</code>
+ </div>
+ <div className="lp-terminal-inline">
+ <code>mercury skills install finance-legal/contract-review</code>
+ </div>
+ </div>
+ <div className="lp-channel-card">
+ <div className="lp-channel-header">
+ <span className="lp-channel-icon">◧</span>
+ <h3>From the Dashboard</h3>
+ </div>
+ <ul>
+ <li>Open <strong>Skills</strong> in the sidebar at <code>localhost:6174</code>.</li>
+ <li>Paste <code>category/slug</code> into the registry installer.</li>
+ <li>Toggle skills on/off without removing them.</li>
+ <li>Or use the URL installer for raw <code>SKILL.md</code> files.</li>
+ </ul>
+ </div>
+ <div className="lp-channel-card">
+ <div className="lp-channel-header">
+ <span className="lp-channel-icon">✈</span>
+ <h3>From Telegram</h3>
+ </div>
+ <ul>
+ <li><code>/skills</code> — list installed skills</li>
+ <li><code>/skills search &lt;query&gt;</code> — search the registry</li>
+ <li><code>/skills view &lt;id&gt;</code> — show details + registry URL</li>
+ <li><code>/skills install &lt;id&gt;</code> — admin only</li>
+ </ul>
+ </div>
+ </div>
+
+ <div style={{ textAlign: 'center', marginTop: '2.5rem' }}>
+ <a
+ href="https://skills.mercuryagent.sh"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="lp-btn lp-btn-primary"
+ >
+ Browse the registry →
+ </a>{' '}
+ <Link to="/docs/reference/skills" className="lp-btn lp-btn-secondary">
+ Read the docs
+ </Link>
+ </div>
+ </div>
+ </section>
+
{/* Multi-Agent */}
<section id="agents" className="lp-section lp-section-dark">
<div className="lp-container">