🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
🔧 Fix Agent Type System: Dynamic Loading from .claude/agents/ (Implements PR #485)
rUva1bcc7884698
diff --git a/package-lock.json b/package-lock.jsonindex 8bb717bcb6..81a0f6936d 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,24 +1,22 @@{"name": "claude-flow",- "version": "2.0.0-alpha.63",+ "version": "2.0.0-alpha.78","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "claude-flow",- "version": "2.0.0-alpha.63",+ "version": "2.0.0-alpha.78","hasInstallScript": true,"license": "MIT","dependencies": {"@modelcontextprotocol/sdk": "^1.0.4","@types/better-sqlite3": "^7.6.13",- "better-sqlite3": "^12.2.0","blessed": "^0.1.81","chalk": "^4.1.2","cli-table3": "^0.6.3","commander": "^11.1.0","cors": "^2.8.5",- "diskusage": "^1.1.3","express": "^4.18.2","figlet": "^1.8.1","fs-extra": "^11.2.0",@@ -27,14 +25,14 @@"helmet": "^7.1.0","inquirer": "^9.2.12","nanoid": "^5.0.4",- "node-pty": "^1.0.0","ora": "^7.0.1","p-queue": "^8.1.0","ruv-swarm": "^1.0.14",- "ws": "^8.18.3"+ "ws": "^8.18.3",+ "yaml": "^2.8.0"},"bin": {- "claude-flow": "bin/claude-flow"+ "claude-flow": "bin/claude-flow.js"},"devDependencies": {"@babel/core": "^7.28.0",@@ -70,6 +68,11 @@"engines": {"node": ">=20.0.0","npm": ">=9.0.0"+ },+ "optionalDependencies": {+ "better-sqlite3": "^12.2.0",+ "diskusage": "^1.1.3",+ "node-pty": "^1.0.0"}},"../../ruv-swarm/npm": {@@ -5694,6 +5697,7 @@"integrity": "sha512-2u3OG3xuf5MFyzc4MctNRUKjjwK+UkovRYdD2ed/NZNZPrt0lqHnLKxGhlFVvAb4/oufIgQG3nWgwmeTbHOvXA==","hasInstallScript": true,"license": "MIT",+ "optional": true,"dependencies": {"es6-promise": "^4.2.8","nan": "^2.18.0"@@ -5996,7 +6000,8 @@"version": "4.2.8","resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz","integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==",- "license": "MIT"+ "license": "MIT",+ "optional": true},"node_modules/esbuild": {"version": "0.25.5",@@ -9403,7 +9408,8 @@"version": "2.22.2","resolved": "https://registry.npmjs.org/nan/-/nan-2.22.2.tgz","integrity": "sha512-DANghxFkS1plDdRsX0X9pm0Z6SJNN6gBdtXfanwoZ8hooC5gosGFSBGRYHUVPz1asKA/kMRqDRdHrluZ61SpBQ==",- "license": "MIT"+ "license": "MIT",+ "optional": true},"node_modules/nanoid": {"version": "5.1.5",@@ -9480,6 +9486,7 @@"integrity": "sha512-wtBMWWS7dFZm/VgqElrTvtfMq4GzJ6+edFI0Y0zyzygUSZMgZdraDUMUhCIvkjhJjme15qWmbyJbtAx4ot4uZA==","hasInstallScript": true,"license": "MIT",+ "optional": true,"dependencies": {"nan": "^2.17.0"}@@ -12799,6 +12806,18 @@"dev": true,"license": "ISC"},+ "node_modules/yaml": {+ "version": "2.8.0",+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.0.tgz",+ "integrity": "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ==",+ "license": "ISC",+ "bin": {+ "yaml": "bin.mjs"+ },+ "engines": {+ "node": ">= 14.6"+ }+ },"node_modules/yargs": {"version": "17.7.2","resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",diff --git a/package.json b/package.jsonindex f1723eda66..16e7c75926 100644--- a/package.json+++ b/package.json@@ -122,7 +122,8 @@"ora": "^7.0.1","p-queue": "^8.1.0","ruv-swarm": "^1.0.14",- "ws": "^8.18.3"+ "ws": "^8.18.3",+ "yaml": "^2.8.0"},"optionalDependencies": {"better-sqlite3": "^12.2.0",diff --git a/src/agents/agent-loader.ts b/src/agents/agent-loader.tsnew file mode 100644index 0000000000..17da087acc--- /dev/null+++ b/src/agents/agent-loader.ts@@ -0,0 +1,247 @@+/**+ * Dynamic Agent Loader - Reads agent definitions from .claude/agents/ directory+ * This is the single source of truth for all agent types in the system+ */++import { readFileSync, existsSync } from 'node:fs';+import { glob } from 'glob';+import { resolve, dirname } from 'node:path';+import { parse as parseYaml } from 'yaml';++export interface AgentDefinition {+ name: string;+ type?: string;+ color?: string;+ description: string;+ capabilities?: string[];+ priority?: 'low' | 'medium' | 'high' | 'critical';+ hooks?: {+ pre?: string;+ post?: string;+ };+ content?: string; // The markdown content after frontmatter+}++export interface AgentCategory {+ name: string;+ agents: AgentDefinition[];+}++class AgentLoader {+ private agentCache: Map<string, AgentDefinition> = new Map();+ private categoriesCache: AgentCategory[] = [];+ private lastLoadTime = 0;+ private cacheExpiry = 60000; // 1 minute cache++ /**+ * Get the .claude/agents directory path+ */+ private getAgentsDirectory(): string {+ // Start from current working directory and walk up to find .claude/agents+ let currentDir = process.cwd();++ while (currentDir !== '/') {+ const claudeAgentsPath = resolve(currentDir, '.claude', 'agents');+ if (existsSync(claudeAgentsPath)) {+ return claudeAgentsPath;+ }+ currentDir = dirname(currentDir);+ }++ // Fallback to relative path+ return resolve(process.cwd(), '.claude', 'agents');+ }++ /**+ * Parse agent definition from markdown file+ */+ private parseAgentFile(filePath: string): AgentDefinition | null {+ try {+ const content = readFileSync(filePath, 'utf-8');++ // Split frontmatter and content+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);+ if (!frontmatterMatch) {+ console.warn(`No frontmatter found in ${filePath}`);+ return null;+ }++ const [, yamlContent, markdownContent] = frontmatterMatch;+ const frontmatter = parseYaml(yamlContent);++ if (!frontmatter.name || !frontmatter.metadata?.description) {+ console.warn(`Missing required fields (name, metadata.description) in ${filePath}`);+ return null;+ }++ return {+ name: frontmatter.name,+ type: frontmatter.type,+ color: frontmatter.color,+ description: frontmatter.metadata.description,+ capabilities: frontmatter.metadata.capabilities || frontmatter.capabilities || [],+ priority: frontmatter.priority || 'medium',+ hooks: frontmatter.hooks,+ content: markdownContent.trim(),+ };+ } catch (error) {+ console.error(`Error parsing agent file ${filePath}:`, error);+ return null;+ }+ }++ /**+ * Load all agent definitions from .claude/agents directory+ */+ private async loadAgents(): Promise<void> {+ const agentsDir = this.getAgentsDirectory();++ if (!existsSync(agentsDir)) {+ console.warn(`Agents directory not found: ${agentsDir}`);+ return;+ }++ // Find all .md files in the agents directory+ const agentFiles = await glob('**/*.md', {+ cwd: agentsDir,+ ignore: ['**/README.md', '**/MIGRATION_SUMMARY.md'],+ absolute: true,+ });++ // Clear cache+ this.agentCache.clear();+ this.categoriesCache = [];++ // Track categories+ const categoryMap = new Map<string, AgentDefinition[]>();++ // Parse each agent file+ for (const filePath of agentFiles) {+ const agent = this.parseAgentFile(filePath);+ if (agent) {+ this.agentCache.set(agent.name, agent);++ // Determine category from file path+ const relativePath = filePath.replace(agentsDir, '');+ const pathParts = relativePath.split('/');+ const category = pathParts[1] || 'uncategorized'; // First directory after agents/++ if (!categoryMap.has(category)) {+ categoryMap.set(category, []);+ }+ categoryMap.get(category)!.push(agent);+ }+ }++ // Build categories array+ this.categoriesCache = Array.from(categoryMap.entries()).map(([name, agents]) => ({+ name,+ agents: agents.sort((a, b) => a.name.localeCompare(b.name)),+ }));++ this.lastLoadTime = Date.now();+ }++ /**+ * Check if cache needs refresh+ */+ private needsRefresh(): boolean {+ return Date.now() - this.lastLoadTime > this.cacheExpiry;+ }++ /**+ * Ensure agents are loaded and cache is fresh+ */+ private async ensureLoaded(): Promise<void> {+ if (this.agentCache.size === 0 || this.needsRefresh()) {+ await this.loadAgents();+ }+ }++ /**+ * Get all available agent types+ */+ async getAvailableAgentTypes(): Promise<string[]> {+ await this.ensureLoaded();+ return Array.from(this.agentCache.keys()).sort();+ }++ /**+ * Get agent definition by name+ */+ async getAgent(name: string): Promise<AgentDefinition | null> {+ await this.ensureLoaded();+ return this.agentCache.get(name) || null;+ }++ /**+ * Get all agent definitions+ */+ async getAllAgents(): Promise<AgentDefinition[]> {+ await this.ensureLoaded();+ return Array.from(this.agentCache.values()).sort((a, b) => a.name.localeCompare(b.name));+ }++ /**+ * Get agents organized by category+ */+ async getAgentCategories(): Promise<AgentCategory[]> {+ await this.ensureLoaded();+ return this.categoriesCache;+ }++ /**+ * Search agents by capabilities, description, or name+ */+ async searchAgents(query: string): Promise<AgentDefinition[]> {+ await this.ensureLoaded();+ const lowerQuery = query.toLowerCase();++ return Array.from(this.agentCache.values()).filter(agent => {+ return (+ agent.name.toLowerCase().includes(lowerQuery) ||+ agent.description.toLowerCase().includes(lowerQuery) ||+ agent.capabilities?.some(cap => cap.toLowerCase().includes(lowerQuery)) ||+ false+ );+ });+ }++ /**+ * Check if an agent type is valid+ */+ async isValidAgentType(name: string): Promise<boolean> {+ await this.ensureLoaded();+ return this.agentCache.has(name);+ }++ /**+ * Get agents by category name+ */+ async getAgentsByCategory(category: string): Promise<AgentDefinition[]> {+ const categories = await this.getAgentCategories();+ const found = categories.find(cat => cat.name === category);+ return found?.agents || [];+ }++ /**+ * Force refresh the agent cache+ */+ async refresh(): Promise<void> {+ this.lastLoadTime = 0; // Force reload+ await this.loadAgents();+ }+}++// Singleton instance+export const agentLoader = new AgentLoader();++// Convenience functions+export const getAvailableAgentTypes = () => agentLoader.getAvailableAgentTypes();+export const getAgent = (name: string) => agentLoader.getAgent(name);+export const getAllAgents = () => agentLoader.getAllAgents();+export const getAgentCategories = () => agentLoader.getAgentCategories();+export const searchAgents = (query: string) => agentLoader.searchAgents(query);+export const isValidAgentType = (name: string) => agentLoader.isValidAgentType(name);+export const getAgentsByCategory = (category: string) => agentLoader.getAgentsByCategory(category);+export const refreshAgents = () => agentLoader.refresh();\ No newline at end of filediff --git a/src/constants/agent-types.ts b/src/constants/agent-types.tsindex 408632acd8..c325f25924 100644--- a/src/constants/agent-types.ts+++ b/src/constants/agent-types.ts@@ -1,37 +1,56 @@/**- * Central source of truth for agent types- * This file ensures consistency across TypeScript types and runtime validation+ * Agent Types - Dynamic loading from .claude/agents/ directory+ * This file provides type-safe access to dynamically loaded agent definitions*/-export const AGENT_TYPES = {- COORDINATOR: 'coordinator',- RESEARCHER: 'researcher',- CODER: 'coder',- ANALYST: 'analyst',- ARCHITECT: 'architect',- TESTER: 'tester',- REVIEWER: 'reviewer',- OPTIMIZER: 'optimizer',- DOCUMENTER: 'documenter',- MONITOR: 'monitor',- SPECIALIST: 'specialist',+import { getAvailableAgentTypes, isValidAgentType as validateAgentType } from '../agents/agent-loader.js';++// Dynamic agent type - will be a string that matches available agents+export type AgentType = string;++// Legacy agent type mapping for backward compatibility+export const LEGACY_AGENT_MAPPING = {+ analyst: 'code-analyzer',+ coordinator: 'task-orchestrator',+ optimizer: 'perf-analyzer',+ documenter: 'api-docs',+ monitor: 'performance-benchmarker',+ specialist: 'system-architect',+ architect: 'system-architect',} as const;-export type AgentType = (typeof AGENT_TYPES)[keyof typeof AGENT_TYPES];+/**+ * Get all valid agent types dynamically+ */+export async function getValidAgentTypes(): Promise<string[]> {+ return await getAvailableAgentTypes();+}-// Array of all valid agent types for runtime validation-export const VALID_AGENT_TYPES = Object.values(AGENT_TYPES);+/**+ * Helper function to validate agent type+ */+export async function isValidAgentType(type: string): Promise<boolean> {+ return await validateAgentType(type);+}-// JSON Schema for agent type validation-export const AGENT_TYPE_SCHEMA = {- type: 'string',- enum: VALID_AGENT_TYPES,- description: 'Type of AI agent',-};+/**+ * Resolve legacy agent types to current equivalents+ */+export function resolveLegacyAgentType(legacyType: string): string {+ const mapped = LEGACY_AGENT_MAPPING[legacyType as keyof typeof LEGACY_AGENT_MAPPING];+ return mapped || legacyType;+}-// Helper function to validate agent type-export function isValidAgentType(type: string): type is AgentType {- return VALID_AGENT_TYPES.includes(type as AgentType);+/**+ * Create JSON Schema for agent type validation (async)+ */+export async function getAgentTypeSchema() {+ const validTypes = await getValidAgentTypes();+ return {+ type: 'string',+ enum: validTypes,+ description: 'Type of specialized AI agent',+ };}// Strategy typesdiff --git a/src/mcp/claude-flow-tools.ts b/src/mcp/claude-flow-tools.tsindex cffa85e379..6655999f68 100644--- a/src/mcp/claude-flow-tools.ts+++ b/src/mcp/claude-flow-tools.ts@@ -4,17 +4,49 @@import type { MCPTool, MCPContext, AgentProfile, Task, MemoryEntry } from '../utils/types.js';import type { ILogger } from '../core/logger.js';+import { getAvailableAgentTypes, getAgentTypeSchema } from '../constants/agent-types.js';import type { Permissions } from './auth.js';export interface ClaudeFlowToolContext extends MCPContext {orchestrator?: any; // Reference to orchestrator instance}+/**+ * Enhance tool schema with dynamic agent types+ */+async function enhanceToolWithAgentTypes(tool: MCPTool): Promise<MCPTool> {+ const availableTypes = await getAvailableAgentTypes();++ // Clone the tool to avoid modifying the original+ const enhancedTool = JSON.parse(JSON.stringify(tool));++ // Find and populate enum fields for agent types+ function addEnumToAgentTypeFields(obj: any) {+ if (typeof obj !== 'object' || obj === null) return;++ for (const [key, value] of Object.entries(obj)) {+ if (typeof value === 'object' && value !== null) {+ // Check if this is an agent type field+ if (key === 'type' || key === 'filterByType' || key === 'assignToAgentType') {+ const field = value as any;+ if (field.type === 'string' && field.description?.includes('loaded dynamically from .claude/agents/')) {+ field.enum = availableTypes;+ }+ }+ addEnumToAgentTypeFields(value);+ }+ }+ }++ addEnumToAgentTypeFields(enhancedTool.inputSchema);+ return enhancedTool;+}+/*** Create all Claude-Flow specific MCP tools*/-export function createClaudeFlowTools(logger: ILogger): MCPTool[] {- return [+export async function createClaudeFlowTools(logger: ILogger): Promise<MCPTool[]> {+ const tools = [// Agent management toolscreateSpawnAgentTool(logger),createListAgentsTool(logger),@@ -55,6 +87,13 @@ export function createClaudeFlowTools(logger: ILogger): MCPTool[] {createListTerminalsTool(logger),createCreateTerminalTool(logger),];++ // Enhance tools with dynamic agent types+ const enhancedTools = await Promise.all(+ tools.map(tool => enhanceToolWithAgentTypes(tool))+ );++ return enhancedTools;}function createSpawnAgentTool(logger: ILogger): MCPTool {@@ -66,20 +105,8 @@ function createSpawnAgentTool(logger: ILogger): MCPTool {properties: {type: {type: 'string',- enum: [- 'coordinator',- 'researcher',- 'coder',- 'analyst',- 'architect',- 'tester',- 'reviewer',- 'optimizer',- 'documenter',- 'monitor',- 'specialist',- ],- description: 'Type of agent to spawn',+ // Note: enum will be populated dynamically at runtime+ description: 'Type of specialized agent to spawn (loaded dynamically from .claude/agents/)',},name: {type: 'string',@@ -161,20 +188,8 @@ function createListAgentsTool(logger: ILogger): MCPTool {},filterByType: {type: 'string',- enum: [- 'coordinator',- 'researcher',- 'coder',- 'analyst',- 'architect',- 'tester',- 'reviewer',- 'optimizer',- 'documenter',- 'monitor',- 'specialist',- ],- description: 'Filter agents by type',+ // Note: enum will be populated dynamically at runtime+ description: 'Filter agents by type (loaded dynamically from .claude/agents/)',},},},@@ -317,20 +332,8 @@ function createCreateTaskTool(logger: ILogger): MCPTool {},assignToAgentType: {type: 'string',- enum: [- 'coordinator',- 'researcher',- 'coder',- 'analyst',- 'architect',- 'tester',- 'reviewer',- 'optimizer',- 'documenter',- 'monitor',- 'specialist',- ],- description: 'Type of agent to assign the task to',+ // Note: enum will be populated dynamically at runtime+ description: 'Type of specialized agent to assign the task to (loaded dynamically from .claude/agents/)',},input: {type: 'object',