sophia-code
Version:
Production-ready agentic CLI code editor with AI-powered coding assistance, planning, and multi-agent delegation. Enterprise-grade security and reliability.
275 lines (217 loc) • 8.14 kB
Markdown
# AGENTS.md
This document describes Sophia's agentic architecture, subagent system, and plugin ecosystem.
## Agent Architecture Overview
Sophia implements a multi-layered agent system designed for flexible, specialized AI assistance:
1. **Primary CLI Agent**: The main interactive interface that manages conversations and delegates tasks
2. **Subagents**: YAML-configurable specialized agents with custom system prompts and tool restrictions
3. **Tool System**: Extensible plugin architecture for external capabilities
4. **Session Management**: Persistent context and conversation history across sessions
## Subagent System
### Configuration Structure
Subagents are defined using YAML configuration files with the following structure:
```yaml
name: agent-identifier
description: Brief description of when to use this agent
system_prompt: |
Custom system message that defines the agent's behavior,
expertise, and constraints. Can be multi-line.
tools:
- /tool1
- /tool2
- /tool3
```
### Agent Discovery Locations
1. **User-level agents**: `~/.sophia/agents/` (global to user)
2. **Project-level agents**: `.sophia/agents/` (specific to project)
Project-level agents take precedence over user-level agents with the same name.
### Agent Invocation
```bash
/agent <agent-name> <task-description>
```
The subagent runs with:
- Its custom system prompt
- Access only to tools listed in its configuration
- The original user's task as input
- No access to conversation history (fresh context)
### Example Agent Configurations
#### Code Reviewer Agent
```yaml
name: code-reviewer
description: Provide detailed code reviews focusing on potential bugs and improvements
system_prompt: |
You are an expert code reviewer. Analyze code for:
- Potential bugs and edge cases
- Performance issues
- Security vulnerabilities
- Code style and maintainability
- Suggest specific improvements with examples.
Be concise and precise in your feedback.
tools:
- /read
- /ls
- /search
```
#### Documentation Agent
```yaml
name: docs-writer
description: Generate comprehensive documentation for code and projects
system_prompt: |
You are a technical documentation specialist. Create clear,
comprehensive documentation that includes:
- Purpose and overview
- API/function signatures
- Usage examples
- Common pitfalls and best practices
Focus on clarity and usefulness for other developers.
tools:
- /read
- /ls
- /http
```
#### Security Auditor Agent
```yaml
name: security-audit
description: Perform security analysis on code and configurations
system_prompt: |
You are a cybersecurity expert focused on defensive security.
Analyze code for security vulnerabilities, configuration issues,
and recommend defensive measures. Never provide information
that could be used maliciously.
tools:
- /read
- /search
```
## Tool System
### Built-in Tools
#### File Operations
- `/edit <file> <instructions>` - AI-driven file editing with patch application
- `/read <file>` - Read file contents (if implemented)
- `/ls <path>` - List directory contents (if implemented)
#### External Information
- `/search <query>` - Web search via DuckDuckGo HTML parsing
- `/http <url>` - Fetch content from HTTP/HTTPS URLs
- `/github_issue <owner> <repo> <number>` - Retrieve GitHub issue details
#### Session Management
- `/help` - Show available commands and agents
- `/clear` - Clear conversation history
- `/model` - Change AI model
- `/config` - Show current configuration
- `/agent <name> <task>` - Delegate to specialized subagent
### Plugin Development
#### Plugin Interface
```python
from tool_registry import Tool, ToolRegistry
def register(registry: ToolRegistry) -> None:
"""Register tools with the registry."""
def my_tool_function(cli, command: str) -> str:
# Parse command arguments
parts = command.split(maxsplit=1)
if len(parts) < 2:
return "Usage: /mytool <argument>"
# Implement tool functionality
result = process_command(parts[1])
# Print and return result
print(result)
return result
registry.register(
Tool(
name="/mytool",
description="Description shown in /help",
execute=my_tool_function,
aliases=["/mt", "/tool"] # Optional alternative names
)
)
```
#### Plugin Loading
Plugins are automatically loaded from the `plugins/` directory. Each plugin file should:
1. Define a `register(registry: ToolRegistry)` function
2. Register one or more `Tool` instances
3. Handle errors gracefully (plugin failures shouldn't crash the CLI)
#### Example Plugin Structure
```python
"""Example plugin for custom functionality."""
import requests
from tool_registry import Tool, ToolRegistry
def register(registry: ToolRegistry) -> None:
"""Register the custom tool."""
def custom_command(cli, command: str) -> str:
# Implementation here
return "Tool executed successfully"
registry.register(
Tool(
name="/custom",
description="Custom tool description",
execute=custom_command
)
)
```
## Agent Security and Constraints
### Tool Restrictions
- Agents only have access to tools explicitly listed in their configuration
- No access to tools = no external capabilities beyond text generation
- Tool access can be fine-tuned per agent for security and focus
### Context Isolation
- Subagents start with fresh context (no conversation history)
- Agents cannot access or modify primary session state
- Each agent invocation is independent
### Best Practices
- Limit tool access to minimum required for agent's purpose
- Use descriptive agent names and clear descriptions
- Test agents in isolation before deployment
- Document agent-specific limitations and use cases
## Advanced Usage Patterns
### Hierarchical Agent Delegation
```bash
# Primary agent delegates to specialist
User: "Review this Python file for security issues"
Sophia: "/agent security-audit Check file.py for vulnerabilities"
# Security agent uses restricted toolset
SecurityAgent: "/read file.py" → analyzes → provides security recommendations
```
### Project-Specific Workflows
```bash
# Project contains .sophia/agents/api-tester.yml
/agent api-tester "Test the user authentication endpoint"
# Agent configured with project-specific knowledge and tools
# Tools: [/http, /search], System prompt includes API documentation context
```
### Multi-Agent Collaboration
```bash
# Sequential agent usage for comprehensive analysis
/agent code-reviewer "Review auth.py"
/agent security-audit "Security check auth.py"
/agent docs-writer "Document auth.py functions"
```
## Session and State Management
### Session Persistence
- Conversations stored in `~/.sophia/sessions/`
- Session format: `YYYYMMDD-HHMMSS.jsonl`
- Resume with `sophia --resume last` or `--resume <session-id>`
### State Isolation
- Primary agent maintains conversation history
- Subagents receive only the immediate task
- Tool state is not shared between agents
- Session configuration (model, API keys) inherited by subagents
### Configuration Management
- Global config: `~/.sophia/config.yml`
- Environment variables: `GROQ_API_KEY`, `GITHUB_TOKEN`
- Model selection persisted per session
- Agent definitions cached and reloaded on file changes
## Extending the Agent System
### Adding New Agent Types
1. Create YAML configuration file
2. Define system prompt for specialized behavior
3. Select appropriate tool subset
4. Test with representative tasks
5. Document usage patterns and limitations
### Custom Tool Development
1. Implement plugin following the standard interface
2. Handle errors and edge cases gracefully
3. Provide clear usage documentation
4. Consider security implications
5. Test integration with existing agents
### Integration Patterns
- API integrations via HTTP tools
- File system operations via built-in tools
- External service authentication via environment variables
- Custom data processing via specialized plugins