components/agents/ — Agent UI Components

UI components for multi-agent workflows and agent management

The agents module provides the complete user interface for creating, viewing, editing, and deleting custom agents. It includes a multi-step creation wizard, property editors (tools, color, model), agent listing with source grouping, AI-powered agent generation, and comprehensive validation.

15
Components
18
Files
~3.2 k
Lines
7
FSM Modes

📚 What is this & why does it exist?

The agents UI module lets you manage your collection of AI sub-agents—specialized helpers that Claude Code can spawn for specific tasks. You can browse existing agents grouped by where they live (user, project, built-in, plugin), create new ones step-by-step or with AI assistance, edit their tools and colors, and delete ones you no longer need. It is the control panel for the multi-agent system.

💡 Real-world analogy

Think of it like an HR department dashboard for a company. You can view employee profiles (agent detail), hire new staff through a structured interview process (creation wizard) or a recruitment agency (AI generation), assign roles and tools to each person (tool selector), give them a color-coded badge (color picker), and terminate their employment (delete). The dashboard groups staff by department (source: user, project, built-in) and prevents you from creating duplicate positions.

Contents

Architecture

flowchart TD
  AM["AgentsMenu\n(State machine root)"] --> AL["AgentsList\n(Browse by source)"]
  AM --> AD["AgentDetail\n(Read-only view)"]
  AM --> AE["AgentEditor\n(Edit tools/color/model)"]
  AM --> CW["CreateAgentWizard\n(Multi-step creation)"]
  AM --> DC["Delete Confirm\n(Confirmation dialog)"]

  AE --> TS["ToolSelector\n(5 tool buckets)"]
  AE --> CP["ColorPicker\n(Agent colors)"]
  AE --> MS["ModelSelector\n(Claude models)"]

  CW --> LS["LocationStep"]
  CW --> MTS["MethodStep"]
  CW --> GS["GenerateStep\n(AI generation)"]
  CW --> TYS["TypeStep"]
  CW --> PS["PromptStep"]
  CW --> DS["DescriptionStep"]
  CW --> CS["ConfirmStep"]

  GS --> GA["generateAgent()\n(Claude API call)"]

Key Classes & Functions

Class / FunctionFilePurpose
AgentsMenuAgentsMenu.tsxRoot state machine orchestrating all agent management modes
AgentsListAgentsList.tsxSelectable list of agents grouped by source with override warnings
AgentDetailAgentDetail.tsxRead-only view of agent config: description, tools, memory, model, color
AgentEditorAgentEditor.tsxMenu-driven editing of agent tools, color, and model properties
CreateAgentWizardnew-agent-creation/CreateAgentWizard.tsx11-step wizard for creating new agents (manual or AI-generated)
ToolSelectorToolSelector.tsxInteractive tool picker organizing tools into 5 buckets (Read, Edit, Exec, MCP, Other)
ColorPickerColorPicker.tsxArrow-key color selection with real-time @agentName preview
ModelSelectorModelSelector.tsxClaude model selection with descriptions of reasoning/speed tradeoffs
generateAgentgenerateAgent.tsAI-powered agent generation using Claude with specialized system prompt
validateAgentvalidateAgent.tsValidates agent type (3-50 chars, alphanumeric), description, tools, and prompt
formatAgentAsMarkdownagentFileUtils.tsSerializes agent definition to YAML-in-markdown file format
saveAgentToFileagentFileUtils.tsWrites agent markdown file to the correct source directory
ModeStatetypes.tsDiscriminated union FSM: main-menu | list-agents | view-agent | edit-agent | create-agent | delete-confirm
AgentNavigationFooterAgentNavigationFooter.tsxFooter displaying ↑↓/Enter/Esc navigation hints and Ctrl+D exit

Data Structures

TypeNameDescription
unionModeState7-variant discriminated union driving the agent management state machine
typeAgentDefinitionCore agent config: agentType, whenToUse, systemPrompt, tools, color, model, memory, source
typeAgentValidationResult{ isValid: boolean, errors: string[], warnings: string[] }
typeToolBuckets5 named buckets: READ_ONLY, EDIT, EXECUTION, MCP, OTHER — each with toolNames Set
typeGeneratedAgentAI-generated result: { identifier, whenToUse, systemPrompt }
constAGENT_PATHS{ FOLDER_NAME: '.claude', AGENTS_DIR: 'agents' }

