# Claude Code CLI Reference and Integration Guide
## Overview
Claude Code is the AI agent process that powers individual agents within the Agent Orchestration Platform. This document provides comprehensive CLI reference and integration patterns for optimal agent management.
## Core Activation and Usage
### **Basic Activation**
```bash
# Primary activation method (run from session root directory)
cd /path/to/session/root
claude # Start interactive mode in current directory
# Alternative activation methods
claude -p "your prompt" # Non-interactive single prompt execution
claude --help # Show comprehensive help information
claude --version # Display Claude Code version information
```
### **Configuration Options**
```bash
# Model and behavior configuration
claude --model sonnet-3.5 # Specify AI model (sonnet-3.5, opus-3, haiku-3)
claude --model opus-3 # Use more powerful model for complex tasks
claude --model haiku-3 # Use faster model for simple tasks
# Output and interface configuration
claude --output-format json # JSON output for automation and parsing
claude --no-color # Disable colored output (preferred for automation)
claude --verbose # Enable verbose logging and debugging output
# Permission and security configuration
claude --dangerously-skip-permissions # Skip permission prompts (automation only)
```
### **Session Management**
```bash
# Session continuity
claude --continue # Continue previous session in same directory
claude --resume # Resume interrupted session with state recovery
# Debug and diagnostics
claude --mcp-debug # Debug MCP server connection issues
```
## Interactive Commands Reference
### **Essential Navigation Commands**
```bash
/help # Show all available commands with descriptions
/clear # Clear current conversation history
/compact # Summarize long conversations to reduce context
/exit # Exit Claude Code (alternative: /quit)
/cost # Show token usage and associated costs
/model # Switch between available AI models
/config # View and modify current configuration
```
### **Project Management Commands**
```bash
# Project analysis and setup
/init # Analyze project structure and create CLAUDE.md
/permissions # Manage tool permissions (Allow/Deny/Default)
# Version control integration
/git # Git operations and repository status
/git status # Quick Git status check
/git log # View commit history
/git diff # Show current changes
# Build and deployment
/test # Run project test suite
/build # Execute project build process
/deploy # Run deployment operations
```
### **File Operations Commands**
```bash
# File content operations
/read <file> # Read and display file contents
/write <file> # Write content to file (interactive)
/edit <file> # Edit existing file with modifications
/create <file> # Create new file with content
/delete <file> # Delete specified file (with confirmation)
# Search and discovery
/search <pattern> # Search codebase using ripgrep (fast search)
/find <filename> # Find files by name or pattern
```
### **Advanced Feature Commands**
```bash
# External content integration
/web <url> # Fetch and analyze web page content
/image # Analyze images (supports drag & drop)
# System integration
/shell <command> # Execute shell commands in current context
/context # Show current conversation context size
/reset # Reset all settings to default values
```
### **Debug and Diagnostic Commands**
```bash
# System diagnostics
/debug # Show comprehensive debug information and system state
/logs # View recent error logs and activity history
/mcp-debug # Debug MCP server connection and communication issues
# Configuration and permissions
/permissions # Check current file access and tool permissions
/config # Verify and display current Claude Code configuration
# Performance monitoring
/context # Monitor conversation context usage
/cost # Track token consumption and costs
```
### **Hidden and Advanced Commands**
```bash
# Terminal and environment
/terminal-setup # Configure terminal-specific behaviors and settings
/cache # Manage conversation cache and storage
/reset # Reset all settings and clear cached data
# Development and debugging
/logs # Access detailed logging information
/debug # Advanced debugging and system introspection
```
## Custom Command System
### **Project-Level Commands**
Located in `.claude/commands/` within the project directory:
```bash
# Project-specific automation
/project:setup # Custom project initialization and setup
/project:deploy-staging # Deploy to staging environment
/project:deploy-production # Deploy to production environment
/project:fix-issue <number> # Automated issue analysis and fixing
/project:review-pr <number> # Pull request review automation
/project:generate-docs # Documentation generation and updates
/project:run-tests # Custom test execution workflows
/project:cleanup # Project cleanup and maintenance
```
### **Personal Commands**
Located in `~/.claude/commands/` for user-specific automation:
```bash
# Personal workflow automation
/personal:backup # Personal backup scripts and procedures
/personal:cleanup # Code cleanup and formatting routines
/personal:optimize # Performance optimization workflows
/personal:sync # Synchronization with external systems
/personal:deploy # Personal deployment configurations
```
### **Custom Command Structure**
```bash
# Command file structure
.claude/commands/
├── setup.md # Project setup automation
├── deploy-staging.md # Staging deployment workflow
├── fix-issue.md # Issue resolution automation
└── generate-docs.md # Documentation generation
# Example command file (.claude/commands/setup.md)
# Setup Project Environment
This command initializes the development environment.
## Steps
1. Install dependencies
2. Configure environment variables
3. Initialize database
4. Run initial tests
## Command
```bash
npm install
cp .env.example .env
npm run db:migrate
npm test
```
```
## Integration with Agent Orchestration Platform
### **Agent Activation Pattern**
```python
# Agent activation in session context
async def activate_claude_code(agent_id: AgentId, session_root: Path) -> None:
"""Activate Claude Code for agent in session directory."""
# Change to session root directory
activation_command = f"cd {session_root} && claude"
# Add configuration options
if config.no_color:
activation_command += " --no-color"
if config.model != "sonnet-3.5":
activation_command += f" --model {config.model}"
if config.verbose:
activation_command += " --verbose"
# Send activation command to iTerm2 tab
await iterm_manager.send_text_to_tab(agent_id, activation_command + "\n")
# Wait for Claude Code initialization
await asyncio.sleep(3)
# Verify activation successful
status = await check_claude_code_status(agent_id)
if not status.active:
raise AgentActivationError(f"Failed to activate Claude Code for agent {agent_id}")
```
### **Command Execution Integration**
```python
# Execute Claude Code commands programmatically
async def send_claude_command(agent_id: AgentId, command: str) -> CommandResult:
"""Send command to active Claude Code instance."""
# Validate command safety
if not is_safe_command(command):
raise SecurityError(f"Unsafe command rejected: {command}")
# Send command via iTerm2
await iterm_manager.send_text_to_tab(agent_id, f"{command}\n")
# Monitor for completion
output = await monitor_command_output(agent_id, timeout=30)
return CommandResult(
success=output.exit_code == 0,
output=output.stdout,
error=output.stderr
)
# Example usage patterns
async def initialize_agent_environment(agent_id: AgentId):
"""Initialize agent with project-specific setup."""
# Run project initialization
await send_claude_command(agent_id, "/init")
# Set appropriate permissions
await send_claude_command(agent_id, "/permissions allow-file-operations")
# Check project status
status = await send_claude_command(agent_id, "/git status")
return status
```
### **Health Monitoring Integration**
```python
# Monitor Claude Code agent health
async def monitor_claude_code_health(agent_id: AgentId) -> HealthStatus:
"""Monitor Claude Code instance health."""
try:
# Check basic responsiveness
debug_output = await send_claude_command(agent_id, "/debug")
# Parse debug information
health_info = parse_debug_output(debug_output.output)
# Check resource usage
resource_info = await send_claude_command(agent_id, "/context")
context_usage = parse_context_output(resource_info.output)
return HealthStatus(
responsive=debug_output.success,
context_usage=context_usage.percentage,
memory_usage=health_info.memory_mb,
error_count=health_info.error_count,
last_activity=health_info.last_activity
)
except Exception as e:
return HealthStatus(
responsive=False,
error_message=str(e),
requires_restart=True
)
```
## Troubleshooting and Diagnostics
### **Common Issues and Solutions**
#### **Activation Issues**
```bash
# Problem: Claude Code won't start
# Solution: Check directory and permissions
pwd # Verify in correct directory
ls -la # Check directory permissions
claude --version # Verify Claude Code installation
# Problem: Model not available
# Solution: Check available models and fallback
claude --model sonnet-3.5 # Try different model
claude --model haiku-3 # Use fallback model
```
#### **Permission Issues**
```bash
# Problem: File access denied
# Solution: Check and adjust permissions
/permissions # Check current permissions
/permissions allow-all # Allow all operations (if safe)
/permissions reset # Reset to default permissions
# Problem: Directory access restricted
# Solution: Verify directory boundaries
pwd # Check current directory
/config # Verify configuration
```
#### **Performance Issues**
```bash
# Problem: Slow response times
# Solution: Monitor and optimize context
/context # Check context usage
/compact # Reduce context size
/clear # Clear conversation if needed
# Problem: High memory usage
# Solution: Monitor and restart if needed
/debug # Check system resources
/reset # Reset system state
```
#### **Connection Issues**
```bash
# Problem: MCP connection failures
# Solution: Debug MCP connectivity
/mcp-debug # Debug MCP server connection
/logs # Check recent error logs
claude --mcp-debug # Start with MCP debugging enabled
# Problem: iTerm2 integration issues
# Solution: Check terminal integration
/terminal-setup # Verify terminal configuration
/config # Check integration settings
```
### **Diagnostic Commands Workflow**
```bash
# Step 1: Basic health check
/debug # Get system overview
/config # Verify configuration
# Step 2: Performance analysis
/context # Check context usage
/cost # Review resource consumption
# Step 3: Detailed diagnostics
/logs # Review error history
/permissions # Verify access rights
# Step 4: Advanced troubleshooting
/mcp-debug # Debug MCP connectivity
claude --verbose # Restart with verbose logging
```
### **Error Recovery Procedures**
```python
# Automated error recovery
async def recover_claude_code_agent(agent_id: AgentId) -> RecoveryResult:
"""Attempt automatic recovery of Claude Code agent."""
try:
# Step 1: Attempt soft recovery
debug_result = await send_claude_command(agent_id, "/debug")
if debug_result.success:
return RecoveryResult(success=True, method="soft_recovery")
# Step 2: Clear and reset
await send_claude_command(agent_id, "/clear")
await send_claude_command(agent_id, "/reset")
# Step 3: Restart if needed
if not await is_agent_responsive(agent_id):
await restart_claude_code_agent(agent_id)
return RecoveryResult(success=True, method="full_restart")
return RecoveryResult(success=True, method="reset_recovery")
except Exception as e:
return RecoveryResult(
success=False,
error=str(e),
requires_manual_intervention=True
)
```
## Best Practices for Integration
### **Agent Configuration Management**
```python
# Recommended agent configuration
@dataclass(frozen=True)
class OptimalClaudeConfig:
"""Optimal configuration for orchestrated Claude Code agents."""
model: str = "sonnet-3.5" # Balanced performance and capability
no_color: bool = True # Clean output for automation
skip_permissions: bool = False # Security-conscious default
verbose: bool = False # Reduce noise in logs
output_format: str = "text" # Human-readable by default
def to_command_args(self) -> List[str]:
"""Convert to command line arguments."""
args = []
if self.model != "sonnet-3.5":
args.extend(["--model", self.model])
if self.no_color:
args.append("--no-color")
if self.skip_permissions:
args.append("--dangerously-skip-permissions")
if self.verbose:
args.append("--verbose")
if self.output_format != "text":
args.extend(["--output-format", self.output_format])
return args
```
### **Resource Management**
```python
# Monitor and limit resource usage
async def enforce_resource_limits(agent_id: AgentId) -> None:
"""Enforce resource limits on Claude Code agent."""
health = await monitor_claude_code_health(agent_id)
if health.context_usage > 80:
await send_claude_command(agent_id, "/compact")
if health.memory_usage > 400: # MB
await send_claude_command(agent_id, "/clear")
if health.error_count > 10:
await restart_claude_code_agent(agent_id)
```
This comprehensive Claude Code integration guide ensures optimal agent performance and reliability within the Agent Orchestration Platform.