Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(skills): skill builder — describe a skill, Mercury writes it, you save it
Salman Qureshid9678affc09c
diff --git a/src/index.ts b/src/index.tsindex e8df5e9b..21b9715b 100644--- a/src/index.ts+++ b/src/index.ts@@ -102,6 +102,7 @@ import { setCloudReload } from './web/api/cloud.js';import { spawnDetachedRestart } from './cli/daemon.js';import { recordVoiceCalls } from './plugins/voice-calls.js';import { setChannelRuntime } from './web/api/channels.js';+import { setSkillBuilder } from './web/api/system.js';import { isWebAuthInitialized, setWebPassword, writeAttachToken, initWebAuth } from './web/auth.js';import { startLoopLagMonitor } from './utils/loop-lag.js';import { McpManager, probeMcpServer, validateMcpConfig, type McpServerStatus } from './capabilities/mcp/index.js';@@ -3490,6 +3491,8 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {setWebBgTasks(agent.backgroundTasks);setWebModelSwitch((provider, model) => agent.switchProvider(provider, model));setProvidersReload(() => agent.reloadProviders());+ // Settings-free skill builder: the default model writes a skill from the owner's description.+ setSkillBuilder({ provider: () => providers.getDefault(), tools: () => Object.keys(capabilities.getTools()).sort() });setCloudReload(() => agent.reloadProviders());setWebStop(() => agent.stopAllWork('stopped'));setWebCurrentProvider(() => agent.getCurrentProvider());diff --git a/src/skills/builder.test.ts b/src/skills/builder.test.tsnew file mode 100644index 00000000..ad2bfadd--- /dev/null+++ b/src/skills/builder.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from 'vitest';+import { buildSkillDraft, draftProblem, parseDraft } from './builder.js';++const good = {+ name: 'Weekly Sales Report',+ description: 'Builds the weekly sales report from the shared sheet as a PDF for the owner.',+ intents: ['make the weekly sales report', 'sales report for this week'],+ instructions: '1. Ask the owner which week (default: last full week).\n2. Read the sales sheet with the sheets tool.\n3. Total revenue per product and compare with the previous week.\n4. Write the summary and a table, then export a PDF.\n5. Open the PDF to check it has every product and the totals match the sheet.\n6. Send the PDF and a two-line summary.',+ allowedTools: ['read_file', 'not_a_real_tool'],+};++const provider = (...replies: string[]) => {+ const generateText = vi.fn();+ for (const r of replies) generateText.mockResolvedValueOnce({ text: r });+ return { generateText, getModel: () => 'test-model' } as never;+};++describe('skill builder', () => {+ it('reads a draft even with chatter and fences around it, and drops tools that do not exist', () => {+ const d = parseDraft('Sure!\n```json\n' + JSON.stringify(good) + '\n```', ['read_file', 'web_search']);+ expect(d.name).toBe('weekly-sales-report');+ expect(d.allowedTools).toEqual(['read_file']);+ expect(draftProblem(d)).toBeNull();+ });++ it('a reply with no skill in it is a clear error', () => {+ expect(() => parseDraft('I cannot help with that.', [])).toThrow(/didn't return a skill/);+ });++ it('fixes a draft that breaks the rules with one automatic retry', async () => {+ const p = provider(JSON.stringify({ ...good, instructions: 'Do the report.' }), JSON.stringify(good));+ const r = await buildSkillDraft(p, 'a weekly sales report from my sheet', ['read_file']);+ expect(r.problem).toBeNull();+ expect(r.draft.instructions).toContain('1. Ask the owner');+ expect((p as any).generateText).toHaveBeenCalledTimes(2);+ expect((p as any).generateText.mock.calls[1][0]).toMatch(/Fix this: instructions are too short/);+ });++ it('asks for changes in the owner\'s words', async () => {+ const p = provider(JSON.stringify(good));+ await buildSkillDraft(p, 'sales report', ['read_file'], { draft: parseDraft(JSON.stringify(good), ['read_file']), feedback: 'also email it to finance' });+ expect((p as any).generateText.mock.calls[0][0]).toContain('Change it like this: also email it to finance');+ });+});diff --git a/src/skills/builder.ts b/src/skills/builder.tsnew file mode 100644index 00000000..7a47e628--- /dev/null+++ b/src/skills/builder.ts@@ -0,0 +1,81 @@+import type { BaseProvider } from '../providers/base.js';+import { MAX_INSTRUCTION_CHARS, MIN_INSTRUCTION_CHARS, rejectDraft, slugify } from './self-made.js';++/**+ * The skill builder: the owner describes a skill in their own words and+ * Mercury's model writes it (name, when to use it, a step-by-step+ * procedure, the tools it needs). Nothing is saved here; the owner reviews,+ * edits or asks for changes, then saves it as a self-made skill.+ */++export interface SkillDraft {+ name: string;+ description: string;+ intents: string[];+ instructions: string;+ allowedTools?: string[];+}++export const BUILDER_VERIFIED_NOTE = 'Written with the skill builder from the owner\'s description; not run yet.';++const SYSTEM = `You write skills for Mercury, a personal AI agent. A skill is a reusable, step-by-step procedure Mercury follows when the owner asks for that kind of task.++Return ONLY a JSON object, no prose, no code fences:+{+ "name": "short-kebab-slug (3-40 chars)",+ "description": "One or two sentences (20-220 chars): what it does and for which inputs.",+ "intents": ["3-6 ways the owner would ask for this, in plain words"],+ "instructions": "The procedure as numbered steps (1. 2. 3.). Exact tools to use, inputs to ask the owner for, checks to make, the output to deliver, and pitfalls. ${MIN_INSTRUCTION_CHARS}-${Math.min(4000, MAX_INSTRUCTION_CHARS)} chars. No credentials: refer to where they are configured.",+ "allowedTools": ["only tools from the list given, the fewest that do the job"]+}++Rules: concrete and runnable, not a narrative; ask the owner for anything you can't know; verify the result before reporting; never invent tools.`;++export function builderPrompt(request: string, tools: string[], previous?: { draft: SkillDraft; feedback: string }): string {+ const lines = [`The owner wants a skill for this:\n${request.trim()}`, '', `Tools Mercury has (use these names exactly): ${tools.slice(0, 200).join(', ') || '(none listed)'}`];+ if (previous) lines.push('', 'Your previous draft:', JSON.stringify(previous.draft), '', `Change it like this: ${previous.feedback.trim()}`);+ return lines.join('\n');+}++/** Pull the JSON object out of a model reply (tolerates fences and chatter around it). */+export function parseDraft(text: string, tools: string[]): SkillDraft {+ const start = text.indexOf('{');+ const end = text.lastIndexOf('}');+ if (start < 0 || end <= start) throw new Error('The model didn\'t return a skill. Try describing it again.');+ let raw: Record<string, unknown>;+ try { raw = JSON.parse(text.slice(start, end + 1)); } catch { throw new Error('The model returned something that isn\'t a skill. Try again.'); }+ const str = (v: unknown) => (typeof v === 'string' ? v.trim() : '');+ const known = new Set(tools);+ const allowed = Array.isArray(raw.allowedTools) ? (raw.allowedTools as unknown[]).map(str).filter((t) => t && (known.size === 0 || known.has(t))) : [];+ return {+ name: slugify(str(raw.name)) ?? str(raw.name),+ description: str(raw.description),+ intents: Array.isArray(raw.intents) ? (raw.intents as unknown[]).map(str).filter(Boolean).slice(0, 12) : [],+ instructions: str(raw.instructions),+ ...(allowed.length ? { allowedTools: [...new Set(allowed)] } : {}),+ };+}++/** What's wrong with a draft as a self-made skill, or null. */+export function draftProblem(d: SkillDraft): string | null {+ return rejectDraft({ ...d, verified: BUILDER_VERIFIED_NOTE });+}++/**+ * Write a draft with the given model. One automatic retry when the first+ * try breaks the skill rules, telling the model exactly what to fix.+ */+export async function buildSkillDraft(provider: BaseProvider, request: string, tools: string[], previous?: { draft: SkillDraft; feedback: string }): Promise<{ draft: SkillDraft; problem: string | null; model: string }> {+ const first = await provider.generateText(builderPrompt(request, tools, previous), SYSTEM);+ let draft = parseDraft(first.text, tools);+ let problem = draftProblem(draft);+ if (problem) {+ const again = await provider.generateText(builderPrompt(request, tools, { draft, feedback: `Fix this: ${problem}.` }), SYSTEM);+ try {+ const fixed = parseDraft(again.text, tools);+ const fixedProblem = draftProblem(fixed);+ if (!fixedProblem || fixedProblem.length <= problem.length) { draft = fixed; problem = fixedProblem; }+ } catch { /* keep the first draft and say what's wrong */ }+ }+ return { draft, problem, model: provider.getModel() };+}diff --git a/src/skills/loader.ts b/src/skills/loader.tsindex 5aee83b6..d972ac26 100644--- a/src/skills/loader.ts+++ b/src/skills/loader.ts@@ -296,6 +296,7 @@ export class SkillLoader {list.push({name: parsed.meta.name,description: parsed.meta.description,+ ...(parsed.meta.category ? { category: parsed.meta.category } : {}),active: !disabled,});} catch (err) {diff --git a/src/skills/types.ts b/src/skills/types.tsindex 2431ad20..3e60fa67 100644--- a/src/skills/types.ts+++ b/src/skills/types.ts@@ -30,6 +30,8 @@ export interface SkillBatch {export interface SkillDiscovery {name: string;description: string;+ /** e.g. "self-made" for skills Mercury wrote (ADR-027). */+ category?: string;}export interface Skill extends SkillMeta {diff --git a/src/web/api/skill-builder-route.test.ts b/src/web/api/skill-builder-route.test.tsnew file mode 100644index 00000000..76837db9--- /dev/null+++ b/src/web/api/skill-builder-route.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from 'vitest';++await vi.hoisted(async () => {+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ process.env.MERCURY_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-skill-builder-'));+});++import system, { setSkillBuilder } from './system.js';++const draft = {+ name: 'tidy-downloads',+ description: 'Sorts the Downloads folder into subfolders by file type and removes duplicates.',+ intents: ['tidy my downloads', 'clean up downloads'],+ instructions: '1. Ask which folder (default ~/Downloads).\n2. List the files with list_dir.\n3. Group them by type: images, documents, archives, installers, other.\n4. Move each file into its group folder; never overwrite, add a number instead.\n5. Find exact duplicates by size and hash and ask before deleting any.\n6. Report what moved and what was removed.',+};+const post = (path: string, body: unknown) => system.request(`http://127.0.0.1${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });++describe('skill builder routes', () => {+ it('drafts with the default model and the real tool list', async () => {+ const generateText = vi.fn().mockResolvedValue({ text: JSON.stringify({ ...draft, allowedTools: ['list_dir', 'made_up'] }) });+ setSkillBuilder({ provider: () => ({ generateText, getModel: () => 'm' }) as never, tools: () => ['list_dir', 'move_file'] });+ const res = await post('/api/skills/draft', { request: 'tidy my downloads folder by type' });+ const body = (await res.json()) as any;+ expect(res.status).toBe(200);+ expect(body.draft.allowedTools).toEqual(['list_dir']);+ expect(body.problem).toBeNull();+ expect(generateText.mock.calls[0][0]).toContain('list_dir, move_file');+ });++ it('refuses a description that says too little, and an unsaveable draft', async () => {+ expect((await post('/api/skills/draft', { request: 'help' })).status).toBe(400);+ expect((await post('/api/skills/self-made', { draft: { ...draft, instructions: 'tidy it' } })).status).toBe(400);+ });++ it('saves a reviewed draft as a self-made skill that shows up in the list', async () => {+ const res = await post('/api/skills/self-made', { draft });+ expect(res.status).toBe(200);+ expect(((await res.json()) as any).name).toBe('tidy-downloads');+ const list = (await (await system.request('http://127.0.0.1/api/skills')).json()) as { skills: Array<{ name: string; selfMade: boolean }> };+ expect(list.skills.find((s) => s.name === 'tidy-downloads')?.selfMade).toBe(true);+ });+});diff --git a/src/web/api/system.ts b/src/web/api/system.tsindex 7771dcda..c63a25b6 100644--- a/src/web/api/system.ts+++ b/src/web/api/system.ts@@ -1,4 +1,7 @@import { Hono } from 'hono';+import type { BaseProvider } from '../../providers/base.js';+import { BUILDER_VERIFIED_NOTE, buildSkillDraft, draftProblem, type SkillDraft } from '../../skills/builder.js';+import { SELF_MADE_CATEGORY, composeSkillMd, readSelfMadeMeta, slugify } from '../../skills/self-made.js';import { readHistory, historySince } from '../../utils/token-history.js';import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';@@ -26,6 +29,7 @@ system.get('/api/skills', (c) => {name: skill.name,description: skill.description,active: skill.active,+ selfMade: skill.category === SELF_MADE_CATEGORY,version: full?.version ?? null,allowedTools: full?.['allowed-tools'] ?? [],hasScripts: !!full?.scriptsDir,@@ -35,6 +39,55 @@ system.get('/api/skills', (c) => {return c.json({ skills, total: skills.length });});+// ── Skill builder: describe a skill, Mercury writes it, you save it ─────────++type BuilderDeps = { provider: () => BaseProvider; tools: () => string[] };+let builder: BuilderDeps | null = null;+/** Registered by the runtime: the model to write with and the tools a skill may use. */+export function setSkillBuilder(deps: BuilderDeps | null): void { builder = deps; }++system.post('/api/skills/draft', async (c) => {+ if (!builder) return c.json({ error: 'The skill builder needs Mercury running with a model.' }, 503);+ const body = (await c.req.json().catch(() => ({}))) as { request?: unknown; previous?: { draft?: unknown; feedback?: unknown } };+ const request = typeof body.request === 'string' ? body.request.trim() : '';+ if (request.length < 10) return c.json({ error: 'Say a little more about what the skill should do.' }, 400);+ if (request.length > 4000) return c.json({ error: 'Keep the description under 4,000 characters.' }, 400);+ const prev = body.previous && typeof body.previous.feedback === 'string' && body.previous.feedback.trim() && body.previous.draft && typeof body.previous.draft === 'object'+ ? { draft: body.previous.draft as SkillDraft, feedback: body.previous.feedback }+ : undefined;+ try {+ const tools = builder.tools();+ const r = await buildSkillDraft(builder.provider(), request, tools, prev);+ const exists = r.draft.name ? new SkillLoader().load(r.draft.name) : null;+ return c.json({ ...r, clash: exists && exists.category !== SELF_MADE_CATEGORY ? `"${r.draft.name}" is already an installed skill; pick another name.` : null, tools });+ } catch (err) {+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 502);+ }+});++/** Save a reviewed draft as a self-made skill (marked not run yet until Mercury uses it). */+system.post('/api/skills/self-made', async (c) => {+ const body = (await c.req.json().catch(() => ({}))) as { draft?: Partial<SkillDraft> };+ const d = body.draft ?? {};+ const draft: SkillDraft = {+ name: String(d.name ?? '').trim(),+ description: String(d.description ?? '').trim(),+ intents: Array.isArray(d.intents) ? d.intents.map((i) => String(i).trim()).filter(Boolean) : [],+ instructions: String(d.instructions ?? '').trim(),+ ...(Array.isArray(d.allowedTools) && d.allowedTools.length ? { allowedTools: d.allowedTools.map(String) } : {}),+ };+ const problem = draftProblem(draft);+ if (problem) return c.json({ error: `Not saved: ${problem}.` }, 400);+ const slug = slugify(draft.name)!;+ const loader = new SkillLoader();+ const existing = loader.load(slug);+ if (existing && existing.category !== SELF_MADE_CATEGORY) return c.json({ error: `"${slug}" is already an installed skill. Pick a different name.`, field: 'name' }, 409);+ const file = join(loader.rootDir(), SELF_MADE_CATEGORY, slug, 'SKILL.md');+ const prior = existsSync(file) ? readSelfMadeMeta(readFileSync(file, 'utf-8')) ?? undefined : undefined;+ loader.saveSkill(`${SELF_MADE_CATEGORY}/${slug}`, composeSkillMd({ ...draft, verified: BUILDER_VERIFIED_NOTE }, prior));+ return c.json({ success: true, name: slug, updated: !!prior });+});+system.post('/api/skills/install', async (c) => {const body = await c.req.json();const url = String(body?.url || '').trim();