Interactions

DirectionPartnerInterfaceDescription
→AgentToolloadAgentsDir()Loads agent definitions from .claude/agents/ directories
→agentColorManagergetAgentColor()Resolves color names to theme colors for display
→agentToolUtilsresolveAgentTools()Resolves tool names to tool instances for the agent
→SettingsupdateSettingsForSource()Persists agent files to user/project/local directories
→Anthropic APIgenerateAgent()Calls Claude to generate agent configuration from user description
→promptEditoreditFileInEditor()Opens agent markdown file in the user's default editor

State Machine

stateDiagram-v2
  [*] --> main_menu
  main_menu --> list_agents: Select source
  list_agents --> agent_menu: Select agent
  list_agents --> create_agent: Create new
  agent_menu --> view_agent: View details
  agent_menu --> edit_agent: Edit agent
  agent_menu --> delete_confirm: Delete agent
  view_agent --> agent_menu: Back
  edit_agent --> agent_menu: Save/Cancel
  delete_confirm --> list_agents: Confirmed
  delete_confirm --> agent_menu: Cancelled
  create_agent --> list_agents: Completed

Configuration

Knob / ParameterDefaultDescription
AGENT_PATHS.FOLDER_NAME.claudeDirectory name where agent files are stored
AGENT_PATHS.AGENTS_DIRagentsSubdirectory within .claude for agent markdown files
agentType length3-50 charsAllowed identifier length (alphanumeric + hyphens)
description min10 charsMinimum whenToUse description length (warning)
systemPrompt min20 charsMinimum system prompt length (error below this)
systemPrompt warn10,000 charsWarning threshold for overly long system prompts
AGENT_COLORS8 colorsNamed color palette for agent badges (plus 'automatic')

Directory Map

Source tree for agents
components/agents/
├── AgentsMenu.tsx              ← State machine root: mode dispatch and coordination
├── AgentsList.tsx              ← Browsable list grouped by source (user/project/built-in)
├── AgentDetail.tsx             ← Read-only agent profile view
├── AgentEditor.tsx             ← Edit agent tools, color, model via sub-menus
├── AgentNavigationFooter.tsx   ← Navigation hint footer (↑↓ Enter Esc)
├── ColorPicker.tsx             ← Interactive color selector with preview
├── ModelSelector.tsx           ← Claude model dropdown with descriptions
├── ToolSelector.tsx            ← 5-bucket tool picker (Read/Edit/Exec/MCP/Other)
├── types.ts                    ← ModeState union, AGENT_PATHS, validation types
├── utils.ts                    ← Display name helpers for agent sources
├── validateAgent.ts            ← Agent definition validation (type, prompt, tools)
├── agentFileUtils.ts           ← File I/O: save, update, delete, format as markdown
├── generateAgent.ts            ← AI-powered agent generation via Claude API
└── new-agent-creation/
    ├── CreateAgentWizard.tsx    ← 11-step wizard orchestrator
    └── wizard-steps/
        ├── TypeStep.tsx         ← Agent identifier input with validation
        ├── LocationStep.tsx     ← Source selection (user/project/local)
        ├── MethodStep.tsx       ← Manual vs AI-generated creation choice
        ├── GenerateStep.tsx     ← AI generation loading and result handling
        ├── PromptStep.tsx       ← System prompt editor
        ├── DescriptionStep.tsx  ← When-to-use description editor
        ├── ToolsStep.tsx        ← Tool selection via ToolSelector
        ├── ModelStep.tsx        ← Model selection via ModelSelector
        ├── ColorStep.tsx        ← Color selection via ColorPicker
        ├── MemoryStep.tsx       ← Memory scope configuration
        └── ConfirmStep.tsx      ← Review and save confirmation

Deep-Dive Highlights

Core mechanisms from this sub-module have been extracted into dedicated focus pages for in-depth exploration.

Deep-Dive Pages

Agent Creation Wizard Focus

11-step wizard flow with location selection, AI generation, tool bucketing, validation, and file persistence.

Extracted topic page

Tool Bucketing System Focus

How tools are categorized into Read-only, Edit, Execution, MCP, and Other buckets with server-aware grouping.

