@@ -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 }