xonecas.io
64875
Mc

mini-coder / commit d66284f

feat: @skill and @agent references with tab autocomplete

- @skill-name injects ~/.agents/skills/*/SKILL.md content inline (XML-wrapped)
- @agent-name dispatches the prompt through a custom subagent with its own
  system prompt and optional model override
- Both resolve from ~/.agents/{skills,agents}/ (global) and
  .agents/{skills,agents}/ (local), local wins on conflict
- Tab autocomplete in input.ts surfaces skills and agents before files,
  all capped at 10 total results
- /help lists discovered agents (magenta) and skills (yellow)
- resolveFileRefs split into 3 phases: validate → substitute → dispatch,
  fixing agent prompt extraction using stale offsets, images being
  discarded on agent dispatch, depth hardcoded to 0, and multiple @agent
  refs silently dropped (now errors)

Sean2026-02-25 d66284fc18314691935247a21bf960892a03d15c parent 185ee5a

8 files changed

TODO.md+17−26
@@ -1,5 +1,22 @@
11 # TODO
22
3+## Investigate missing output?
4+
5+```
6+Summary of the design:
7+1. Skills (`~/.agents/skills/*/SKILL.md` + `.agents/skills/*/SKILL.md`): `@skill-name` in prompt → loads skill content into context. Tab-autocomplete from both global and local skill dirs.
8+2. Custom Agents (`~/.agents/agents/*.md` + `.agents/agents/*.md`): `@agent-name` in prompt → runs that agent as a subagent with its custom system prompt/model. YAML frontmatter with `description`, `model`.
9+^C3. Tab completion in input.ts should show `@skill-name` and `@agent-name` suggestions alongside file completions.
10+
11+[BIG WAIT HERE, nothing happening for 10m+, user used CTRL+c to return to prompt]
12+
13+claude-sonnet-4-6 mm1v6tyb ~/src/mini-coder ⎇ main ctx 55.9k/200.0k 28% ↑182.1k ↓949
14+▶ What happened?
15+◆ I'm mid-way through exploring the codebase to implement your `@` references feature for skills and custom agents. Here's what I've gathered so far:
16+```
17+
18+LLM said it was exploring but no output or tool calls were seen. Session continued normally after the "What happened?" message. (mm1v6tyb session id)
19+
320 ## Gemini models sometimes get stuck "thinking" forever
421
522 I've seen it a couple times, where after a tool call, gemini 3.1 pro will get stuck
@@ -47,29 +64,3 @@ persistence alongside `preferred_model`.
4764 Opus, o-series OpenAI models). Add a capability flag in `providers.ts`.
4865
4966 ---
50-
51-## `@` references for global skills / agent configs
52-
53-The idea says: *"Reference files, skills, agents from the working directory and
54-global community configs with `@` in prompt input."*
55-
56-Skills:
57-
58-- Should autocomplete from global `~/.agents/skills` and the local agents folder.
59-
60-Custom Agents:
61-
62-- [Claude's flow](https://code.claude.com/docs/en/sub-agents)
63-- [Opencode's flow](https://opencode.ai/docs/agents/#options)
64-
65-Let's implement our own with config in `~/.agents/agents/`. Skip the `/agent` command.
66-
67----
68-
69-Custom commands:
70-
71-https://opencode.ai/docs/commands/ I want to copy this approach to custom commands.
72-
73-Let's also create a local command to this repo, `/search` that fires a small model to explore the codebase for the arguments given.
74-
75-DO NOT make a new config structure! use `~/.agents/` for global commands and the local version `./.agents/` for repo commands.
src/agent/agent.ts+73−7
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
22 import { homedir } from "node:os";
33 import { join } from "node:path";
44 import * as c from "yoctocolors";
5+import { loadAgents } from "../cli/agents.ts";
56 import { type CommandContext, handleCommand } from "../cli/commands.ts";
67 import {
78 type ImageAttachment,
@@ -9,6 +10,7 @@ import {
910 loadImageFile,
1011 } from "../cli/image-types.ts";
1112 import { readline, type InputResult } from "../cli/input.ts";
13+import { loadSkills } from "../cli/skills.ts";
1214
1315 import {
1416 PREFIX,
@@ -189,6 +191,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
189191 prompt: string,
190192 depth = 0,
191193 model?: string,
194+ systemPromptOverride?: string,
192195 ): Promise<import("../tools/subagent.ts").SubagentOutput> => {
193196 const subMessages: CoreMessage[] = [{ role: "user", content: prompt }];
194197 const subTools = buildToolSet({
@@ -200,7 +203,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
200203
201204 const subLlm = resolveModel(model ?? currentModel);
202205
203- const systemPrompt = buildSystemPrompt(cwd);
206+ const systemPrompt = systemPromptOverride ?? buildSystemPrompt(cwd);
204207
205208 let result = "";
206209 let inputTokens = 0;
@@ -488,10 +491,12 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
488491 };
489492 process.on("SIGINT", onSigInt);
490493
491- // Resolve @file references — may expand image refs into additional attachments
494+ // Resolve @file/skill/agent references
492495 const { text: resolvedText, images: refImages } = await resolveFileRefs(
493496 text,
494497 cwd,
498+ 0, // depth 0: processUserInput is always top-level
499+ runSubagent,
495500 );
496501
497502 // Merge pasted images with @-ref images
@@ -676,29 +681,64 @@ export function hasRalphSignal(text: string): boolean {
676681 return /\/ralph\b/.test(text);
677682 }
678683
679-// ─── Resolve @file references in user input ────────────────────────────────────
684+// ─── Resolve @file/skill/agent references in user input ───────────────────────
680685
681686 async function resolveFileRefs(
682687 text: string,
683688 cwd: string,
689+ depth: number,
690+ runSubagentFn: (
691+ prompt: string,
692+ depth: number,
693+ model?: string,
694+ systemPromptOverride?: string,
695+ ) => Promise<import("../tools/subagent.ts").SubagentOutput>,
684696 ): Promise<{ text: string; images: ImageAttachment[] }> {
685- // Find all @<path> tokens
686697 const atPattern = /@([\w./\-_]+)/g;
687698 let result = text;
688699 const matches = [...text.matchAll(atPattern)];
689700 const images: ImageAttachment[] = [];
690701
691- for (const match of matches.reverse()) {
702+ // Load agents and skills once for this resolution pass
703+ const agents = loadAgents(cwd);
704+ const skills = loadSkills(cwd);
705+
706+ // ── Phase 1: validate — catch multiple @agent refs up front ───────────────
707+ const agentMatches = matches.filter((m) => m[1] && agents.has(m[1]));
708+ if (agentMatches.length > 1) {
709+ throw new Error(
710+ `Only one @agent reference is allowed per message, found: ${agentMatches.map((m) => m[0]).join(", ")}`,
711+ );
712+ }
713+
714+ // ── Phase 2: substitute skills, images, and files (right-to-left) ─────────
715+ // Process all non-agent refs first so images are collected and the prompt
716+ // text that the agent receives is clean.
717+ for (const match of [...matches].reverse()) {
692718 const ref = match[1];
693719 if (!ref) continue;
720+
721+ // Skip agent refs — handled in phase 3
722+ if (agents.has(ref)) continue;
723+
724+ // @skill-name — inject skill content inline
725+ const skill = skills.get(ref);
726+ if (skill) {
727+ const replacement = `<skill name="${skill.name}">\n${skill.content}\n</skill>`;
728+ result =
729+ result.slice(0, match.index) +
730+ replacement +
731+ result.slice((match.index ?? 0) + match[0].length);
732+ continue;
733+ }
734+
694735 const filePath = ref.startsWith("/") ? ref : join(cwd, ref);
695736
696- // Image files: read as base64 and add as image attachment
737+ // @image-path — read as base64 attachment
697738 if (isImageFilename(ref)) {
698739 const attachment = await loadImageFile(filePath);
699740 if (attachment) {
700741 images.unshift(attachment); // reverse() + unshift = left-to-right order
701- // Remove the @ref token from the text
702742 result =
703743 result.slice(0, match.index) +
704744 result.slice((match.index ?? 0) + match[0].length);
@@ -706,6 +746,7 @@ async function resolveFileRefs(
706746 }
707747 }
708748
749+ // @file-path — inject file contents inline
709750 try {
710751 const content = await Bun.file(filePath).text();
711752 const lines = content.split("\n");
@@ -723,5 +764,30 @@ async function resolveFileRefs(
723764 }
724765 }
725766
767+ // ── Phase 3: agent dispatch (if any) ──────────────────────────────────────
768+ // By now skills/images/files have been resolved, so `result` contains the
769+ // clean prompt text. We use the original match index against `text` to strip
770+ // just the @agent-name token and pass everything else to the subagent.
771+ const agentMatch = agentMatches[0];
772+ if (agentMatch) {
773+ const ref = agentMatch[1];
774+ const agent = ref ? agents.get(ref) : undefined;
775+ if (!agent) return { text: result, images };
776+ // Strip the @agent-name token from the *original* text to get the prompt,
777+ // then layer in any skill expansions from `result`.
778+ const promptText = (
779+ result.slice(0, agentMatch.index) +
780+ result.slice((agentMatch.index ?? 0) + agentMatch[0].length)
781+ ).trim();
782+ const output = await runSubagentFn(
783+ promptText || "(no prompt)",
784+ depth,
785+ agent.model,
786+ agent.systemPrompt,
787+ );
788+ // Images collected above are passed through so callers can attach them.
789+ return { text: output.result, images };
790+ }
791+
726792 return { text: result, images };
727793 }
src/cli/agents.test.ts+72−0
@@ -0,0 +1,72 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { loadAgents } from "./agents.ts";
6+
7+describe("loadAgents", () => {
8+ let dir: string;
9+
10+ beforeEach(() => {
11+ dir = mkdtempSync(join(tmpdir(), "mc-agents-test-"));
12+ });
13+
14+ afterEach(() => {
15+ rmSync(dir, { recursive: true, force: true });
16+ });
17+
18+ function writeAgent(root: string, name: string, content: string): void {
19+ const agentsDir = join(root, ".agents", "agents");
20+ mkdirSync(agentsDir, { recursive: true });
21+ writeFileSync(join(agentsDir, `${name}.md`), content);
22+ }
23+
24+ test("returns empty map when no .agents/agents dir exists", () => {
25+ expect(loadAgents(dir).size).toBe(0);
26+ });
27+
28+ test("loads an agent with frontmatter", () => {
29+ writeAgent(
30+ dir,
31+ "reviewer",
32+ "---\ndescription: Code reviewer\nmodel: zen/claude-3-5-haiku\n---\n\nYou are a strict code reviewer.",
33+ );
34+ const agents = loadAgents(dir);
35+ const agent = agents.get("reviewer");
36+ expect(agent?.description).toBe("Code reviewer");
37+ expect(agent?.model).toBe("zen/claude-3-5-haiku");
38+ expect(agent?.systemPrompt).toBe("You are a strict code reviewer.");
39+ expect(agent?.source).toBe("local");
40+ });
41+
42+ test("falls back to name as description when frontmatter has none", () => {
43+ writeAgent(dir, "helper", "You help with things.");
44+ expect(loadAgents(dir).get("helper")?.description).toBe("helper");
45+ });
46+
47+ test("body without frontmatter is used as systemPrompt verbatim", () => {
48+ writeAgent(dir, "plain", "Just do the task.");
49+ expect(loadAgents(dir).get("plain")?.systemPrompt).toBe(
50+ "Just do the task.",
51+ );
52+ });
53+
54+ test("ignores non-.md files", () => {
55+ const agentsDir = join(dir, ".agents", "agents");
56+ mkdirSync(agentsDir, { recursive: true });
57+ writeFileSync(join(agentsDir, "script.sh"), "echo hi");
58+ expect(loadAgents(dir).size).toBe(0);
59+ });
60+
61+ test("local agent overrides global with same name", () => {
62+ // Write a local agent; global would be ~/.agents/agents/ (not writable in test)
63+ writeAgent(
64+ dir,
65+ "reviewer",
66+ "---\ndescription: local reviewer\n---\nLocal prompt",
67+ );
68+ const agents = loadAgents(dir);
69+ expect(agents.get("reviewer")?.description).toBe("local reviewer");
70+ expect(agents.get("reviewer")?.source).toBe("local");
71+ });
72+});
src/cli/agents.ts+96−0
@@ -0,0 +1,96 @@
1+import { existsSync, readFileSync, readdirSync } from "node:fs";
2+import { homedir } from "node:os";
3+import { basename, join } from "node:path";
4+
5+// ─── Types ────────────────────────────────────────────────────────────────────
6+
7+export interface AgentConfig {
8+ name: string;
9+ description: string;
10+ /** Override model for this agent (optional) */
11+ model?: string;
12+ /** System prompt (the markdown body after frontmatter) */
13+ systemPrompt: string;
14+ /** "global" (~/.agents/) or "local" (./.agents/) — local wins on conflict */
15+ source: "global" | "local";
16+}
17+
18+// ─── Frontmatter parser ───────────────────────────────────────────────────────
19+
20+interface Frontmatter {
21+ description?: string;
22+ model?: string;
23+}
24+
25+function parseFrontmatter(raw: string): { meta: Frontmatter; body: string } {
26+ const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
27+ const m = raw.match(FM_RE);
28+ if (!m) return { meta: {}, body: raw };
29+
30+ const meta: Frontmatter = {};
31+ const yamlBlock = m[1] ?? "";
32+ for (const line of yamlBlock.split("\n")) {
33+ const colon = line.indexOf(":");
34+ if (colon === -1) continue;
35+ const key = line.slice(0, colon).trim();
36+ const val = line
37+ .slice(colon + 1)
38+ .trim()
39+ .replace(/^["']|["']$/g, "");
40+ if (key === "description") meta.description = val;
41+ if (key === "model") meta.model = val;
42+ }
43+
44+ return { meta, body: (m[2] ?? "").trim() };
45+}
46+
47+// ─── Load agents from a directory ─────────────────────────────────────────────
48+
49+function loadFromDir(
50+ dir: string,
51+ source: "global" | "local",
52+): Map<string, AgentConfig> {
53+ const agents = new Map<string, AgentConfig>();
54+ if (!existsSync(dir)) return agents;
55+
56+ let entries: string[];
57+ try {
58+ entries = readdirSync(dir);
59+ } catch {
60+ return agents;
61+ }
62+
63+ for (const entry of entries) {
64+ if (!entry.endsWith(".md")) continue;
65+ const name = basename(entry, ".md");
66+ const filePath = join(dir, entry);
67+ let raw: string;
68+ try {
69+ raw = readFileSync(filePath, "utf-8");
70+ } catch {
71+ continue;
72+ }
73+ const { meta, body } = parseFrontmatter(raw);
74+ agents.set(name, {
75+ name,
76+ description: meta.description ?? name,
77+ ...(meta.model ? { model: meta.model } : {}),
78+ systemPrompt: body,
79+ source,
80+ });
81+ }
82+ return agents;
83+}
84+
85+// ─── Load all agents (global + local, local wins) ─────────────────────────────
86+
87+export function loadAgents(cwd: string): Map<string, AgentConfig> {
88+ const globalDir = join(homedir(), ".agents", "agents");
89+ const localDir = join(cwd, ".agents", "agents");
90+
91+ const global = loadFromDir(globalDir, "global");
92+ const local = loadFromDir(localDir, "local");
93+
94+ // Merge: local overrides global
95+ return new Map([...global, ...local]);
96+}
src/cli/commands.ts+41−2
@@ -8,6 +8,7 @@ import {
88 listMcpServers,
99 upsertMcpServer,
1010 } from "../session/db.ts";
11+import { loadAgents } from "./agents.ts";
1112 import {
1213 type CustomCommand,
1314 expandTemplate,
@@ -22,6 +23,7 @@ import {
2223 write,
2324 writeln,
2425 } from "./output.ts";
26+import { loadSkills } from "./skills.ts";
2527
2628 // ─── Types ────────────────────────────────────────────────────────────────────
2729
@@ -381,7 +383,10 @@ async function handleCustomCommand(
381383
382384 // ─── Help ─────────────────────────────────────────────────────────────────────
383385
384-function handleHelp(custom: Map<string, CustomCommand>): void {
386+function handleHelp(
387+ ctx: CommandContext,
388+ custom: Map<string, CustomCommand>,
389+): void {
385390 writeln();
386391
387392 const cmds: [string, string][] = [
@@ -417,7 +422,41 @@ function handleHelp(custom: Map<string, CustomCommand>): void {
417422 }
418423 }
419424
425+ // Show agents
426+ const agents = loadAgents(ctx.cwd);
427+ if (agents.size > 0) {
428+ writeln();
429+ writeln(c.dim(" agents (~/.agents/agents/ or .agents/agents/):"));
430+ for (const agent of agents.values()) {
431+ const tag =
432+ agent.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
433+ writeln(
434+ ` ${c.magenta(`@${agent.name}`.padEnd(26))} ${c.dim(agent.description)}${tag}`,
435+ );
436+ }
437+ }
438+
439+ // Show skills
440+ const skills = loadSkills(ctx.cwd);
441+ if (skills.size > 0) {
442+ writeln();
443+ writeln(c.dim(" skills (~/.agents/skills/ or .agents/skills/):"));
444+ for (const skill of skills.values()) {
445+ const tag =
446+ skill.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
447+ writeln(
448+ ` ${c.yellow(`@${skill.name}`.padEnd(26))} ${c.dim(skill.description)}${tag}`,
449+ );
450+ }
451+ }
452+
420453 writeln();
454+ writeln(
455+ ` ${c.green("@agent".padEnd(26))} ${c.dim("run prompt through a custom agent (Tab to complete)")}`,
456+ );
457+ writeln(
458+ ` ${c.green("@skill".padEnd(26))} ${c.dim("inject skill instructions into prompt (Tab to complete)")}`,
459+ );
421460 writeln(
422461 ` ${c.green("@file".padEnd(26))} ${c.dim("inject file contents into prompt (Tab to complete)")}`,
423462 );
@@ -477,7 +516,7 @@ export async function handleCommand(
477516
478517 case "help":
479518 case "?":
480- handleHelp(custom);
519+ handleHelp(ctx, custom);
481520 return { type: "handled" };
482521
483522 case "exit":
src/cli/input.ts+29−7
@@ -1,11 +1,13 @@
11 import { join, relative } from "node:path";
22 import * as c from "yoctocolors";
33 import { addPromptHistory, getPromptHistory } from "../session/db.ts";
4+import { loadAgents } from "./agents.ts";
45 import {
56 type ImageAttachment,
67 isImageFilename,
78 loadImageFile,
89 } from "./image-types.ts";
10+import { loadSkills } from "./skills.ts";
911
1012 // ─── ANSI escape sequences ────────────────────────────────────────────────────
1113
@@ -52,18 +54,38 @@ export type InputResult =
5254
5355 // ─── File autocomplete ────────────────────────────────────────────────────────
5456
55-async function getFileCompletions(
57+async function getAtCompletions(
5658 prefix: string,
5759 cwd: string,
5860 ): Promise<string[]> {
5961 const query = prefix.startsWith("@") ? prefix.slice(1) : prefix;
60- const glob = new Bun.Glob(`**/*${query}*`);
6162 const results: string[] = [];
62- for await (const file of glob.scan({ cwd, onlyFiles: true })) {
63- if (file.includes("node_modules") || file.includes(".git")) continue;
64- results.push(`@${relative(cwd, join(cwd, file))}`);
65- if (results.length >= 10) break;
63+ const MAX = 10;
64+
65+ // Skills: @<skill-name>
66+ const skills = loadSkills(cwd);
67+ for (const [name] of skills) {
68+ if (results.length >= MAX) break;
69+ if (name.includes(query)) results.push(`@${name}`);
70+ }
71+
72+ // Agents: @<agent-name>
73+ const agents = loadAgents(cwd);
74+ for (const [name] of agents) {
75+ if (results.length >= MAX) break;
76+ if (name.includes(query)) results.push(`@${name}`);
6677 }
78+
79+ // Files: @<relative-path> — fill remaining slots up to MAX
80+ if (results.length < MAX) {
81+ const glob = new Bun.Glob(`**/*${query}*`);
82+ for await (const file of glob.scan({ cwd, onlyFiles: true })) {
83+ if (file.includes("node_modules") || file.includes(".git")) continue;
84+ results.push(`@${relative(cwd, join(cwd, file))}`);
85+ if (results.length >= MAX) break;
86+ }
87+ }
88+
6789 return results;
6890 }
6991
@@ -461,7 +483,7 @@ export async function readline(opts: {
461483 const beforeCursor = buf.slice(0, cursor);
462484 const atMatch = beforeCursor.match(/@(\S*)$/);
463485 if (atMatch) {
464- const completions = await getFileCompletions(atMatch[0], cwd);
486+ const completions = await getAtCompletions(atMatch[0], cwd);
465487 if (completions.length === 1 && completions[0]) {
466488 const replacement = completions[0];
467489 buf =
src/cli/skills.test.ts+84−0
@@ -0,0 +1,84 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { loadSkills } from "./skills.ts";
6+
7+describe("loadSkills", () => {
8+ let dir: string;
9+
10+ beforeEach(() => {
11+ dir = mkdtempSync(join(tmpdir(), "mc-skills-test-"));
12+ });
13+
14+ afterEach(() => {
15+ rmSync(dir, { recursive: true, force: true });
16+ });
17+
18+ function writeSkill(root: string, folderName: string, content: string): void {
19+ const skillDir = join(root, ".agents", "skills", folderName);
20+ mkdirSync(skillDir, { recursive: true });
21+ writeFileSync(join(skillDir, "SKILL.md"), content);
22+ }
23+
24+ test("returns empty map when no .agents/skills dir exists", () => {
25+ expect(loadSkills(dir).size).toBe(0);
26+ });
27+
28+ test("loads a skill with name and description from frontmatter", () => {
29+ writeSkill(
30+ dir,
31+ "git-release",
32+ "---\nname: git-release\ndescription: Create consistent releases\n---\n\n# Instructions\nUse conventional commits.",
33+ );
34+ const skills = loadSkills(dir);
35+ const skill = skills.get("git-release");
36+ expect(skill?.name).toBe("git-release");
37+ expect(skill?.description).toBe("Create consistent releases");
38+ expect(skill?.content).toContain("Use conventional commits.");
39+ expect(skill?.source).toBe("local");
40+ });
41+
42+ test("falls back to folder name when frontmatter has no name", () => {
43+ writeSkill(dir, "my-skill", "---\ndescription: A skill\n---\nContent.");
44+ const skills = loadSkills(dir);
45+ // key is name from frontmatter or folder name
46+ expect(skills.get("my-skill")?.name).toBe("my-skill");
47+ });
48+
49+ test("falls back to name as description when frontmatter has none", () => {
50+ writeSkill(dir, "no-desc", "---\nname: no-desc\n---\nContent.");
51+ expect(loadSkills(dir).get("no-desc")?.description).toBe("no-desc");
52+ });
53+
54+ test("skill content includes the raw SKILL.md text", () => {
55+ const raw =
56+ "---\nname: test-skill\ndescription: Test\n---\n\nDo the thing.";
57+ writeSkill(dir, "test-skill", raw);
58+ expect(loadSkills(dir).get("test-skill")?.content).toBe(raw);
59+ });
60+
61+ test("ignores entries without a SKILL.md", () => {
62+ const skillDir = join(dir, ".agents", "skills", "empty-folder");
63+ mkdirSync(skillDir, { recursive: true });
64+ expect(loadSkills(dir).size).toBe(0);
65+ });
66+
67+ test("ignores non-directory entries in skills dir", () => {
68+ const skillsDir = join(dir, ".agents", "skills");
69+ mkdirSync(skillsDir, { recursive: true });
70+ writeFileSync(join(skillsDir, "not-a-dir.md"), "stuff");
71+ expect(loadSkills(dir).size).toBe(0);
72+ });
73+
74+ test("local skill overrides global with same name", () => {
75+ writeSkill(
76+ dir,
77+ "git-release",
78+ "---\nname: git-release\ndescription: local version\n---\nLocal content.",
79+ );
80+ const skills = loadSkills(dir);
81+ expect(skills.get("git-release")?.description).toBe("local version");
82+ expect(skills.get("git-release")?.source).toBe("local");
83+ });
84+});
src/cli/skills.ts+87−0
@@ -0,0 +1,87 @@
1+import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2+import { homedir } from "node:os";
3+import { join } from "node:path";
4+
5+// ─── Types ────────────────────────────────────────────────────────────────────
6+
7+export interface Skill {
8+ name: string;
9+ description: string;
10+ /** Full content of the SKILL.md (frontmatter + body) */
11+ content: string;
12+ /** "global" (~/.agents/) or "local" (./.agents/) — local wins on conflict */
13+ source: "global" | "local";
14+}
15+
16+// ─── Frontmatter parser (name + description only) ────────────────────────────
17+
18+function parseSkillMeta(raw: string): { name?: string; description?: string } {
19+ const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---/;
20+ const m = raw.match(FM_RE);
21+ if (!m) return {};
22+
23+ const meta: { name?: string; description?: string } = {};
24+ for (const line of (m[1] ?? "").split("\n")) {
25+ const colon = line.indexOf(":");
26+ if (colon === -1) continue;
27+ const key = line.slice(0, colon).trim();
28+ const val = line
29+ .slice(colon + 1)
30+ .trim()
31+ .replace(/^["']|["']$/g, "");
32+ if (key === "name") meta.name = val;
33+ if (key === "description") meta.description = val;
34+ }
35+ return meta;
36+}
37+
38+// ─── Load skills from a skills root dir ──────────────────────────────────────
39+// Each skill lives at <dir>/<skill-name>/SKILL.md
40+
41+function loadFromDir(
42+ dir: string,
43+ source: "global" | "local",
44+): Map<string, Skill> {
45+ const skills = new Map<string, Skill>();
46+ if (!existsSync(dir)) return skills;
47+
48+ let entries: string[];
49+ try {
50+ entries = readdirSync(dir);
51+ } catch {
52+ return skills;
53+ }
54+
55+ for (const entry of entries) {
56+ const skillFile = join(dir, entry, "SKILL.md");
57+ try {
58+ if (!statSync(join(dir, entry)).isDirectory()) continue;
59+ if (!existsSync(skillFile)) continue;
60+ const content = readFileSync(skillFile, "utf-8");
61+ const meta = parseSkillMeta(content);
62+ const name = meta.name ?? entry;
63+ skills.set(name, {
64+ name,
65+ description: meta.description ?? name,
66+ content,
67+ source,
68+ });
69+ } catch {
70+ // skip unreadable entries
71+ }
72+ }
73+ return skills;
74+}
75+
76+// ─── Load all skills (global + local, local wins) ────────────────────────────
77+
78+export function loadSkills(cwd: string): Map<string, Skill> {
79+ const globalDir = join(homedir(), ".agents", "skills");
80+ const localDir = join(cwd, ".agents", "skills");
81+
82+ const global = loadFromDir(globalDir, "global");
83+ const local = loadFromDir(localDir, "local");
84+
85+ // Merge: local overrides global
86+ return new Map([...global, ...local]);
87+}