/** * Agent discovery and configuration */ import * as fs from "node:fs"; import * as path from "node:path"; import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent"; export type AgentScope = "user" | "project" | "both"; export type AgentSource = "user" | "project" | "pi-web"; export interface AgentConfig { name: string; description: string; tools?: string[]; model?: string; thinking?: string; systemPrompt: string; promptMode?: "append" | "replace"; source: AgentSource; filePath: string; id?: string; resources?: { extensions?: string[]; skills?: string[]; prompts?: string[] }; } export interface AgentDiscoveryResult { agents: AgentConfig[]; projectAgentsDir: string | null; } interface PiWebAgentEntry { id: string; name: string; description: string; promptMode: "append" | "replace"; systemPrompt: string; toolNames: string[]; resources?: { extensions?: string[]; skills?: string[]; prompts?: string[] }; defaultModel?: { provider: string; modelId: string }; defaultThinkingLevel?: string; builtIn?: boolean; } interface PiWebAgentsJson { version: number; agents: PiWebAgentEntry[]; } function loadAgentsFromDir(dir: string, source: "user" | "project"): AgentConfig[] { const agents: AgentConfig[] = []; if (!fs.existsSync(dir)) { return agents; } let entries: fs.Dirent[]; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return agents; } for (const entry of entries) { if (!entry.name.endsWith(".md")) continue; if (!entry.isFile() && !entry.isSymbolicLink()) continue; const filePath = path.join(dir, entry.name); let content: string; try { content = fs.readFileSync(filePath, "utf-8"); } catch { continue; } const { frontmatter, body } = parseFrontmatter>(content); if (!frontmatter.name || !frontmatter.description) { continue; } const tools = frontmatter.tools ?.split(",") .map((t: string) => t.trim()) .filter(Boolean); agents.push({ name: frontmatter.name, description: frontmatter.description, tools: tools && tools.length > 0 ? tools : undefined, model: frontmatter.model, thinking: frontmatter.thinking, systemPrompt: body, source, filePath, }); } return agents; } function loadPiWebAgents(agentDir: string): AgentConfig[] { const filePath = path.join(agentDir, "agents.json"); if (!fs.existsSync(filePath)) return []; let data: PiWebAgentsJson; try { data = JSON.parse(fs.readFileSync(filePath, "utf-8")) as PiWebAgentsJson; } catch { return []; } if (!data.agents || !Array.isArray(data.agents)) return []; return data.agents.map((agent): AgentConfig => ({ name: agent.name, description: agent.description, tools: agent.toolNames && agent.toolNames.length > 0 ? agent.toolNames : undefined, model: agent.defaultModel ? `${agent.defaultModel.provider}/${agent.defaultModel.modelId}` : undefined, thinking: agent.defaultThinkingLevel, systemPrompt: agent.systemPrompt, promptMode: agent.promptMode, source: "pi-web", filePath, id: agent.id, resources: agent.resources, })); } function isDirectory(p: string): boolean { try { return fs.statSync(p).isDirectory(); } catch { return false; } } function findNearestProjectAgentsDir(cwd: string): string | null { let currentDir = cwd; while (true) { const candidate = path.join(currentDir, ".pi", "agents"); if (isDirectory(candidate)) return candidate; const parentDir = path.dirname(currentDir); if (parentDir === currentDir) return null; currentDir = parentDir; } } export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryResult { const userDir = path.join(getAgentDir(), "agents"); const projectAgentsDir = findNearestProjectAgentsDir(cwd); const piWebAgents = loadPiWebAgents(getAgentDir()); const userAgents = scope === "project" ? [] : loadAgentsFromDir(userDir, "user"); const projectAgents = scope === "user" || !projectAgentsDir ? [] : loadAgentsFromDir(projectAgentsDir, "project"); const agentMap = new Map(); // pi-web agents act as global defaults; local markdown agents override them. for (const agent of piWebAgents) agentMap.set(agent.name, agent); if (scope === "both" || scope === "user") { for (const agent of userAgents) agentMap.set(agent.name, agent); } if (scope === "both" || scope === "project") { for (const agent of projectAgents) agentMap.set(agent.name, agent); } return { agents: Array.from(agentMap.values()), projectAgentsDir }; } export function formatAgentList(agents: AgentConfig[], maxItems: number): { text: string; remaining: number } { if (agents.length === 0) return { text: "none", remaining: 0 }; const listed = agents.slice(0, maxItems); const remaining = agents.length - listed.length; return { text: listed.map((a) => `${a.name} (${a.source}): ${a.description}`).join("; "), remaining, }; } export function agentDisplayName(agent: AgentConfig): string { return agent.id ? `${agent.name} [id: ${agent.id}] (${agent.source})` : `${agent.name} (${agent.source})`; } export function formatAvailableAgents(agents: AgentConfig[]): string { return agents.length > 0 ? agents.map(agentDisplayName).join(", ") : "none"; } function optionalAgentFields(agent: AgentConfig): string { const parts: string[] = []; if (agent.id) parts.push(`id: ${agent.id}`); if (agent.model) parts.push(`model: ${agent.model}`); if (agent.thinking) parts.push(`thinking: ${agent.thinking}`); if (agent.tools?.length) parts.push(`tools: ${agent.tools.join(", ")}`); return parts.length > 0 ? ` [${parts.join("; ")}]` : ""; } export function formatAgentCatalog(agents: AgentConfig[]): string { if (agents.length === 0) return "No subagents are configured."; return agents .map((agent) => `- name: ${agent.name}\n description: ${agent.description || "(no description)"}\n source: ${agent.source}${optionalAgentFields(agent)}`) .join("\n"); } export function resolveAgent(agents: AgentConfig[], requested: string | undefined): AgentConfig | undefined { const raw = requested?.trim(); if (!raw) return undefined; const normalized = raw.toLowerCase(); const exact = agents.find((agent) => agent.name === raw || agent.id === raw); if (exact) return exact; const caseInsensitive = agents.find((agent) => agent.name.toLowerCase() === normalized || agent.id?.toLowerCase() === normalized); if (caseInsensitive) return caseInsensitive; return undefined; }