xonecas.io
64875
Mc

mini-coder / commit 8634a95

fix: @agent UX — delegate via subagent tool instead of eager dispatch

- Remove Phase 3 agent dispatch from resolveFileRefs; @agent tokens are
  now forwarded as-is to the primary agent
- Add agentName param to subagent tool schema so the LLM can target a
  custom agent by name
- buildToolSet passes availableAgents to createSubagentTool; the tool
  description lists available agents and instructs the LLM to use
  agentName when the user addresses a message with @<agent-name>
- runSubagent resolves agent config (model + system prompt) from agentName;
  modelOverride kept for /review and custom command use
- loadAgents called once per runSubagent invocation (was up to 3x)
- resolveFileRefs no longer loads agents at all — unknown @refs fall
  through to the file-inject path unchanged
- Drop redundant ternary in systemPrompt assignment (x ? x : y → x ?? y)

Sean2026-02-25 8634a95d4cdcd0f0269ee4f97995bf1cbc74e745 parent 21179eb

5 files changed

AGENTS.md+1−0
@@ -8,3 +8,4 @@
88 - Use `bun run typecheck && bun run format && bun run lint && bun test` to check your changes.
99 - We care about performance.
1010 - Don't worry about formatting issues, formatting happens automatically on mutations. (see .agents/hooks)
11+- Do not inline `import` calls.
TODO.md+14−0
@@ -1,5 +1,19 @@
11 # TODO
22
3+## Refencing custom subagents with `@` has poor UX
4+
5+- The main agent has no clue a subagent was called.
6+- When the subagent completes, the main agents just gets the result with
7+no context or relation to the user message that triggered it.
8+- This is poorly implemented and does not match how Claude Code or Opencode's custom agents work, leading to breaking on of the core premises of mini-coder: no weird setup or different standards...
9+
10+Write a plan to implement the feature properly, use opencode as the reference
11+implementation to ensure we are compatible with their custom agents.
12+
13+## Subagents don't have access to MCP tools?
14+
15+Investigate if subagents are able to see the mcp tools.
16+
317 ## Investigate missing output?
418
519 ```
src/agent/agent.ts+29−91
@@ -186,24 +186,37 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
186186 // so we can trim or rebuild without mutating the in-memory DB copy.
187187 const coreHistory: CoreMessage[] = [...session.messages];
188188
189- // Subagent runner (recursive) — depth prevents infinite recursion
189+ // Subagent runner (recursive) — depth prevents infinite recursion.
190+ // agentName: optional custom agent to run (looks up .agents/agents/<name>.md).
191+ // modelOverride: explicit model to use (for /review and custom commands).
190192 const runSubagent = async (
191193 prompt: string,
192194 depth = 0,
193- model?: string,
194- systemPromptOverride?: string,
195+ agentName?: string,
196+ modelOverride?: string,
195197 ): Promise<import("../tools/subagent.ts").SubagentOutput> => {
198+ // Resolve custom agent config if an agentName was specified
199+ const allAgents = loadAgents(cwd);
200+ const agentConfig = agentName ? allAgents.get(agentName) : undefined;
201+ if (agentName && !agentConfig) {
202+ throw new Error(
203+ `Unknown agent "${agentName}". Available agents: ${[...allAgents.keys()].join(", ") || "(none)"}`,
204+ );
205+ }
206+
207+ const model = modelOverride ?? agentConfig?.model ?? currentModel;
208+ const systemPrompt = agentConfig?.systemPrompt ?? buildSystemPrompt(cwd);
209+
196210 const subMessages: CoreMessage[] = [{ role: "user", content: prompt }];
197211 const subTools = buildToolSet({
198212 cwd,
199213 depth,
200214 runSubagent,
201215 onHook: renderHook,
216+ availableAgents: allAgents,
202217 });
203218
204- const subLlm = resolveModel(model ?? currentModel);
205-
206- const systemPrompt = systemPromptOverride ?? buildSystemPrompt(cwd);
219+ const subLlm = resolveModel(model);
207220
208221 let result = "";
209222 let inputTokens = 0;
@@ -250,11 +263,14 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
250263 };
251264
252265 // ── MCP: load persisted servers and connect them ───────────────────────────
266+
267+ const agents = loadAgents(cwd);
253268 const tools: ToolDef[] = buildToolSet({
254269 cwd,
255270 depth: 0,
256271 runSubagent,
257272 onHook: renderHook,
273+ availableAgents: agents,
258274 });
259275
260276 const mcpTools: ToolDef[] = [];
@@ -314,7 +330,8 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
314330 // depth=0: custom commands are user-initiated, not LLM-initiated, so they
315331 // don't consume the recursion depth guard (which only applies to the LLM
316332 // subagent tool calling itself).
317- runSubagent: (prompt, model?) => runSubagent(prompt, 0, model),
333+ // model? is an optional override for /review and custom commands.
334+ runSubagent: (prompt, model?) => runSubagent(prompt, 0, undefined, model),
318335
319336 undoLastTurn: async () => {
320337 // Nothing to undo if there are no messages
@@ -491,40 +508,10 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
491508 };
492509 process.on("SIGINT", onSigInt);
493510
494- // Resolve @file/skill/agent references
511+ // Resolve @file/skill references (agent refs are left as-is for the LLM)
495512 const { text: resolvedText, images: refImages } = await resolveFileRefs(
496513 text,
497514 cwd,
498- 0, // depth 0: processUserInput is always top-level
499- runSubagent,
500- async (prompt, model, systemPromptOverride) => {
501- // Run custom agent with full visual output (spinner + renderTurn)
502- const agentLlm = resolveModel(model ?? currentModel);
503- const agentSystem = systemPromptOverride ?? buildSystemPrompt(cwd);
504- const agentTools = buildToolSet({
505- cwd,
506- depth: 0,
507- runSubagent,
508- onHook: renderHook,
509- });
510- const agentMessages: CoreMessage[] = [
511- { role: "user", content: prompt },
512- ];
513- const events = runTurn({
514- model: agentLlm,
515- messages: agentMessages,
516- tools: agentTools,
517- systemPrompt: agentSystem,
518- });
519- spinner.start("thinking");
520- const { newMessages, inputTokens, outputTokens } = await renderTurn(
521- events,
522- spinner,
523- );
524- const result = extractAssistantText(newMessages);
525- const activity: import("../tools/subagent.ts").SubagentToolEntry[] = [];
526- return { result, inputTokens, outputTokens, activity };
527- },
528515 );
529516
530517 // Merge pasted images with @-ref images
@@ -709,51 +696,26 @@ export function hasRalphSignal(text: string): boolean {
709696 return /\/ralph\b/.test(text);
710697 }
711698
712-// ─── Resolve @file/skill/agent references in user input ───────────────────────
699+// ─── Resolve @file/skill references in user input ────────────────────────────
700+// @agent references are left as-is — unrecognised @refs simply fall through to
701+// the file-inject path and are left unchanged when the file doesn't exist.
713702
714703 async function resolveFileRefs(
715704 text: string,
716705 cwd: string,
717- depth: number,
718- runSubagentFn: (
719- prompt: string,
720- depth: number,
721- model?: string,
722- systemPromptOverride?: string,
723- ) => Promise<import("../tools/subagent.ts").SubagentOutput>,
724- runAgentFn: (
725- prompt: string,
726- model?: string,
727- systemPromptOverride?: string,
728- ) => Promise<import("../tools/subagent.ts").SubagentOutput>,
729706 ): Promise<{ text: string; images: ImageAttachment[] }> {
730707 const atPattern = /@([\w./\-_]+)/g;
731708 let result = text;
732709 const matches = [...text.matchAll(atPattern)];
733710 const images: ImageAttachment[] = [];
734711
735- // Load agents and skills once for this resolution pass
736- const agents = loadAgents(cwd);
737712 const skills = loadSkills(cwd);
738713
739- // ── Phase 1: validate — catch multiple @agent refs up front ───────────────
740- const agentMatches = matches.filter((m) => m[1] && agents.has(m[1]));
741- if (agentMatches.length > 1) {
742- throw new Error(
743- `Only one @agent reference is allowed per message, found: ${agentMatches.map((m) => m[0]).join(", ")}`,
744- );
745- }
746-
747- // ── Phase 2: substitute skills, images, and files (right-to-left) ─────────
748- // Process all non-agent refs first so images are collected and the prompt
749- // text that the agent receives is clean.
714+ // Substitute skills, images, and files (right-to-left).
750715 for (const match of [...matches].reverse()) {
751716 const ref = match[1];
752717 if (!ref) continue;
753718
754- // Skip agent refs — handled in phase 3
755- if (agents.has(ref)) continue;
756-
757719 // @skill-name — inject skill content inline
758720 const skill = skills.get(ref);
759721 if (skill) {
@@ -797,29 +759,5 @@ async function resolveFileRefs(
797759 }
798760 }
799761
800- // ── Phase 3: agent dispatch (if any) ──────────────────────────────────────
801- // By now skills/images/files have been resolved, so `result` contains the
802- // clean prompt text. We use the original match index against `text` to strip
803- // just the @agent-name token and pass everything else to the subagent.
804- const agentMatch = agentMatches[0];
805- if (agentMatch) {
806- const ref = agentMatch[1];
807- const agent = ref ? agents.get(ref) : undefined;
808- if (!agent) return { text: result, images };
809- // Strip the @agent-name token from the *original* text to get the prompt,
810- // then layer in any skill expansions from `result`.
811- const promptText = (
812- result.slice(0, agentMatch.index) +
813- result.slice((agentMatch.index ?? 0) + agentMatch[0].length)
814- ).trim();
815- const output = await runAgentFn(
816- promptText || "(no prompt)",
817- agent.model,
818- agent.systemPrompt,
819- );
820- // Images collected above are passed through so callers can attach them.
821- return { text: output.result, images };
822- }
823-
824762 return { text: result, images };
825763 }
src/agent/tools.ts+5−3
@@ -100,9 +100,11 @@ export function buildToolSet(opts: {
100100 runSubagent: (
101101 prompt: string,
102102 depth?: number,
103+ agentName?: string,
103104 ) => Promise<import("../tools/subagent.ts").SubagentOutput>;
104105
105106 onHook: (toolName: string, scriptPath: string, success: boolean) => void;
107+ availableAgents: ReadonlyMap<string, { description: string }>;
106108 }): ToolDef[] {
107109 const { cwd, onHook } = opts;
108110 const depth = opts.depth ?? 0;
@@ -182,15 +184,15 @@ export function buildToolSet(opts: {
182184 (result, input) => hookEnvForShell(result, input, cwd),
183185 onHook,
184186 ) as ToolDef,
185- createSubagentTool(async (prompt) => {
187+ createSubagentTool(async (prompt, agentName) => {
186188 if (depth >= MAX_SUBAGENT_DEPTH) {
187189 throw new Error(
188190 `Subagent depth limit reached (max ${MAX_SUBAGENT_DEPTH}). ` +
189191 `Cannot spawn another subagent from depth ${depth}.`,
190192 );
191193 }
192- return opts.runSubagent(prompt, depth + 1);
193- }) as ToolDef,
194+ return opts.runSubagent(prompt, depth + 1, agentName);
195+ }, opts.availableAgents) as ToolDef,
194196 ];
195197 }
196198
src/tools/subagent.ts+14−6
@@ -3,6 +3,12 @@ import type { ToolDef } from "../llm-api/types.ts";
33
44 const SubagentInput = z.object({
55 prompt: z.string().describe("The task or question to give the subagent"),
6+ agentName: z
7+ .string()
8+ .optional()
9+ .describe(
10+ "Name of a custom agent to use (from .agents/agents/). Omit to use a generic subagent.",
11+ ),
612 });
713
814 type SubagentInput = z.infer<typeof SubagentInput>;
@@ -28,17 +34,19 @@ export interface SubagentOutput {
2834 * the agent without creating a circular import.
2935 */
3036 export function createSubagentTool(
31- runSubagent: (prompt: string) => Promise<SubagentOutput>,
37+ runSubagent: (prompt: string, agentName?: string) => Promise<SubagentOutput>,
38+ availableAgents: ReadonlyMap<string, { description: string }>,
3239 ): ToolDef<SubagentInput, SubagentOutput> {
40+ const agentSection =
41+ availableAgents.size > 0
42+ ? `\n\nWhen the user's message contains @<agent-name>, delegate to that agent by setting agentName to the exact agent name. Available custom agents: ${[...availableAgents.entries()].map(([name, cfg]) => `"${name}" (${cfg.description})`).join(", ")}.`
43+ : "";
3344 return {
3445 name: "subagent",
35- description:
36- "Spawn a sub-agent to handle a focused subtask. " +
37- "Use this for parallel exploration, specialised analysis, or tasks that benefit from " +
38- "a fresh context window. The subagent has access to all the same tools.",
46+ description: `Spawn a sub-agent to handle a focused subtask. Use this for parallel exploration, specialised analysis, or tasks that benefit from a fresh context window. The subagent has access to all the same tools.${agentSection}`,
3947 schema: SubagentInput,
4048 execute: async (input) => {
41- return runSubagent(input.prompt);
49+ return runSubagent(input.prompt, input.agentName);
4250 },
4351 };
4452 }