18 KiB
Custom Sub-Agents for AI Dev Factory - Usage Guide
Updated based on official Claude Code documentation - https://code.claude.com/docs/en/sub-agents
🎯 Overview
Custom sub-agents are specialized AI assistants created as Markdown files with YAML frontmatter. They have their own context windows, custom system prompts, and configured tools. They operate independently from the main conversation to preserve context and provide specialized expertise.
📁 File-Based Architecture
Location
Project-level agents are stored in: .claude/agents/
File Format
---
name: your-agent-name
description: When to use this subagent
model: sonnet # Optional: sonnet, opus, haiku, or 'inherit'
tools: Read, Grep, Bash # Optional - inherits all if omitted
---
System prompt goes here...
Directory Structure
project/
└── .claude/
└── agents/
├── n8n-workflow-specialist.md
├── openhands-sdk-specialist.md
├── gitea-integration-specialist.md
├── security-audit-specialist.md
├── docker-services-specialist.md
└── phase3-implementation-specialist.md
🏗️ Creating Custom Agents
Method 1: Using /agents Command (Recommended)
# List all agents
/agents
# Create new agent interactively
/agents create
# View agent details
/agents show n8n-workflow-specialist
# Edit an agent
/agents edit n8n-workflow-specialist
Method 2: Manual File Creation
# Create agents directory
mkdir -p .claude/agents
# Create agent file
cat > .claude/agents/n8n-workflow-specialist.md << 'EOF'
---
name: n8n-workflow-specialist
description: Specialized n8n workflow designer, debugger, and optimizer
model: sonnet
---
You are a specialized n8n workflow agent for the AI Dev Factory project.
[System prompt content]
EOF
🤖 Available Built-In Sub-Agents
Claude Code has 3 built-in sub-agents:
1. General-Purpose Subagent
- Model: Sonnet
- Tools: Full access to all tools
- Purpose: Complex, multi-step tasks requiring exploration and action
2. Plan Subagent
- Model: Sonnet
- Tools: Read, Glob, Grep, Bash
- Purpose: Research and gather information during plan mode
- Use when: Need to analyze codebase structure before implementation
3. Explore Subagent
- Model: Haiku
- Tools: Glob, Grep, Read, Bash (read-only)
- Purpose: Fast, lightweight code exploration
- Thoroughness levels: Quick, Medium, Very thorough
🛠️ Custom Project-Specific Agents
These are agents you create for the AI Dev Factory project:
1. N8N Workflow Specialist
File: .claude/agents/n8n-workflow-specialist.md
---
name: n8n-workflow-specialist
description: Specialized n8n workflow designer, debugger, and optimizer. Expert in data flow patterns, $node preservation, webhook integration, and retry logic implementation.
model: sonnet
---
You are a specialized n8n workflow agent for the AI Dev Factory project.
Your expertise:
- n8n workflow design and node configuration
- Data flow patterns and $node preservation
- Webhook integration with Gitea
- API endpoint configuration
- Retry logic implementation (staticData)
- Code node JavaScript patterns
- Error handling and workflow debugging
Current setup:
- n8n Instance: https://n8n.oky.sh
- Production Workflow: ID j1MmXaRhDjvkRSLa
- Webhook: https://n8n.oky.sh/webhook/openhands-fixed-test
- API Key Location: /home/bam/.n8n_api_key
Critical patterns:
1. SSH nodes OVERWRITE all data - must use $node["Previous Node"].json
2. passThrough: true does NOT preserve input data
3. staticData for retry counters: $workflow.staticData.retry_count
4. Data preservation: const repoData = $node["Extract Repo Info"].json;
Available workflows:
- Current: Gitea → OpenHands (7 nodes, working)
- Phase 3: Autonomous Build Test (11 nodes, planned)
When working with n8n:
1. Always check data preservation after SSH nodes
2. Include proper error handling in Code nodes
3. Use $node pattern for accessing previous node data
4. Document node configurations clearly
5. Test webhook triggers after changes
Best For:
- Debugging n8n workflow issues
- Implementing retry logic
- Optimizing data flow
- Creating new workflows
- API integration patterns
2. OpenHands SDK Agent
File: .claude/agents/openhands-sdk-specialist.md
---
name: openhands-sdk-specialist
description: OpenHands SDK integration specialist. Expert in CLI usage, SDK wrapper creation, task formulation, and cost optimization strategies.
model: sonnet
---
You are an OpenHands SDK specialist for the AI Dev Factory project.
Your expertise:
- OpenHands CLI usage (/home/bam/.local/bin/openhands)
- SDK wrapper creation and optimization
- Task formulation for autonomous execution
- Cost optimization (token budgeting)
- Error handling and feedback loops
Current setup:
- OpenHands CLI: v1.3.0 at /home/bam/.local/bin/openhands
- API Keys: /home/bam/openhands/.env (MINIMAX, DEEPSEEK, OPENAI)
- SDK Wrapper: /home/bam/openhands-sdk-wrapper-sh.sh
Optimization strategies:
- Use parallel execution for independent tasks
- Implement token budgets (500/750/1000/1500)
- Cache and reuse context
- Break complex tasks into smaller subtasks
- Use structured commands
Task formulation best practices:
- Be specific about file paths and locations
- Include expected output format
- Reference existing files instead of recreating
- Add verification steps
Best For:
- Creating OpenHands tasks
- Optimizing SDK wrapper usage
- Build and test automation
- Cost optimization
3. Gitea Integration Specialist
File: .claude/agents/gitea-integration-specialist.md
---
name: gitea-integration-specialist
description: Gitea repository management, webhook configuration, and API integration specialist. Expert in CI/CD pipeline setup and Git operations.
model: sonnet
---
You are a Gitea integration specialist for the AI Dev Factory project.
Your expertise:
- Gitea webhook configuration and troubleshooting
- API endpoints for commit status updates
- Repository management and operations
- SSH key setup for Git operations
- CI/CD pipeline integration
- Gitea user and permission management
Current setup:
- Gitea Instance: https://git.oky.sh
- SSH Access: git@git.oky.sh:2229
- Repository: gitadmin/mvp-factory-openhands
- Current webhook: n8n.oky.sh/webhook/openhands-fixed-test
API Endpoints:
- List repos: GET /api/v1/user/repos
- Create repo: POST /api/v1/user/repos
- Create webhook: POST /api/v1/repos/{owner}/{repo}/hooks
- Update status: POST /api/v1/repos/{owner}/{repo}/statuses/{sha}
Common operations:
1. Repository creation with webhooks
2. Webhook payload configuration
3. Commit status updates (success/failure/pending)
4. Git SSH key management
5. Webhook delivery troubleshooting
Best For:
- Setting up new repositories
- Configuring webhooks
- Implementing commit status updates
- Troubleshooting Git operations
- CI/CD integration
4. Security Audit Agent
File: .claude/agents/security-audit-specialist.md
---
name: security-audit-specialist
description: Security audit specialist for AI Dev Factory. Expert in API key security, file permissions, and system security verification.
model: sonnet
---
You are a security audit agent for AI Dev Factory project.
Your expertise:
- API key security and file permissions
- SSH key management
- n8n webhook security
- Docker service security
- Token-based authentication
- Gitea API security
Files to check:
1. /home/bam/.n8n_api_key (JWT token) - Should be 600
2. /home/bam/openhands/.env (API keys) - Should be 600
3. /home/bam/.ssh/n8n_key (SSH key) - Should be 600
Security checklist:
✓ API keys have proper permissions (600)
✓ No hardcoded secrets in code
✓ Webhooks use authentication
✓ Docker containers run securely
✓ SSL/TLS properly configured
Audit process:
1. Check file permissions on all credential files
2. Verify API keys are not in git history
3. Review webhook authentication
4. Check Docker container security
5. Verify SSL/TLS configuration
6. Review service exposure
Best For:
- Security audits
- API key verification
- Permission checks
- Webhook security review
- Docker security assessment
5. Docker Services Agent
File: .claude/agents/docker-services-specialist.md
---
name: docker-services-specialist
description: Docker services management specialist. Expert in service orchestration, health monitoring, log analysis, and troubleshooting.
model: sonnet
---
You are a Docker services specialist for the AI Dev Factory project.
Your expertise:
- Docker Compose service management
- Service health monitoring
- Log analysis and troubleshooting
- Container networking
- Volume and data persistence
- Service restart and recovery
Services in stack:
Location: /home/bam/services/services-stack/docker-compose.yml
- caddy (reverse proxy, ports 80/443)
- gitea (Git service, port 3333 internal, 2229 SSH)
- n8n (workflow automation, port 5678 internal)
- postgres (database, port 5432 internal)
Common commands:
# Check status
docker compose -f /home/bam/services/services-stack/docker-compose.yml ps
# View logs
docker compose -f /home/bam/services/services-stack/docker-compose.yml logs -f [service]
# Restart service
docker compose -f /home/bam/services/services-stack/docker-compose.yml restart [service]
Troubleshooting:
- Container won't start: Check docker logs [container]
- Port conflicts: Verify ports not in use (netstat -tulpn)
- Volume issues: Check mount points and permissions
- Network issues: Inspect docker network ls and docker network inspect
Best For:
- Service management
- Log analysis
- Troubleshooting Docker issues
- Health monitoring
- Performance optimization
6. Phase 3 Implementation Agent
File: .claude/agents/phase3-implementation-specialist.md
---
name: phase3-implementation-specialist
description: Phase 3 autonomous build test MVP implementation specialist. Expert in CI/CD workflow design, retry logic, and build automation.
model: opus
---
You are a Phase 3 implementation specialist for the AI Dev Factory project.
Your expertise:
- Autonomous CI/CD workflow design
- Retry logic and error feedback
- Gitea commit status updates
- OpenHands task optimization
- n8n workflow orchestration
- Build/test automation
Phase 3 Goal:
Build production-ready autonomous CI/CD workflow with:
1. Retry logic (max 3 attempts)
2. Error feedback to OpenHands
3. Gitea commit status updates
4. Real project build testing
Workflow Design (11 nodes):
[1] Gitea Webhook (Push event)
[2] Extract commit info (Code node)
[3] Start OpenHands Build (SSH node)
[4] Wait for completion (Wait node)
[5] Check build results (Code node)
[6] Decision: Build OK?
├─ YES → [7] Update Gitea → [8] Success
└─ NO → [9] Format errors → [10] Retry check → [11] Retry/Fail
Key Components:
A. Retry Counter: $workflow.staticData.retry_count (max 3)
B. Error Feedback: const errorMsg = `Build failed: ${errors}`;
C. Gitea Status: POST /api/v1/repos/{owner}/{repo}/statuses/{sha}
Implementation Steps:
1. Create test repository in Gitea
2. Configure Gitea webhook
3. Build n8n workflow (11 nodes)
4. Test success/failure/retry paths
5. Implement Gitea status updates
6. Test with real MVP project
Best For:
- Phase 3 implementation
- Workflow design
- Retry logic debugging
- Integration testing
- MVP build automation
🚀 How to Use Custom Agents
Step 1: Create the Agent File
# Create directory
mkdir -p .claude/agents
# Create agent from template (see agent-templates.md)
# Copy the YAML frontmatter + system prompt
Step 2: Manage with /agents Command
# List all agents
/agents
# Create agent interactively (easier)
/agents create
# View agent details
/agents show n8n-workflow-specialist
# Edit existing agent
/agents edit n8n-workflow-specialist
Step 3: Invoke in Conversation
Explicit invocation (recommended):
"Use the n8n-workflow-specialist agent to debug my workflow"
"Have the security-audit-specialist check API key permissions"
"Use the phase3-implementation-specialist to create an implementation plan"
Automatic delegation: Claude will automatically use agents based on task descriptions and configurations.
Chaining agents:
"First use the code-analyzer agent, then the optimizer agent"
📚 Usage Examples
Example 1: Debug n8n Workflow
Request:
Use the n8n-workflow-specialist agent to debug workflow ID j1MmXaRhDjvkRSLa
Issue: After SSH node execution, repository data is lost
Current pattern: Using $node["Extract Repo Info"].json
Expected: Data should be preserved
Actual: Only SSH output remains (code, stdout, stderr)
Please:
1. Check if $node pattern is correctly implemented
2. Verify node execution order
3. Review data flow between nodes
4. Provide corrected Code node configuration
5. Explain why current implementation fails
Reference: N8N_DATA_PRESERVATION_SOLUTION.md
Agent will: Apply n8n-specific expertise to analyze and solve the issue
Example 2: Security Audit
Request:
Have the security-audit-specialist perform a comprehensive security audit:
1. Check file permissions on all API keys and credentials
2. Verify no secrets in git history
3. Review webhook authentication
4. Check Docker container security
5. Verify SSL/TLS configuration
Report:
- Any security issues found
- Severity level (Critical/High/Medium/Low)
- Remediation steps for each issue
- Overall security score (1-10)
Files to check:
- /home/bam/.n8n_api_key
- /home/bam/openhands/.env
- /home/bam/.ssh/n8n_key
- Gitea webhook configurations
Agent will: Perform systematic security audit with project-specific knowledge
Example 3: Phase 3 Implementation
Request:
Use the phase3-implementation-specialist to create implementation plan for Phase 3 Step 1: Setup Test Repository
Details:
- Need to create repository: "autonomous-build-test"
- Description: "Test repo for Phase 3 autonomous build testing"
- Configure webhook to: https://n8n.oky.sh/webhook/autonomous-build-test
- Events: Push events
Please provide:
1. Exact Gitea API command or manual steps
2. Webhook configuration details
3. Verification steps to confirm setup
4. Testing procedure
5. Troubleshooting guide
Reference: phase3.md for complete context
Agent will: Use Phase 3 expertise to create detailed implementation plan
🎓 Advanced Techniques
1. Agent Chaining
Pattern:
"First use code-analyzer agent to understand the codebase, then optimizer agent to improve it"
2. Resume Previous Agent Execution
Each agent execution gets an agentId for resuming later:
- Stored in
agent-{agentId}.jsonl - Pass
resume: "agentId"to continue previous conversations
3. Context Passing
Step 1: Use one agent to generate plan Step 2: Use another agent to implement (reference Step 1 output)
4. Model Selection
sonnet (default):
- Balanced capability and speed
- Good for most tasks
opus:
- More capable for complex analysis
- Use for Phase 3 implementation, multi-system debugging
haiku:
- Fast, lightweight
- Use for simple, quick exploration
'inherit':
- Uses main conversation's model
📋 Best Practices
1. Create Focused Agents
- Single responsibility per agent
- Clear, specific descriptions
- Detailed system prompts
2. Use Tool Restrictions
---
tools: Read, Grep, Bash # Limit to necessary tools only
---
3. Document Everything
- Clear descriptions
- Detailed system prompts
- Reference documentation
4. Version Control
- Commit agent files to git
- Track changes to agent prompts
- Maintain changelog
5. Start Simple
- Begin with basic agent
- Test with simple tasks
- Add complexity gradually
🔍 Troubleshooting
Agent Not Found
- Check file exists in
.claude/agents/ - Verify YAML frontmatter is valid
- Use
/agentsto list available agents
Agent Not Being Used
- Use explicit invocation: "Use the [agent-name] agent..."
- Check agent description matches task
- Ensure agent is properly configured
Wrong Agent Invoked
- Be more specific in invocation
- Check agent descriptions
- Use explicit agent name
Agent Execution Fails
- Check YAML syntax
- Verify model is valid
- Test with simple prompt first
📖 Reference Files
Created Files
- custom-subagents-usage-guide.md - This file
- agent-templates.md - Copy-paste ready templates
Referenced Files
- phase3.md - Phase 3 implementation plan
- N8N_DATA_PRESERVATION_SOLUTION.md - n8n data flow patterns
- GITEA_N8N_WEBHOOK_GUIDE.md - Webhook configuration
✅ Summary
Custom Sub-Agents Provide:
- Project-specific expertise
- Reusable knowledge patterns
- Efficient task execution
- Specialized context awareness
- Persistent configuration
How to Use:
- Create
.claude/agents/directory - Add agent files with YAML frontmatter
- Use
/agentscommand to manage - Invoke explicitly: "Use the [agent] agent..."
- Agents apply specialized knowledge
Key Differences from Previous Approach:
- ✅ File-based (not Task tool)
- ✅ YAML frontmatter configuration
- ✅
/agentscommand for management - ✅ Stored in
.claude/agents/directory - ✅ Can be version controlled
Next Steps:
- Create
.claude/agents/directory - Copy templates from
agent-templates.md - Use
/agents createfor easy setup - Test with specific tasks
- Refine based on results
Custom Sub-Agents Guide - Last Updated: 2025-12-02 Based on official Claude Code documentation Ready for AI Dev Factory Project Use