xonecas.io
64875
Mc

mini-coder / commit 0fa4292

refactor: remove subagent experimentation

xonecas2026-03-18 0fa4292de1207c74a39dab1902f16182965be501 parent 80aaec5

39 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

README.md+1−2
@@ -53,11 +53,10 @@ Use `/login` inside the REPL to authenticate via browser-based OAuth (currently
5353 - **Multi-provider** — auto-discovers Anthropic, OpenAI, Gemini, Ollama, or any OpenAI-compatible endpoint
5454 - **Session memory** — SQLite-backed. Resume with `-c` or `-r <id>`
5555 - **Shell integration** — `!` prefix for inline commands, `@` to reference files with tab completion
56-- **Subagents** — spawn parallel mini-coder instances for independent subtasks
5756 - **Web search** — `webSearch` + `webContent` tools when `EXA_API_KEY` is set
5857 - **MCP support** — connect external tool servers over HTTP or stdio
5958 - **Custom commands** — drop `.md` files in `.agents/commands/` → instant `/slash` commands
60-- **Custom agents** — `.agents/agents/*.md` for specialized personas, usable as primary or via subagent
59+- **Custom agents** — `.agents/agents/*.md` for specialized personas you can activate with `/agent`
6160 - **Skills** — `.agents/skills/<name>/SKILL.md`, inject with `@name`
6261 - **`mc-edit`** — safe, exact-text file editing (no full-file rewrites)
6362 - **16 ANSI colors** — inherits your terminal theme. Always looks right.
SHARE.md+0−1
@@ -11,7 +11,6 @@ mc
1111 - **Multi-provider** — Anthropic, OpenAI, Google, Ollama, auto-detected from env vars
1212 - **Session memory** — local SQLite, resume with `mc -c`
1313 - **Shell integration** — `!command` inline, `@file` references with tab completion
14-- **Subagents** — spawns parallel agents for independent subtasks
1514 - **Built-in web search** — enable Exa-backed `webSearch`/`webContent` with `EXA_API_KEY`
1615 - **MCP support** — connect external tools and servers
1716 - **Shell-first editing** — inspect with shell, make targeted edits with `mc-edit`, verify with shell
TODO.md+3−2
@@ -1,9 +1,10 @@
11 # TODO
22
3+- Reaching max tool calls causes a 400 error
4+- CTRL+d hangs sometimes and doesn't exit
5+
36 ## Deferred fixes
47
5-- Investigate using tmux to allow agents to use mc from a users perspective
6-- Subagent and shell tools are very similar, shell could do what subagent does without changes. This could be leveraged to reduce code. Subagent process runner is used for custom commands that fork context as well, there will need to be refactored.
78 - `/_debug` hidden command that snapshots recent logs/db and creates a report in the cwd. For dev mostly but available to all. Do not list it anywhere, only documented here and in the code itself.
89
910 ---
docs/mini-coder.1.md+4−19
@@ -86,7 +86,7 @@ Developer-focused CLI coding agent. Prioritizes dev flow — no slow startup, no
8686 : Remove MCP server.
8787
8888 `/agent` \[*name*\]
89-: Set or clear active primary agent.
89+: Set or clear active agent.
9090
9191 `/review`
9292 : Review changes (custom command, auto-created globally).
@@ -119,9 +119,6 @@ Developer-focused CLI coding agent. Prioritizes dev flow — no slow startup, no
119119 **shell**
120120 : Execute bash commands; repo inspection and `mc-edit` edits happen here.
121121
122-**subagent**
123-: Spawn a focused mini-agent for parallel subtasks.
124-
125122 **listSkills**
126123 : List discovered skills (metadata only).
127124
@@ -165,16 +162,7 @@ Drop a `.md` file in `.agents/commands/` (local) or `~/.agents/commands/` (globa
165162 : Shown in `/help`.
166163
167164 `model`
168-: Override model (only with `context: fork`).
169-
170-`context`
171-: `fork` to run as isolated subagent; default is inline.
172-
173-`subtask`
174-: `true` forces subagent (OpenCode-compatible alias).
175-
176-`agent`
177-: Run under named agent's system prompt (only with `context: fork`).
165+: Optional metadata field.
178166
179167 **Argument substitution:**
180168
@@ -198,12 +186,9 @@ Drop a `.md` file in `.agents/agents/` (local) or `~/.agents/agents/` (global).
198186 : Shown in `/help`.
199187
200188 `model`
201-: Override active model.
202-
203-`mode`
204-: `primary` excludes from subagent tool; `subagent`/`all`/omitted keeps it available.
189+: Optional metadata field.
205190
206-Body is the agent system prompt. Non-primary agents are exposed to the **subagent** tool for delegation.
191+Body is the agent system prompt.
207192
208193 ## SKILLS
209194
mini-coder-idea.md+3−4
@@ -32,11 +32,10 @@ conventions and not introduce more specs. (`.agents` / `AGENTS.md`, while also s
3232 - Elegantly handles hitting max context size for the model. Also handles max tool calls, gracefully finishing the turn with an update from the agent
3333 - Support prompt caching via the used sdks.
3434 - Feature parity with community configs like custom agents, skill and commands.
35-- Shell-first tool surface for LLMs: `shell`, `subagent`, `listSkills`, and `readSkill`, plus connected MCP tools. Keep the core surface small and easy to use so it actually reduces friction for the LLMs.
35+- Shell-first tool surface for LLMs: `shell`, `listSkills`, and `readSkill`, plus connected MCP tools and optional web tools when configured. Keep the core surface small and easy to use so it actually reduces friction for the LLMs.
3636 - File work should follow a simple flow: inspect with shell, mutate with `mc-edit`, verify with shell.
3737 - `mc-edit` should stay narrow and reliable: exact-text edits only, deterministic failures on stale or ambiguous state, diff and machine-friendly output while staying human readable.
3838 - Optional `webSearch` and `webContent` tools when `EXA_API_KEY` is set.
39-- `subagent` tool spawns a fresh `mc` subprocess in one shot mode.
4039 - Commands in CLI prompt:
4140 - `/model` (alias `/models`) command allows the user to pick a model from connected providers. As well as thinking effort for the model if supported. Selection persists accross sessions.
4241 - `/undo` removes the last turn from conversation history, it does not restore filesystem state.
@@ -45,7 +44,7 @@ conventions and not introduce more specs. (`.agents` / `AGENTS.md`, while also s
4544 - `/context` configures context pruning and tool-result caps.
4645 - `/cache` toggles prompt caching globally; sub-commands configure provider-specific caching (`/cache openai <in_memory|24h>`, `/cache gemini <off|cachedContents/...>`).
4746 - `/review` reviews recent changes via a global custom command installed at app start (`~/.agents/commands/review.md`), and can be customized or shadowed locally.
48- - `/agent` sets or clears the active primary agent.
47+ - `/agent` sets or clears the active agent.
4948 - `/mcp` list/add/remove mcp servers. servers are stored in sqlite
5049 - `/login` shows OAuth login status. `/login <provider>` starts browser-based OAuth login. `/logout <provider>` clears saved tokens. Currently supports Anthropic.
5150 - `/new` starts a new session with clean context. Clean UI and fresh session display
@@ -81,6 +80,6 @@ Core modules:
8180 - `llm-api`: Provides the api to intereact with the provider and process the full conversation turn + tool calling.
8281 - `cli`: Output/UI, with logical separated subfolder: user input/output and ui/etc..
8382 - `agent`: Main agent implementation
84-- `tools`: shell, subagent, skill, and web/search helpers
83+- `tools`: shell, skill, and web/search helpers
8584 - `session`: sqlite-backed sessions, settings, model info, and MCP server storage
8685 - `mcp`: handles connecting to mcp servers
scripts/ui-oneshot.ts+3−42
@@ -176,7 +176,7 @@ async function main() {
176176 );
177177
178178 // ── Parallel mixed tools ───────────────────────────────
179- separator("8. Parallel mixed tools (shell + subagent + readSkill)");
179+ separator("8. Parallel mixed tools (shell + readSkill)");
180180 await renderTurn(
181181 eventsFrom([
182182 {
@@ -185,12 +185,6 @@ async function main() {
185185 toolCallId: "m1",
186186 args: { command: "wc -l src/**/*.ts" },
187187 },
188- {
189- type: "tool-call-start",
190- toolName: "subagent",
191- toolCallId: "m2",
192- args: { prompt: "Review the error handling patterns in src/", agentName: "reviewer" },
193- },
194188 {
195189 type: "tool-call-start",
196190 toolName: "readSkill",
@@ -206,13 +200,6 @@ async function main() {
206200 stdout: " 142 src/index.ts\n 87 src/utils.ts\n 45 src/config.ts\n 274 total",
207201 }),
208202 },
209- {
210- type: "tool-result",
211- toolName: "subagent",
212- toolCallId: "m2",
213- isError: false,
214- result: { inputTokens: 2500, outputTokens: 800, agentName: "reviewer" },
215- },
216203 {
217204 type: "tool-result",
218205 toolName: "readSkill",
@@ -329,34 +316,8 @@ async function main() {
329316 writeln("");
330317 renderError("Connection timed out after 60s");
331318
332- // ── MCP tool ───────────────────────────────────────────
333- separator("13. MCP tool call");
334- await renderTurn(
335- eventsFrom([
336- {
337- type: "tool-call-start",
338- toolName: "mcp_github_create_issue",
339- toolCallId: "mcp1",
340- args: { repo: "my-org/my-repo", title: "Fix validation bug", body: "..." },
341- },
342- {
343- type: "tool-result",
344- toolName: "mcp_github_create_issue",
345- toolCallId: "mcp1",
346- isError: false,
347- result: { url: "https://github.com/my-org/my-repo/issues/42" },
348- },
349- {
350- type: "text-delta",
351- delta: "Created issue #42 for tracking the validation bug.",
352- },
353- done(),
354- ]),
355- new Spinner(),
356- );
357-
358319 // ── Full realistic session ─────────────────────────────
359- separator("14. Realistic multi-turn snippet");
320+ separator("13. Realistic multi-turn snippet");
360321 renderUserMessage("Fix the type error in src/config.ts");
361322 writeln("");
362323 await renderTurn(
@@ -444,7 +405,7 @@ async function main() {
444405 );
445406
446407 // ── Web search ──────────────────────────────────────────
447- separator("15. Web search results");
408+ separator("14. Web search results");
448409 await renderTurn(
449410 eventsFrom([
450411 {
src/agent/agent.ts+4−31
@@ -1,5 +1,5 @@
11 import * as c from "yoctocolors";
2-import { type AgentConfig, loadAgents } from "../cli/agents.ts";
2+import { loadAgents } from "../cli/agents.ts";
33 import type { CommandContext } from "../cli/types.ts";
44 import type { ThinkingEffort } from "../llm-api/providers.ts";
55 import type { ContextPruningMode } from "../llm-api/turn.ts";
@@ -21,7 +21,6 @@ import {
2121 } from "../session/db/index.ts";
2222 import type { AgentReporter } from "./reporter.ts";
2323 import { SessionRunner } from "./session-runner.ts";
24-import { createSubagentRunner } from "./subagent-runner.ts";
2524 import { buildToolSet } from "./tools.ts";
2625
2726 interface AgentOptions {
@@ -37,38 +36,17 @@ interface AgentOptions {
3736 initialGoogleCachedContent: string | null;
3837 sessionId?: string;
3938 reporter: AgentReporter;
40- headless?: boolean;
4139 agentSystemPrompt?: string;
4240 }
4341
44-/** Agents with mode "primary" are for interactive use only — exclude from subagent tool. */
45-function subagentAgents(
46- agents: Map<string, AgentConfig>,
47-): Map<string, AgentConfig> {
48- const filtered = new Map<string, AgentConfig>();
49- for (const [name, cfg] of agents) {
50- if (cfg.mode !== "primary") filtered.set(name, cfg);
51- }
52- return filtered;
53-}
54-
5542 export async function initAgent(opts: AgentOptions): Promise<{
5643 runner: SessionRunner;
5744 cmdCtx: CommandContext;
5845 }> {
5946 const cwd = opts.cwd;
60- let currentModel = opts.model;
6147
62- const { runSubagent, killAll } = createSubagentRunner(
63- cwd,
64- () => currentModel,
65- );
6648 const agents = loadAgents(cwd);
67- const tools: ToolDef[] = buildToolSet({
68- cwd,
69- runSubagent,
70- availableAgents: subagentAgents(agents),
71- });
49+ const tools: ToolDef[] = buildToolSet({ cwd });
7250
7351 const mcpTools: ToolDef[] = [];
7452
@@ -103,7 +81,7 @@ export async function initAgent(opts: AgentOptions): Promise<{
10381 reporter: opts.reporter,
10482 tools,
10583 mcpTools,
106- initialModel: currentModel,
84+ initialModel: opts.model,
10785 initialThinkingEffort: opts.initialThinkingEffort,
10886 initialShowReasoning: opts.initialShowReasoning,
10987 initialVerboseOutput: opts.initialVerboseOutput,
@@ -114,11 +92,9 @@ export async function initAgent(opts: AgentOptions): Promise<{
11492 initialGoogleCachedContent: opts.initialGoogleCachedContent,
11593 sessionId: opts.sessionId,
11694 extraSystemPrompt: opts.agentSystemPrompt,
117- isSubagent: opts.headless,
118- killSubprocesses: killAll,
11995 });
12096
121- // Active primary agent state — name only; the system prompt is stored on runner.
97+ // Active agent state — name only; the system prompt is stored on runner.
12298 let activeAgentName: string | null = getPreferredActiveAgent();
12399 if (opts.agentSystemPrompt) {
124100 activeAgentName = null;
@@ -140,7 +116,6 @@ export async function initAgent(opts: AgentOptions): Promise<{
140116 runner.currentModel = m;
141117 runner.session.model = m;
142118 setPreferredModel(m);
143- currentModel = m; // Update local reference for runSubagent
144119 },
145120 get thinkingEffort() {
146121 return runner.currentThinkingEffort;
@@ -199,8 +174,6 @@ export async function initAgent(opts: AgentOptions): Promise<{
199174 setPreferredGoogleCachedContent(contentId);
200175 },
201176 cwd,
202- runSubagent: (prompt, agentName?, model?, abortSignal?) =>
203- runSubagent(prompt, agentName, model, abortSignal),
204177
205178 get activeAgent() {
206179 return activeAgentName;
src/agent/session-runner.ts+0−14
@@ -38,8 +38,6 @@ interface SessionRunnerOptions {
3838 initialGoogleCachedContent: string | null;
3939 sessionId?: string | undefined;
4040 extraSystemPrompt?: string | undefined;
41- isSubagent?: boolean | undefined;
42- killSubprocesses?: (() => void) | undefined;
4341 }
4442
4543 interface RunnerStatusInfo {
@@ -78,8 +76,6 @@ export class SessionRunner {
7876 private lastContextTokens = 0;
7977 private _extraSystemPrompt: string | undefined;
8078 private _systemPrompt: string | undefined;
81- private isSubagent: boolean | undefined;
82- private killSubprocesses: (() => void) | undefined;
8379
8480 constructor(opts: SessionRunnerOptions) {
8581 this.cwd = opts.cwd;
@@ -95,8 +91,6 @@ export class SessionRunner {
9591 this.promptCachingEnabled = opts.initialPromptCachingEnabled;
9692 this.openaiPromptCacheRetention = opts.initialOpenAIPromptCacheRetention;
9793 this.googleCachedContent = opts.initialGoogleCachedContent;
98- this.isSubagent = opts.isSubagent;
99- this.killSubprocesses = opts.killSubprocesses;
10094 this.extraSystemPrompt = opts.extraSystemPrompt;
10195 this.initSession(opts.sessionId);
10296 }
@@ -182,13 +176,6 @@ export class SessionRunner {
182176 const abortController = new AbortController();
183177 const stopWatcher = watchForCancel(abortController);
184178
185- if (this.killSubprocesses) {
186- const killSubs = this.killSubprocesses;
187- abortController.signal.addEventListener("abort", () => {
188- killSubs();
189- });
190- }
191-
192179 const thisTurn = this.turnIndex++;
193180 const userMsg: CoreMessage =
194181 pastedImages.length > 0
@@ -288,7 +275,6 @@ export class SessionRunner {
288275 this.sessionTimeAnchor,
289276 this.cwd,
290277 this._extraSystemPrompt,
291- this.isSubagent,
292278 );
293279 }
294280 }
src/agent/subagent-runner.test.ts+0−103
@@ -1,103 +0,0 @@
1-import { describe, expect, test } from "bun:test";
2-import {
3- parseSubagentOutput,
4- resolveMcCommand,
5- tailTextFromChunks,
6-} from "./subagent-runner.ts";
7-
8-describe("tailTextFromChunks", () => {
9- test("keeps only the byte tail without buffering everything", () => {
10- const encode = (text: string) => new TextEncoder().encode(text);
11- expect(tailTextFromChunks([encode("abc"), encode("def")], 4)).toBe("cdef");
12- expect(tailTextFromChunks([encode("hello"), encode(" world")], 64)).toBe(
13- "hello world",
14- );
15- expect(tailTextFromChunks([encode("hello")], 0)).toBe("");
16- });
17-
18- test("respects utf-8 boundaries across chunk rotations", () => {
19- const encoder = new TextEncoder();
20- const emoji = encoder.encode("🙂");
21- const prefix = encoder.encode("xx");
22- const suffix = encoder.encode("yy");
23- expect(tailTextFromChunks([prefix, emoji, suffix], emoji.length + 2)).toBe(
24- "🙂yy",
25- );
26- });
27-});
28-
29-describe("resolveMcCommand", () => {
30- test("uses Bun.main for TypeScript entrypoints", () => {
31- expect(
32- resolveMcCommand("/usr/bin/bun", "/repo/src/index.ts", undefined),
33- ).toEqual(["/usr/bin/bun", "/repo/src/index.ts"]);
34- });
35-
36- test("uses Bun.main for installed JavaScript entrypoints", () => {
37- expect(
38- resolveMcCommand("/usr/bin/bun", "/repo/dist/mc.js", undefined),
39- ).toEqual(["/usr/bin/bun", "/repo/dist/mc.js"]);
40- });
41-
42- test("falls back to argv[1] when Bun.main is eval", () => {
43- expect(
44- resolveMcCommand("/usr/bin/bun", "/repo/[eval]", "/repo/src/index.ts"),
45- ).toEqual(["/usr/bin/bun", "/repo/src/index.ts"]);
46- });
47-
48- test("returns bare execPath when no script entrypoint exists", () => {
49- expect(resolveMcCommand("/repo/mc", undefined, "--help")).toEqual([
50- "/repo/mc",
51- ]);
52- });
53-});
54-
55-describe("parseSubagentOutput", () => {
56- test("returns error string for empty output", () => {
57- const result = parseSubagentOutput("", 0);
58- expect(typeof result).toBe("string");
59- expect(result).toContain("no output");
60- });
61-
62- test("returns error string for non-JSON output", () => {
63- const result = parseSubagentOutput("not json", 0);
64- expect(typeof result).toBe("string");
65- expect(result).toContain("non-JSON");
66- });
67-
68- test("returns error string when parsed JSON has error field", () => {
69- const result = parseSubagentOutput(
70- JSON.stringify({
71- error: "something broke",
72- result: "",
73- inputTokens: 0,
74- outputTokens: 0,
75- }),
76- 0,
77- );
78- expect(typeof result).toBe("string");
79- expect(result).toContain("something broke");
80- });
81-
82- test("returns error string for non-zero exit code", () => {
83- const result = parseSubagentOutput(
84- JSON.stringify({ result: "ok", inputTokens: 10, outputTokens: 5 }),
85- 1,
86- );
87- expect(typeof result).toBe("string");
88- expect(result).toContain("exit");
89- });
90-
91- test("returns parsed summary on success", () => {
92- const result = parseSubagentOutput(
93- JSON.stringify({ result: "done", inputTokens: 100, outputTokens: 50 }),
94- 0,
95- );
96- expect(typeof result).toBe("object");
97- expect(result).toEqual({
98- result: "done",
99- inputTokens: 100,
100- outputTokens: 50,
101- });
102- });
103-});
src/agent/subagent-runner.ts+0−292
@@ -1,292 +0,0 @@
1-import { resolveProcessScriptPath } from "../internal/runtime/script.ts";
2-import type { SubagentOutput, SubagentSummary } from "../tools/subagent.ts";
3-
4-/**
5- * Resolve the command to invoke a new `mc` subprocess.
6- * - Dev / installed JS: Bun runs a script entrypoint → [bun, script]
7- * - Compiled binary: no script entrypoint is available → [process.execPath]
8- */
9-export function resolveMcCommand(
10- execPath: string,
11- mainModule: string | undefined,
12- argv1: string | undefined,
13-): string[] {
14- const script = resolveProcessScriptPath(mainModule, argv1);
15- if (script) {
16- return [execPath, script];
17- }
18- return [execPath];
19-}
20-
21-function getMcCommand(): string[] {
22- return resolveMcCommand(process.execPath, Bun.main, process.argv[1]);
23-}
24-
25-// Loose recursion cap passed via environment so subprocess chains are bounded
26-// without an in-process depth parameter. Generous enough for real use-cases.
27-const MAX_SUBAGENT_DEPTH = 10;
28-
29-class TailByteBuffer {
30- private readonly ring: Uint8Array;
31- private writePos = 0;
32- private totalSeen = 0;
33-
34- constructor(private readonly maxBytes: number) {
35- this.ring = new Uint8Array(Math.max(0, maxBytes));
36- }
37-
38- push(chunk: Uint8Array): void {
39- if (this.maxBytes <= 0 || chunk.length === 0) return;
40-
41- let offset = 0;
42- while (offset < chunk.length) {
43- const remaining = chunk.length - offset;
44- const writable = Math.min(this.maxBytes - this.writePos, remaining);
45- this.ring.set(chunk.subarray(offset, offset + writable), this.writePos);
46- this.writePos = (this.writePos + writable) % this.maxBytes;
47- offset += writable;
48- this.totalSeen += writable;
49- }
50- }
51-
52- toUint8Array(): Uint8Array {
53- if (this.maxBytes <= 0) return new Uint8Array(0);
54- const kept = Math.min(this.totalSeen, this.maxBytes);
55- if (kept === 0) return new Uint8Array(0);
56- if (this.totalSeen <= this.maxBytes) return this.ring.subarray(0, kept);
57-
58- const out = new Uint8Array(kept);
59- const tailBytes = this.ring.subarray(this.writePos);
60- out.set(tailBytes, 0);
61- out.set(this.ring.subarray(0, this.writePos), tailBytes.length);
62- return out;
63- }
64-}
65-
66-function tailBytesFromChunks(
67- chunks: readonly Uint8Array[],
68- maxBytes: number,
69-): Uint8Array {
70- const buffer = new TailByteBuffer(maxBytes);
71- for (const chunk of chunks) {
72- buffer.push(chunk);
73- }
74- return buffer.toUint8Array();
75-}
76-
77-export function tailTextFromChunks(
78- chunks: readonly Uint8Array[],
79- maxBytes: number,
80-): string {
81- return new TextDecoder().decode(tailBytesFromChunks(chunks, maxBytes));
82-}
83-
84-async function drainTail(
85- stream: ReadableStream | null,
86- maxBytes = 8192,
87-): Promise<string> {
88- if (!stream) return "";
89- const reader = stream.getReader();
90- const buffer = new TailByteBuffer(maxBytes);
91-
92- try {
93- while (true) {
94- const { done, value } = await reader.read();
95- if (done) break;
96- if (value) {
97- buffer.push(value as Uint8Array);
98- }
99- }
100- } finally {
101- reader.releaseLock();
102- }
103-
104- return new TextDecoder().decode(buffer.toUint8Array());
105-}
106-
107-function formatSubagentDiagnostics(stdout: string, stderr: string): string {
108- const lines = [...stderr.split("\n"), ...stdout.split("\n")]
109- .map((line) => line.trim())
110- .filter(Boolean);
111- if (lines.length === 0) return "";
112- const tail = lines.slice(-6).join(" | ");
113- return ` (diagnostics: ${tail.slice(0, 300)})`;
114-}
115-
116-async function resolveDiagnostics(opts: {
117- stdoutTail: Promise<string>;
118- stderrTail: Promise<string>;
119-}): Promise<string> {
120- const [stdout, stderr] = await Promise.all([
121- opts.stdoutTail,
122- opts.stderrTail,
123- ]);
124- return formatSubagentDiagnostics(stdout, stderr);
125-}
126-
127-/**
128- * Parse the structured output from a subagent subprocess.
129- * Returns the parsed summary on success, or an error message string on failure.
130- */
131-export function parseSubagentOutput(
132- rawText: string,
133- exitCode: number | null,
134-): SubagentSummary | string {
135- const trimmed = rawText.trim();
136- if (!trimmed) {
137- return `Subagent subprocess produced no output (exit code ${String(exitCode)})`;
138- }
139-
140- let parsed: SubagentSummary & { error?: string };
141- try {
142- parsed = JSON.parse(trimmed) as SubagentSummary & { error?: string };
143- } catch {
144- return `Subagent subprocess wrote non-JSON output (exit code ${String(exitCode)}): ${trimmed.slice(0, 200)}`;
145- }
146-
147- if (parsed.error) {
148- return `Subagent failed: ${parsed.error}`;
149- }
150- if (exitCode !== 0) {
151- return `Subagent process exited with code ${String(exitCode)}`;
152- }
153-
154- return parsed;
155-}
156-
157-export function createSubagentRunner(
158- cwd: string,
159- getCurrentModel: () => string,
160-) {
161- // Active subprocesses for interrupt cleanup.
162- const activeProcs = new Set<ReturnType<typeof Bun.spawn>>();
163-
164- // Depth is injected by the parent subprocess via MC_SUBAGENT_DEPTH env var.
165- const subagentDepth = Number.parseInt(
166- process.env.MC_SUBAGENT_DEPTH ?? "0",
167- 10,
168- );
169-
170- const runSubagent = async (
171- prompt: string,
172- agentName?: string,
173- modelOverride?: string,
174- abortSignal?: AbortSignal,
175- ): Promise<SubagentOutput> => {
176- if (subagentDepth >= MAX_SUBAGENT_DEPTH) {
177- throw new Error(
178- `Subagent recursion limit reached (depth ${subagentDepth}). ` +
179- `Cannot spawn another subagent.`,
180- );
181- }
182-
183- if (abortSignal?.aborted) {
184- throw new DOMException(
185- "Subagent execution was interrupted",
186- "AbortError",
187- );
188- }
189-
190- const model = modelOverride ?? getCurrentModel();
191- const cmd = [
192- ...getMcCommand(),
193- "--subagent",
194- "--cwd",
195- cwd,
196- "--model",
197- model,
198- "--output-fd",
199- "3",
200- ...(agentName ? ["--agent", agentName] : []),
201- prompt,
202- ];
203-
204- const proc = Bun.spawn({
205- cmd,
206- env: {
207- ...process.env,
208- MC_SUBAGENT_DEPTH: String(subagentDepth + 1),
209- },
210- // Keep subagent stdout/stderr isolated so transient tool errors or warnings
211- // don't leak into the parent UI. We only surface these streams on failure.
212- stdio: ["ignore", "pipe", "pipe", "pipe"],
213- });
214-
215- activeProcs.add(proc);
216-
217- let aborted = false;
218- const onAbort = () => {
219- aborted = true;
220- try {
221- proc.kill("SIGTERM");
222- } catch {
223- /* process may have already exited */
224- }
225- };
226-
227- if (abortSignal) {
228- abortSignal.addEventListener("abort", onAbort);
229- }
230-
231- const stdoutTail = drainTail(proc.stdout).catch(() => "");
232- const stderrTail = drainTail(proc.stderr).catch(() => "");
233-
234- try {
235- const [text] = await Promise.all([
236- Bun.file(proc.stdio[3] as number).text(),
237- proc.exited,
238- ]);
239-
240- if (aborted || abortSignal?.aborted) {
241- throw new DOMException(
242- "Subagent execution was interrupted",
243- "AbortError",
244- );
245- }
246-
247- const parsed = parseSubagentOutput(text, proc.exitCode);
248- if (typeof parsed === "string") {
249- const diagnostics = await resolveDiagnostics({
250- stdoutTail,
251- stderrTail,
252- });
253- throw new Error(`${parsed}${diagnostics}`);
254- }
255-
256- const output: SubagentOutput = {
257- result: parsed.result,
258- inputTokens: parsed.inputTokens,
259- outputTokens: parsed.outputTokens,
260- };
261- if (agentName) output.agentName = agentName;
262-
263- return output;
264- } catch (error) {
265- if (aborted || abortSignal?.aborted) {
266- throw new DOMException(
267- "Subagent execution was interrupted",
268- "AbortError",
269- );
270- }
271- throw error;
272- } finally {
273- if (abortSignal) {
274- abortSignal.removeEventListener("abort", onAbort);
275- }
276- activeProcs.delete(proc);
277- }
278- };
279-
280- return {
281- runSubagent,
282- killAll: () => {
283- for (const proc of activeProcs) {
284- try {
285- proc.kill("SIGTERM");
286- } catch {
287- // Process may have already exited.
288- }
289- }
290- },
291- };
292-}
src/agent/system-prompt.test.ts+9−81
@@ -48,7 +48,6 @@ describe("buildSystemPrompt", () => {
4848 "mock-time-anchor",
4949 tmpDir,
5050 undefined,
51- undefined,
5251 fakeHome,
5352 );
5453 expect(prompt).toContain("You are mini-coder");
@@ -77,7 +76,6 @@ describe("buildSystemPrompt", () => {
7776 "mock-time-anchor",
7877 tmpDir,
7978 undefined,
80- undefined,
8179 fakeHome,
8280 );
8381 expect(prompt).toContain("# Project context");
@@ -90,62 +88,22 @@ describe("buildSystemPrompt", () => {
9088 "mock-time-anchor",
9189 tmpDir,
9290 undefined,
93- undefined,
9491 fakeHome,
9592 );
9693 const occurrences = prompt.split("# Project context").length - 1;
9794 expect(occurrences).toBe(1);
9895 });
9996
100- it("appends subagent delegation wording in subagent mode", () => {
101- const prompt = buildSystemPrompt(
102- "mock-time-anchor",
103- tmpDir,
104- undefined,
105- true,
106- fakeHome,
107- );
108- expect(prompt).toContain("You are running as a subagent");
109- expect(prompt).toContain(
110- "Do not spawn further subagents unless the subtask is unambiguously separable",
111- );
112- });
113-
114- it("does not append subagent wording in non-subagent mode", () => {
115- const prompt = buildSystemPrompt(
116- "mock",
117- tmpDir,
118- undefined,
119- false,
120- fakeHome,
121- );
122- expect(prompt).not.toContain("You are running as a subagent");
123- });
124-
125- it("appends extraSystemPrompt after context and subagent wording", () => {
97+ it("appends extraSystemPrompt after context", () => {
12698 writeFileSync(join(tmpDir, "AGENTS.md"), "ctx");
127- const prompt = buildSystemPrompt(
128- "mock",
129- tmpDir,
130- "custom extra",
131- true,
132- fakeHome,
133- );
134- const subagentIdx = prompt.indexOf("You are running as a subagent");
99+ const prompt = buildSystemPrompt("mock", tmpDir, "custom extra", fakeHome);
135100 const extraIdx = prompt.indexOf("custom extra");
136101 const contextIdx = prompt.indexOf("ctx");
137- expect(contextIdx).toBeLessThan(subagentIdx);
138- expect(subagentIdx).toBeLessThan(extraIdx);
102+ expect(contextIdx).toBeLessThan(extraIdx);
139103 });
140104
141105 it("includes cwd and current time in prompt", () => {
142- const prompt = buildSystemPrompt(
143- "mock",
144- tmpDir,
145- undefined,
146- undefined,
147- fakeHome,
148- );
106+ const prompt = buildSystemPrompt("mock", tmpDir, undefined, fakeHome);
149107 expect(prompt).toContain("Current working directory:");
150108 expect(prompt).toContain("Current date/time:");
151109 });
@@ -153,13 +111,7 @@ describe("buildSystemPrompt", () => {
153111 it("includes global context when ~/.agents/AGENTS.md present", () => {
154112 mkdirSync(join(fakeHome, ".agents"), { recursive: true });
155113 writeFileSync(join(fakeHome, ".agents", "AGENTS.md"), "global info");
156- const prompt = buildSystemPrompt(
157- "mock",
158- tmpDir,
159- undefined,
160- undefined,
161- fakeHome,
162- );
114+ const prompt = buildSystemPrompt("mock", tmpDir, undefined, fakeHome);
163115 expect(prompt).toContain("# Project context");
164116 expect(prompt).toContain("global info");
165117 });
@@ -168,13 +120,7 @@ describe("buildSystemPrompt", () => {
168120 mkdirSync(join(fakeHome, ".agents"), { recursive: true });
169121 writeFileSync(join(fakeHome, ".agents", "AGENTS.md"), "global info");
170122 writeFileSync(join(tmpDir, "AGENTS.md"), "local info");
171- const prompt = buildSystemPrompt(
172- "mock",
173- tmpDir,
174- undefined,
175- undefined,
176- fakeHome,
177- );
123+ const prompt = buildSystemPrompt("mock", tmpDir, undefined, fakeHome);
178124 expect(prompt).toContain("global info");
179125 expect(prompt).toContain("local info");
180126 expect(prompt.indexOf("global info")).toBeLessThan(
@@ -183,13 +129,7 @@ describe("buildSystemPrompt", () => {
183129 });
184130
185131 it("does not include # Project context when neither global nor local context present", () => {
186- const prompt = buildSystemPrompt(
187- "mock",
188- tmpDir,
189- undefined,
190- undefined,
191- fakeHome,
192- );
132+ const prompt = buildSystemPrompt("mock", tmpDir, undefined, fakeHome);
193133 expect(prompt).not.toContain("# Project context");
194134 });
195135
@@ -201,13 +141,7 @@ describe("buildSystemPrompt", () => {
201141 "---\nname: deploy\ndescription: Deploy safely\n---\n\n# Deploy\nDetailed body",
202142 );
203143
204- const prompt = buildSystemPrompt(
205- "mock",
206- tmpDir,
207- undefined,
208- undefined,
209- fakeHome,
210- );
144+ const prompt = buildSystemPrompt("mock", tmpDir, undefined, fakeHome);
211145 expect(prompt).toContain("# Available skills (metadata only)");
212146 expect(prompt).toContain(
213147 "Use `listSkills` to browse and `readSkill` to load one SKILL.md on demand.",
@@ -224,13 +158,7 @@ describe("buildSystemPrompt", () => {
224158 "---\nname: release\ndescription: Ship releases\n---\n\nRelease body",
225159 );
226160
227- const prompt = buildSystemPrompt(
228- "mock",
229- tmpDir,
230- undefined,
231- undefined,
232- fakeHome,
233- );
161+ const prompt = buildSystemPrompt("mock", tmpDir, undefined, fakeHome);
234162 expect(prompt).toContain("- release: Ship releases (global)");
235163 expect(prompt).not.toContain("Release body");
236164 });
src/agent/system-prompt.ts+1−8
@@ -72,13 +72,10 @@ const FINAL_MESSAGE = `
7272 - If verification was run, report commands and outcomes briefly.
7373 - If verification could not be run, say so clearly.`;
7474
75-const SUBAGENT_DELEGATION = `You are running as a subagent. Complete the task you have been given directly using your tools. Do not spawn further subagents unless the subtask is unambiguously separable and self-contained.`;
76-
7775 export function buildSystemPrompt(
7876 sessionTimeAnchor: string,
7977 cwd: string,
8078 extraSystemPrompt?: string,
81- isSubagent?: boolean,
8279 /** Override home directory — used in tests to isolate global context loading. */
8380 homeDir?: string,
8481 ): string {
@@ -86,7 +83,7 @@ export function buildSystemPrompt(
8683 const localContext = loadLocalContextFile(cwd);
8784 const cwdDisplay = tildePath(cwd);
8885 let prompt = `You are mini-coder, a small and fast CLI coding agent.
89-You have access to shell, subagent, listSkills, readSkill, connected MCP tools, and optional web tools.
86+You have access to shell, listSkills, readSkill, connected MCP tools, and optional web tools.
9087
9188 Current working directory: ${cwdDisplay}
9289 Current date/time: ${sessionTimeAnchor}
@@ -139,10 +136,6 @@ Apply one safe exact-text edit to an existing file.
139136 }
140137 }
141138
142- if (isSubagent) {
143- prompt += `\n\n${SUBAGENT_DELEGATION}`;
144- }
145-
146139 if (extraSystemPrompt) {
147140 prompt += `\n\n${extraSystemPrompt}`;
148141 }
src/agent/tools.test.ts+1−8
@@ -16,19 +16,12 @@ afterEach(() => {
1616 });
1717
1818 describe("tool set registration", () => {
19- test("keeps shell, subagent, and skill tools while removing local file tools", () => {
19+ test("keeps shell and skill tools while removing local file tools", () => {
2020 const names = buildToolSet({
2121 cwd,
22- runSubagent: async () => ({
23- result: "ok",
24- inputTokens: 0,
25- outputTokens: 0,
26- }),
27- availableAgents: new Map(),
2822 }).map((tool) => tool.name);
2923
3024 expect(names).toContain("shell");
31- expect(names).toContain("subagent");
3225 expect(names).toContain("listSkills");
3326 expect(names).toContain("readSkill");
3427 expect(names).not.toContain("read");
src/agent/tools.ts+1−14
@@ -3,7 +3,6 @@ import { webContentTool, webSearchTool } from "../tools/exa.ts";
33 import type { ShellOutput } from "../tools/shell.ts";
44 import { shellTool } from "../tools/shell.ts";
55 import { listSkillsTool, readSkillTool } from "../tools/skills.ts";
6-import { createSubagentTool, type SubagentOutput } from "../tools/subagent.ts";
76
87 /**
98 * Inject a default cwd if not provided by the LLM.
@@ -22,15 +21,7 @@ function withCwdDefault(tool: ToolDef, cwd: string): ToolDef {
2221 };
2322 }
2423
25-export function buildToolSet(opts: {
26- cwd: string;
27- runSubagent: (
28- prompt: string,
29- agentName?: string,
30- modelOverride?: string,
31- ) => Promise<SubagentOutput>;
32- availableAgents: ReadonlyMap<string, { description: string }>;
33-}): ToolDef[] {
24+export function buildToolSet(opts: { cwd: string }): ToolDef[] {
3425 const { cwd } = opts;
3526
3627 const shell = withCwdDefault(shellTool as ToolDef, cwd) as ToolDef<
@@ -42,10 +33,6 @@ export function buildToolSet(opts: {
4233 shell as ToolDef,
4334 withCwdDefault(listSkillsTool as ToolDef, cwd),
4435 withCwdDefault(readSkillTool as ToolDef, cwd),
45- createSubagentTool(
46- (prompt, agentName) => opts.runSubagent(prompt, agentName, undefined),
47- opts.availableAgents,
48- ) as ToolDef,
4936 ];
5037
5138 if (process.env.EXA_API_KEY) {
src/cli/agents.test.ts+0−16
@@ -74,22 +74,6 @@ describe("loadAgents", () => {
7474 expect(agents.get("reviewer")?.source).toBe("local");
7575 });
7676
77- test("loads mode field from frontmatter", () => {
78- writeAgent(
79- dir,
80- "orchestrator",
81- "---\ndescription: Primary orchestrator\nmode: primary\n---\n\nYou are the orchestrator.",
82- );
83- const agent = loadAgents(dir).get("orchestrator");
84- expect(agent?.mode).toBe("primary");
85- expect(agent?.systemPrompt).toBe("You are the orchestrator.");
86- });
Cut short: this commit's diff is over 1000 lines.
src/cli/agents.ts+1−5
Cut short: this commit's diff is over 1000 lines.
src/cli/args.ts+0−17
Cut short: this commit's diff is over 1000 lines.
src/cli/bootstrap.ts+0−1
Cut short: this commit's diff is over 1000 lines.
src/cli/commands-agent.ts+1−2
Cut short: this commit's diff is over 1000 lines.
src/cli/commands-config.test.ts+0−1
Cut short: this commit's diff is over 1000 lines.
src/cli/commands-help.ts+2−3
Cut short: this commit's diff is over 1000 lines.
src/cli/commands.ts+2−41
Cut short: this commit's diff is over 1000 lines.
src/cli/custom-commands.test.ts+0−23
Cut short: this commit's diff is over 1000 lines.
src/cli/custom-commands.ts+1−13
Cut short: this commit's diff is over 1000 lines.
src/cli/frontmatter.test.ts+0−45
Cut short: this commit's diff is over 1000 lines.
src/cli/frontmatter.ts+0−16
Cut short: this commit's diff is over 1000 lines.
src/cli/headless-reporter.ts+0−83
Cut short: this commit's diff is over 1000 lines.
src/cli/input-control.ts+0−12
Cut short: this commit's diff is over 1000 lines.
src/cli/input.test.ts+0−29
Cut short: this commit's diff is over 1000 lines.
src/cli/input.ts+4−19
Cut short: this commit's diff is over 1000 lines.
src/cli/log-paths.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/cli/output.ts+0−1
Cut short: this commit's diff is over 1000 lines.
src/cli/tool-render.test.ts+0−9
Cut short: this commit's diff is over 1000 lines.
src/cli/tool-render.ts+0−10
Cut short: this commit's diff is over 1000 lines.
src/cli/tool-result-renderers.ts+0−18
Cut short: this commit's diff is over 1000 lines.
src/cli/types.ts+0−7
Cut short: this commit's diff is over 1000 lines.
src/cli/ui-audit.test.ts+3−47
Cut short: this commit's diff is over 1000 lines.
src/index.ts+2−77
Cut short: this commit's diff is over 1000 lines.
src/tools/subagent.ts+0−51
Cut short: this commit's diff is over 1000 lines.