xonecas.io
64875
Mc

mini-coder / commit 48f8e96

feat: custom commands via .agents/commands/ (opencode-style)

- Load .md files from ~/.agents/commands/ (global) and ./.agents/commands/ (local)
- Local commands override global on name conflict
- Frontmatter: description, model (optional override)
- Template expansion: $ARGUMENTS, $1-$9, !`cmd` shell interpolation
- Shell interpolation: 10s timeout, stderr suppressed on non-zero exit
- loadCustomCommands called lazily (only in help/default branches)
- handleCommand dispatches unknown /commands to custom commands before erroring
- /help shows custom commands with (local)/(global) source tag
- runSubagent accepts optional model override, threaded through cmdCtx
- Add local /search command using zen/claude-3-5-haiku
- 19 tests for parseFrontmatter, loadCustomCommands, and expandTemplate

Sean2026-02-25 48f8e960b88cbd4d17d48b55f471474567ffad0c parent 20d9481

6 files changed

.agents/commands/search.md+13−0
@@ -0,0 +1,13 @@
1+---
2+description: Search the codebase for a topic using a subagent
3+model: zen/claude-3-5-haiku
4+---
5+
6+Search the codebase for: $ARGUMENTS
7+
8+Use glob, grep, and read tools to explore thoroughly. Report:
9+1. All relevant files and locations found
10+2. Key code snippets with file paths and line numbers
11+3. A short summary of what you found
12+
13+Be exhaustive but concise. No edits — read only.
TODO.md+3−1
@@ -70,4 +70,6 @@ Custom commands:
7070
7171 https://opencode.ai/docs/commands/ I want to copy this approach to custom commands.
7272
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.
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+6−2
@@ -188,6 +188,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
188188 const runSubagent = async (
189189 prompt: string,
190190 depth = 0,
191+ model?: string,
191192 ): Promise<import("../tools/subagent.ts").SubagentOutput> => {
192193 const subMessages: CoreMessage[] = [{ role: "user", content: prompt }];
193194 const subTools = buildToolSet({
@@ -197,7 +198,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
197198 onHook: renderHook,
198199 });
199200
200- const subLlm = resolveModel(currentModel);
201+ const subLlm = resolveModel(model ?? currentModel);
201202
202203 const systemPrompt = buildSystemPrompt(cwd);
203204
@@ -307,7 +308,10 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
307308 planMode = v;
308309 },
309310 cwd,
310- runSubagent: (prompt) => runSubagent(prompt),
311+ // depth=0: custom commands are user-initiated, not LLM-initiated, so they
312+ // don't consume the recursion depth guard (which only applies to the LLM
313+ // subagent tool calling itself).
314+ runSubagent: (prompt, model?) => runSubagent(prompt, 0, model),
311315
312316 undoLastTurn: async () => {
313317 // Nothing to undo if there are no messages
src/cli/commands.ts+69−3
@@ -8,6 +8,11 @@ import {
88 listMcpServers,
99 upsertMcpServer,
1010 } from "../session/db.ts";
11+import {
12+ type CustomCommand,
13+ expandTemplate,
14+ loadCustomCommands,
15+} from "./custom-commands.ts";
1116 import { renderMarkdown } from "./markdown.ts";
1217 import {
1318 PREFIX,
@@ -33,6 +38,7 @@ export interface CommandContext {
3338 connectMcpServer: (name: string) => Promise<void>;
3439 runSubagent: (
3540 prompt: string,
41+ model?: string,
3642 ) => Promise<import("../tools/subagent.ts").SubagentOutput>;
3743
3844 cwd: string;
@@ -335,7 +341,47 @@ function handleNew(ctx: CommandContext): void {
335341 );
336342 }
337343
338-function handleHelp(): void {
344+// ─── Custom commands ──────────────────────────────────────────────────────────
345+
346+async function handleCustomCommand(
347+ cmd: CustomCommand,
348+ args: string,
349+ ctx: CommandContext,
350+): Promise<CommandResult> {
351+ const prompt = await expandTemplate(cmd.template, args, ctx.cwd);
352+ const label = c.cyan(cmd.name);
353+ const srcPath =
354+ cmd.source === "local"
355+ ? `.agents/commands/${cmd.name}.md`
356+ : `~/.agents/commands/${cmd.name}.md`;
357+ const src = c.dim(`[${srcPath}]`);
358+ writeln(`${PREFIX.info} ${label} ${src}`);
359+ writeln();
360+
361+ try {
362+ const output = await ctx.runSubagent(prompt, cmd.model);
363+
364+ if (output.activity.length) {
365+ renderSubagentActivity(output.activity, " ", 1);
366+ writeln();
367+ }
368+
369+ write(renderMarkdown(output.result));
370+ writeln();
371+
372+ return {
373+ type: "inject-user-message",
374+ text: `/${cmd.name} output:\n\n${output.result}\n\n<system-message>Summarize the findings above to the user.</system-message>`,
375+ };
376+ } catch (e) {
377+ writeln(`${PREFIX.error} /${cmd.name} failed: ${String(e)}`);
378+ return { type: "handled" };
379+ }
380+}
381+
382+// ─── Help ─────────────────────────────────────────────────────────────────────
383+
384+function handleHelp(custom: Map<string, CustomCommand>): void {
339385 writeln();
340386
341387 const cmds: [string, string][] = [
@@ -357,6 +403,20 @@ function handleHelp(): void {
357403 for (const [cmd, desc] of cmds) {
358404 writeln(` ${c.cyan(cmd.padEnd(26))} ${c.dim(desc)}`);
359405 }
406+
407+ // Show custom commands
408+ if (custom.size > 0) {
409+ writeln();
410+ writeln(c.dim(" custom commands:"));
411+ for (const cmd of custom.values()) {
412+ const tag =
413+ cmd.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
414+ writeln(
415+ ` ${c.green(`/${cmd.name}`.padEnd(26))} ${c.dim(cmd.description)}${tag}`,
416+ );
417+ }
418+ }
419+
360420 writeln();
361421 writeln(
362422 ` ${c.green("@file".padEnd(26))} ${c.dim("inject file contents into prompt (Tab to complete)")}`,
@@ -409,7 +469,7 @@ export async function handleCommand(
409469
410470 case "help":
411471 case "?":
412- handleHelp();
472+ handleHelp(loadCustomCommands(ctx.cwd));
413473 return { type: "handled" };
414474
415475 case "exit":
@@ -417,10 +477,16 @@ export async function handleCommand(
417477 case "q":
418478 return { type: "exit" };
419479
420- default:
480+ default: {
481+ const custom = loadCustomCommands(ctx.cwd);
482+ const cmd = custom.get(command.toLowerCase());
483+ if (cmd) {
484+ return await handleCustomCommand(cmd, args, ctx);
485+ }
421486 writeln(
422487 `${PREFIX.error} unknown: /${command} ${c.dim("— /help for commands")}`,
423488 );
424489 return { type: "unknown", command };
490+ }
425491 }
426492 }
src/cli/custom-commands.test.ts+149−0
@@ -0,0 +1,149 @@
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 { expandTemplate, loadCustomCommands } from "./custom-commands.ts";
6+
7+// ─── parseFrontmatter / loadCustomCommands ────────────────────────────────────
8+
9+describe("loadCustomCommands", () => {
10+ let dir: string;
11+
12+ beforeEach(() => {
13+ dir = mkdtempSync(join(tmpdir(), "mc-cmd-test-"));
14+ });
15+
16+ afterEach(() => {
17+ rmSync(dir, { recursive: true, force: true });
18+ });
19+
20+ function writeCmd(root: string, name: string, content: string): void {
21+ const cmdsDir = join(root, ".agents", "commands");
22+ mkdirSync(cmdsDir, { recursive: true });
23+ writeFileSync(join(cmdsDir, `${name}.md`), content);
24+ }
25+
26+ test("returns empty map when no .agents/commands dir exists", () => {
27+ const result = loadCustomCommands(dir);
28+ expect(result.size).toBe(0);
29+ });
30+
31+ test("loads a command with frontmatter", () => {
32+ writeCmd(
33+ dir,
34+ "hello",
35+ "---\ndescription: Say hello\nmodel: zen/claude-3-5-haiku\n---\n\nHello $ARGUMENTS",
36+ );
37+ const result = loadCustomCommands(dir);
38+ const cmd = result.get("hello");
39+ expect(cmd?.description).toBe("Say hello");
40+ expect(cmd?.model).toBe("zen/claude-3-5-haiku");
41+ expect(cmd?.template).toBe("Hello $ARGUMENTS");
42+ expect(cmd?.source).toBe("local");
43+ });
44+
45+ test("falls back to name as description when frontmatter has none", () => {
46+ writeCmd(dir, "mytool", "Just a plain template");
47+ const result = loadCustomCommands(dir);
48+ expect(result.get("mytool")?.description).toBe("mytool");
49+ });
50+
51+ test("body without frontmatter is used as template verbatim", () => {
52+ writeCmd(dir, "plain", "Do the thing with $1");
53+ expect(loadCustomCommands(dir).get("plain")?.template).toBe(
54+ "Do the thing with $1",
55+ );
56+ });
57+
58+ test("ignores non-.md files", () => {
59+ const cmdsDir = join(dir, ".agents", "commands");
60+ mkdirSync(cmdsDir, { recursive: true });
61+ writeFileSync(join(cmdsDir, "script.sh"), "echo hi");
62+ expect(loadCustomCommands(dir).size).toBe(0);
63+ });
64+
65+ test("local command overrides global with same name", () => {
66+ // Simulate by writing two commands to the local dir and checking only one wins
67+ writeCmd(dir, "search", "---\ndescription: local\n---\nlocal template");
68+ const result = loadCustomCommands(dir);
69+ expect(result.get("search")?.description).toBe("local");
70+ expect(result.get("search")?.source).toBe("local");
71+ });
72+});
73+
74+// ─── expandTemplate ───────────────────────────────────────────────────────────
75+
76+describe("expandTemplate", () => {
77+ test("replaces $ARGUMENTS with the full args string", async () => {
78+ const out = await expandTemplate("Search for $ARGUMENTS", "foo bar", "/");
79+ expect(out).toBe("Search for foo bar");
80+ });
81+
82+ test("replaces positional $1, $2, $3", async () => {
83+ const out = await expandTemplate("$1 $2 $3", "alpha beta gamma", "/");
84+ expect(out).toBe("alpha beta gamma");
85+ });
86+
87+ test("replaces $1 without touching $10+ (no such placeholder)", async () => {
88+ // We only support $1–$9; $10 should not be replaced by $1 + "0"
89+ const out = await expandTemplate("$10", "x", "/");
90+ // $1 → "x", then "0" remains → "x0"
91+ expect(out).toBe("x0");
92+ });
93+
94+ test("missing positional args become empty string", async () => {
95+ const out = await expandTemplate("$1 $2 $3", "only-one", "/");
96+ expect(out).toBe("only-one ");
97+ });
98+
99+ test("quoted tokens are parsed as single args", async () => {
100+ const out = await expandTemplate("$1|$2", '"hello world" second', "/");
101+ expect(out).toBe("hello world|second");
102+ });
103+
104+ test("replaces all occurrences of the same $ARGUMENTS", async () => {
105+ const out = await expandTemplate(
106+ "Arg: $ARGUMENTS and again $ARGUMENTS",
107+ "test",
108+ "/",
109+ );
110+ expect(out).toBe("Arg: test and again test");
111+ });
112+
113+ test("shell interpolation !`cmd` is replaced with command output", async () => {
114+ const out = await expandTemplate("Result: !`echo hello`", "", "/");
115+ expect(out).toBe("Result: hello");
116+ });
117+
118+ test("duplicate !`cmd` occurrences are all replaced", async () => {
119+ const out = await expandTemplate("!`echo hi` and !`echo hi`", "", "/");
120+ expect(out).toBe("hi and hi");
121+ });
122+
123+ test("failed shell command suppresses stderr, keeps stdout", async () => {
124+ // exit 1 with stdout output — stdout kept, stderr discarded
125+ const out = await expandTemplate(
126+ "pre !`echo out; echo err >&2; exit 1` post",
127+ "",
128+ "/",
129+ );
130+ expect(out).toBe("pre out post");
131+ });
132+
133+ test("successful command includes stderr in output", async () => {
134+ const out = await expandTemplate("!`echo err >&2; exit 0`", "", "/");
135+ expect(out).toBe("err");
136+ });
137+
138+ test("timed-out shell command leaves empty string", async () => {
139+ // sleep 60 will be killed by the 10s timeout — use a short sleep and
140+ // mock the timeout by testing that a non-blocking command returns quickly
141+ const out = await expandTemplate("pre !`exit 1` post", "", "/");
142+ expect(out).toBe("pre post");
143+ });
144+
145+ test("no placeholders — template returned unchanged", async () => {
146+ const out = await expandTemplate("plain text", "ignored", "/");
147+ expect(out).toBe("plain text");
148+ });
149+});
src/cli/custom-commands.ts+165−0
@@ -0,0 +1,165 @@
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 CustomCommand {
8+ name: string;
9+ description: string;
10+ /** Override model for this command (optional) */
11+ model?: string;
12+ /** Raw template string (after frontmatter is stripped) */
13+ template: 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 commands from a directory ──────────────────────────────────────────
48+
49+function loadFromDir(
50+ dir: string,
51+ source: "global" | "local",
52+): Map<string, CustomCommand> {
53+ const commands = new Map<string, CustomCommand>();
54+ if (!existsSync(dir)) return commands;
55+
56+ let entries: string[];
57+ try {
58+ entries = readdirSync(dir);
59+ } catch {
60+ return commands;
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+ commands.set(name, {
75+ name,
76+ description: meta.description ?? name,
77+ ...(meta.model ? { model: meta.model } : {}),
78+ template: body,
79+ source,
80+ });
81+ }
82+ return commands;
83+}
84+
85+// ─── Load all custom commands (global + local, local wins) ───────────────────
86+
87+export function loadCustomCommands(cwd: string): Map<string, CustomCommand> {
88+ const globalDir = join(homedir(), ".agents", "commands");
89+ const localDir = join(cwd, ".agents", "commands");
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+}
97+
98+// ─── Template expansion ───────────────────────────────────────────────────────
99+
100+/**
101+ * Expands a command template:
102+ * - `$ARGUMENTS` → full args string
103+ * - `$1`, `$2`, … → positional tokens
104+ * - `!`cmd`` → stdout of running cmd in a shell
105+ */
106+export async function expandTemplate(
107+ template: string,
108+ args: string,
109+ cwd: string,
110+): Promise<string> {
111+ const tokens =
112+ args
113+ .match(/("([^"]*)")|('([^']*)')|(\S+)/g)
114+ ?.map((t) => t.replace(/^["']|["']$/g, "")) ?? [];
115+
116+ // Replace positional $1 … $9
117+ let result = template;
118+ for (let i = 9; i >= 1; i--) {
119+ result = result.replaceAll(`$${i}`, tokens[i - 1] ?? "");
120+ }
121+ // Replace $ARGUMENTS
122+ result = result.replaceAll("$ARGUMENTS", args);
123+
124+ // Replace !`cmd` shell interpolations (10s timeout per command)
125+ const SHELL_RE = /!`([^`]+)`/g;
126+ const shellMatches = [...result.matchAll(SHELL_RE)];
127+ for (const match of shellMatches) {
128+ const cmd = match[1] ?? "";
129+ let output = "";
130+ try {
131+ const signal = AbortSignal.timeout(10_000);
132+ const proc = Bun.spawn(["bash", "-c", cmd], {
133+ cwd,
134+ stdout: "pipe",
135+ stderr: "pipe",
136+ });
137+ // Race the process exit against the timeout signal.
138+ await Promise.race([
139+ proc.exited,
140+ new Promise<void>((_, reject) =>
141+ signal.addEventListener("abort", () => {
142+ proc.kill();
143+ reject(new Error("timeout"));
144+ }),
145+ ),
146+ ]);
147+ const [stdout, stderr] = await Promise.all([
148+ new Response(proc.stdout).text(),
149+ new Response(proc.stderr).text(),
150+ ]);
151+ const exitCode = proc.exitCode ?? 0;
152+ // Only include stderr when the command succeeded — on failure it's
153+ // likely an error message that would confuse the LLM prompt.
154+ output =
155+ exitCode === 0
156+ ? [stdout, stderr].filter(Boolean).join("\n").trim()
157+ : stdout.trim();
158+ } catch {
159+ // Timeout or spawn failure — leave output empty.
160+ }
161+ result = result.replaceAll(match[0], output);
162+ }
163+
164+ return result;
165+}