Extracted topic page

AI-Powered Agent Generation Focus

Claude-based generation using AGENT_CREATION_SYSTEM_PROMPT to produce expert persona configurations from user descriptions.

Extracted topic page

Creation Wizard Steps

#StepComponentDescription
1LocationLocationStepChoose where to save: user (~/.claude/agents/), project, or local
2MethodMethodStepManual entry or AI-generated from a description
3GenerateGenerateStepAI calls Claude with AGENT_CREATION_SYSTEM_PROMPT (if AI chosen)
4IdentifierTypeStepEnter agent identifier (3-50 chars, alphanumeric + hyphens)
5PromptPromptStepWrite or edit the system prompt (min 20 chars)
6DescriptionDescriptionStepWrite when-to-use description (min 10 chars)
7ToolsToolsStepSelect allowed tools from 5 buckets
8ModelModelStepChoose Claude model (reasoning/speed tradeoff)
9ColorColorStepPick badge color (8 named + automatic)
10MemoryMemoryStepConfigure memory scope (if auto-memory enabled)
11ConfirmConfirmStepReview all settings, save to file, update app state

Validation Rules

FieldConstraintSeverity
agentType3-50 charactersError
agentTypeAlphanumeric + hyphens onlyError
agentTypeMust start/end with alphanumericError
agentTypeNo duplicate across sources (except self during edit)Error
whenToUseRequired, non-emptyError
whenToUseMinimum 10 charactersWarning
whenToUseMaximum 5,000 charactersWarning
systemPromptRequired, minimum 20 charactersError
systemPromptMaximum 10,000 charactersWarning
toolsMust be array or undefinedError
toolsNo invalid tool referencesWarning

Agent Sources

Agents can be defined in multiple locations with override precedence:

SourcePathScope
user~/.claude/agents/*.mdAll projects for this user
project.claude/agents/*.mdThis project only (committed)
local.claude/agents/*.local.mdThis project, this machine only
built-inBundled with Claude CodeAlways available
pluginMCP server-providedWhen MCP server is connected

Code Examples

Example: Agent Validation

// Validates an agent definition before saving
const result = validateAgent(
  {
    agentType: 'code-reviewer',
    whenToUse: 'Use when reviewing pull requests for bugs and style issues',
    systemPrompt: 'You are an expert code reviewer. Focus on correctness, security...',
    tools: ['FileRead', 'Grep', 'Glob'],
  },
  availableTools,
  existingAgents,
);

if (!result.isValid) {
  result.errors.forEach(err => console.error(err));
}
result.warnings.forEach(warn => console.warn(warn));

Example: Tool Bucket Categorization

// Tools are organized into 5 buckets for the selector UI
const buckets: ToolBuckets = {
  READ_ONLY: {
    name: 'Read-only',
    toolNames: new Set(['FileRead', 'Grep', 'Glob', 'LSP']),
  },
  EDIT: {
    name: 'Edit',
    toolNames: new Set(['FileEdit', 'FileWrite', 'NotebookEdit']),
  },
  EXECUTION: {
    name: 'Execution',
    toolNames: new Set(['Bash', 'WebFetch', 'WebSearch']),
  },
  MCP: {
    name: 'MCP Tools',
    toolNames: getMcpServerBuckets(tools),
    isMcp: true,
  },
  OTHER: {
    name: 'Other',
    toolNames: new Set(['Agent', 'TaskOutput']),
  },
};

Example: Agent File Format (Markdown with YAML)

// formatAgentAsMarkdown() produces this format for agent files:
function formatAgentAsMarkdown(
  agentType: string,
  whenToUse: string,
  tools: string[] | undefined,
  systemPrompt: string,
  color?: string,
  model?: string,
): string {
  const lines: string[] = [
    '---',
    `agent: ${agentType}`,
  ];

  if (tools) {
    lines.push('tools:');
    tools.forEach(t => lines.push(`  - ${t}`));
  }
  if (color) lines.push(`color: ${color}`);
  if (model) lines.push(`model: ${model}`);

  lines.push('---', '', `# ${agentType}`, '');
  lines.push('## When to use', '', whenToUse, '');
  lines.push('## System prompt', '', systemPrompt);

  return lines.join('\n');
}