Home · Developers · Guides · Agents

Intelligence

Agents

Multi-agent hierarchy and built-ins

Nova Coder uses a multi-agent system instead of a single monolithic prompt. Specialist agents collaborate through the event bus and are coordinated by the AgentManager.

Agent Hierarchy

Manager
  ↓
Planner
  ↓
Architect
  ↓
Coder
  ↓
Reviewer
  ↓
Tester
  ↓
Debugger
  ↓
Documenter

Base Agent

Every agent extends Agent and receives optional service references:

from novacoder.agents.agent import Agent, AgentTask, AgentResult

class MyAgent(Agent):
    name = "my_agent"
    description = "Does something useful."

    async def run(self, task: AgentTask) -> AgentResult:
        return AgentResult(
            success=True,
            output={},
            summary=f"Completed {task.goal}",
        )

Agent may be constructed with ai, tools, memory, workspace, and communication_protocol references. AgentService.initialize() injects these services from the kernel container. A synchronous wrapper, run_sync(), is available for non-async callers.

During a run, AgentManager sets a SessionContext on the agent via agent.set_session_context(). The agent can access it through self.session_context to read or write session-scoped memory. Agents can also communicate with each other through the communication_protocol if enabled.

Built-in Agents

Agent Responsibility
chat Provides fast conversational responses for quick interactions
planner Breaks goals into executable plans
architect Explores project structure and designs implementation approaches
coder Generates and edits code
reviewer Reviews code for quality and safety
tester Plans and executes tests to verify code changes
debugger Analyzes errors and proposes debugging steps
documentation Drafts and updates project documentation
security Scans code for vulnerabilities and security anti-patterns
performance Analyzes and optimizes code performance
devops Handles deployment, CI/CD, and infrastructure
database Database schema design, migrations, and queries
mobile Mobile app development (iOS, Android)
ui_ux User interface and experience design
data_science Data analysis, ML model development
api_design API design, documentation, and testing
compliance Regulatory compliance checking
git Manages Git version control operations including commits, branches, merges, and conflict resolution

Note: The default built-in set in the AgentService includes the core agents plus documentation and security. Advanced/specialized agents (performance, devops, database, mobile, ui_ux, data_science, api_design, compliance, git) are disabled by default and can be enabled through AgentsConfig or by explicitly calling AgentManager.register().

AgentTask

Tasks carry the context an agent needs:

from novacoder.agents.agent import AgentTask

task = AgentTask(
    id="task-1",
    description="Add OAuth login",
    goal="Add OAuth login",
    context={"framework": "flask"},
    priority=1,
)

AgentManager

AgentManager registers and dispatches agents. Both async and sync runners are available:

from novacoder.agents.manager import AgentManager

manager = AgentManager()
print(manager.list_agents())

# Synchronous entry point
result = manager.run("planner", task)

# Asynchronous entry point
result = await manager.run_async("planner", task)
print(result.success, result.summary)

Advanced AgentManager Features

The AgentManager supports several advanced systems that can be enabled or disabled:

manager = AgentManager(
    memory_service=None,
    enable_communication=True,      # Enable agent-to-agent communication
    enable_learning=True,           # Enable performance tracking and learning
    enable_testing=True,             # Enable agent testing framework
    enable_recovery=True,            # Enable error recovery system
    enable_state_management=True,    # Enable agent state management
    enable_monitoring=True,          # Enable agent monitoring
    enable_security_validation=True,  # Enable agent security validation
    enable_cost_tracking=True,       # Enable agent cost tracking
    enable_collaboration=True,       # Enable agent collaboration patterns
    enable_marketplace=True,         # Enable agent marketplace
    enable_versioning=True,          # Enable agent versioning
    enable_sandboxing=True,          # Enable agent sandboxing
    enable_task_distribution=True,   # Enable intelligent task distribution
    enable_access_control=True,      # Enable role-based access control
    enable_input_validation=True,    # Enable input validation
    enable_pooling=True,             # Enable agent pooling
    enable_execution_pool=True,      # Enable execution pool management
    enable_memory_management=True,   # Enable memory management
    enable_profiling=True,           # Enable agent profiling
)
  • Communication Protocol: Enables agents to send messages to each other, delegate tasks, and hand off work
  • Learning System: Tracks agent performance and provides recommendations for improvement
  • Orchestrator: Provides multiple strategies for multi-agent workflow execution (sequential, parallel, dynamic, etc.)
  • Testing Framework: Comprehensive testing infrastructure for validating agent behavior
  • Error Recovery: Automatic error classification and recovery strategies
  • State Management: Persistent agent state storage with checkpointing and task resumption
  • Monitoring: Agent execution tracing, performance metrics, and anomaly detection
  • Security Validation: Agent action validation with security policies and audit logging
  • Cost Tracking: Per-agent cost monitoring with budgeting and optimization recommendations
  • Collaboration: Multiple collaboration patterns for complex multi-agent workflows
  • Marketplace: Agent sharing and discovery system with packaging, search, and reviews
  • Versioning: Semantic versioning for agent configurations with rollback capabilities
  • Sandboxing: Secure isolated execution environments with resource limits
  • Task Distribution: Intelligent load balancing and capability-based task assignment
  • Access Control: Role-based access control with permissions and policies
  • Input Validation: Comprehensive input validation with security checks
  • Agent Pooling: Agent pooling with lazy initialization and load balancing
  • Execution Pool: Concurrent task execution with retry logic and queuing
  • Memory Management: Memory usage tracking, limits, and garbage collection
  • Profiling: Function call tracing and performance analysis
  • Performance Optimization: Performance metrics tracking, optimization suggestions, and result management
  • Documentation Automation: Automatic documentation generation with templates and multiple output formats

Access these systems through the manager:

# Communication
protocol = manager.communication_protocol
await protocol.send_message('agent1', 'agent2', MessageType.NOTIFICATION, {'data': 'value'})

# Learning
metrics = manager.get_agent_metrics('coder')
recommendations = manager.get_learning_recommendations('coder')

# Orchestration
orchestrator = manager.orchestrator
orchestrator.set_strategy(OrchestrationStrategy.PARALLEL)

# Testing
framework = manager.test_framework
suite = framework.create_test_suite('coder')

# Error Recovery
recovery = manager.error_recovery
stats = manager.get_error_statistics('coder')

# State Management
state_manager = manager.state_manager
summary = manager.get_state_summary('coder')

# Monitoring
monitoring = manager.monitoring
perf_summary = manager.get_performance_summary('coder')

# Security Validation
security_validator = manager.security_validator
sec_summary = manager.get_security_summary('coder')

# Cost Tracking
cost_tracker = manager.cost_tracker
cost_summary = manager.get_cost_summary('coder')

# Collaboration
collaboration = manager.collaboration
result = await collaboration.execute_swarm('Write code', 'Generate code', ['coder', 'architect'])

# Marketplace
marketplace = manager.marketplace
stats = manager.get_marketplace_statistics()

# Versioning
version_manager = manager.version_manager
history = manager.get_version_history('coder')

# Sandboxing
sandbox_manager = manager.sandbox_manager
sandbox_stats = manager.get_sandbox_statistics()

# Task Distribution
task_distributor = manager.task_distributor
dist_stats = manager.get_distribution_statistics()

# Access Control
access_control = manager.access_control
has_permission = access_control.check_permission('coder', PermissionType.READ, '/path/to/file')

# Input Validation
input_validator = manager.input_validator
validation_result = input_validator.validate({'data': 'value'}, 'agent_input')

# Agent Pooling
pool_manager = manager.pool_manager
pool_stats = pool_manager.get_statistics()

# Execution Pool
execution_pool_manager = manager.execution_pool_manager
exec_stats = execution_pool_manager.get_statistics()

# Memory Management
memory_manager = manager.memory_manager
mem_stats = memory_manager.get_statistics()

# Profiling
profiler = manager.profiler
prof_stats = profiler.get_statistics()

# Performance Optimization
performance_optimizer = manager.performance_optimizer
perf_stats = performance_optimizer.get_statistics()

# Documentation Automation
documentation_automation = manager.documentation_automation
doc_summary = documentation_automation.get_documentation_summary()

TUI Integration

The Agent System is integrated into the Terminal User Interface (TUI) through the Agents page.

Agent Monitoring in TUI

The TUI provides enhanced agent monitoring capabilities:

  • Performance Metrics Display: Real-time display of total runs, success rate, average cost, and active tasks
  • Per-Agent Metrics: Each agent in the table shows runs, success rate, and average cost
  • Detailed Metrics View: Button to view detailed performance metrics for selected agent
  • Automatic Refresh: Metrics automatically refresh after agent execution

Agent Versioning in TUI

The TUI provides agent version management capabilities:

  • Version History: View all versions of an agent with status and creation date
  • Active Version Display: Shows currently active version for each agent
  • Changelog View: Display change log for each version
  • Rollback Support: Support for rolling back to previous versions via TUI

TUI Usage

Access agent monitoring and versioning in the TUI:

  • Navigate to the Agents page
  • View performance metrics at the top of the page
  • Click "View Metrics" to see detailed metrics for selected agent
  • Click "Version History" to view version history and changelog

Agent Collaboration in TUI

The TUI provides agent collaboration pattern execution:

  • Collaboration Patterns: 8 pattern types (Swarm, Hierarchical, Peer Review, Debate, Consensus, Chain of Thought, Divide and Conquer, Specialist Pool)
  • Multi-Agent Execution: Execute tasks with multiple agents working together
  • Pattern Selection: Choose the appropriate collaboration pattern for the task
  • Agent Selection: Specify which agents should participate in the collaboration
  • Result Display: View collaboration results including agent contributions and execution time

Agent Configuration in TUI

The TUI provides agent configuration management:

  • Priority Setting: Configure agent priority (1-10)
  • Execution Time Limits: Set maximum execution time for agents
  • Retry Configuration: Configure retry count for failed executions
  • Enable/Disable: Enable or disable specific agents
  • Configuration Persistence: Save and load agent configurations

Sandboxing

sandbox_manager = manager.sandbox_manager sandbox_stats = manager.get_sandbox_statistics()

Task Distribution

task_distributor = manager.task_distributor dist_stats = manager.get_distribution_statistics()


Agents can also be unregistered:

```python
manager.unregister("planner")

AgentService

AgentService is the kernel service that exposes the agent manager and workflow executor to the rest of the application. It resolves AIService, ToolService, MemoryService, WorkspaceService, and RuntimeService from the container and injects them into agent constructors. AgentService also uses ModelRouter to choose the best AI provider for each agent task. Agents are enabled or disabled based on AgentsConfig flags during initialization.

from novacoder.agents.service import AgentService
from novacoder.config.settings import AppConfig

config = AppConfig(agents={"chat": False, "planner": False, "coder": True})
service = AgentService(config)
service.initialize()

assert "chat" not in service.manager.list_agents()
assert "planner" not in service.manager.list_agents()
assert "coder" in service.manager.list_agents()

For a full end-to-end workflow, use AgentService.execute():

result = await service.execute("Build a Flask API")
print(result["plan"])
print(result["results"])

Tool Actions

Specialist agents do not only return text; they now call tools through the injected ToolService:

  • coder, writes generated code with WriteFileTool and applies edits with ApplyEditTool
  • tester, runs RunPytestTool and RunPythonTool to verify changes
  • debugger, analyses output and applies suggested fixes with ApplyEditTool
  • documentation, writes or updates docs with WriteFileTool

The result object returned by each agent includes the outcome of the tool calls, including generated files, test results, and applied edits.

Development Instructions

Adding a New Agent

  1. Create a class in novacoder/agents/ extending Agent.
  2. Set name and description class attributes.
  3. Implement async def run(self, task: AgentTask) -> AgentResult.
  4. Use injected self._ai, self._tools, self._memory, and self._workspace to access runtime services.
  5. Register the agent in AgentManager._register_defaults() in novacoder/agents/manager.py.
  6. Add tests in tests/test_agents.py or a new test file.
  7. Update this wiki page and the CLI help text if relevant.

Agent Template

from novacoder.agents.agent import Agent, AgentResult, AgentTask

class MyAgent(Agent):
    name = "my_agent"
    description = "Performs a specialized task."

    async def run(self, task: AgentTask) -> AgentResult:
        # Access task.goal, task.description, task.context
        # Access self._ai, self._tools, self._memory, self._workspace
        return AgentResult(
            success=True,
            output={"done": True},
            summary=f"Processed {task.goal}",
        )

Agent Testing

def test_my_agent():
    agent = MyAgent()
    task = AgentTask(id="1", description="Test", goal="Test")
    result = agent.run(task)
    assert result.success
    assert result.summary

Agent Collaboration

Agents should not call each other directly. Instead, the manager or planner dispatches tasks and combines results. Use the event bus for notifications such as AgentFinished.

Error Handling

If an agent cannot complete a task, return AgentResult(success=False, errors=[...]) with a descriptive error. Do not raise exceptions unless the failure is unrecoverable.

Enhanced Error Handling (August 2026):

All specialist agents now include comprehensive error handling and logging:

  • AI Service Validation: Agents check if AI provider is available before attempting calls
  • Exception Handling: Try-catch blocks around all AI service calls with detailed error logging
  • Informative Error Messages: Clear error messages when AI service is unavailable or fails
  • Logging Integration: All agent operations are logged for debugging and monitoring
  • Graceful Degradation: Agents return structured error results instead of silent failures

Example error handling pattern:

if self._ai is not None:
    try:
        response = await self._ai.chat(messages)
        logger.info(f"Agent successfully processed task: {task.goal}")
    except Exception as e:
        logger.error(f"Agent AI call failed: {e}", exc_info=True)
        return AgentResult(
            success=False,
            errors=[f"AI service error: {str(e)}"],
            output=None,
            summary="Task failed due to AI service error"
        )
else:
    logger.warning(f"Agent: AI provider not available for task: {task.goal}")
    return AgentResult(
        success=False,
        errors=["AI provider not available - please ensure AI service is configured and running"],
        output=None,
        summary="Task failed - AI provider unavailable"
    )

Discovery Notes

During the latest system-wide debug pass, the default plan produced by PlannerEngine referenced architect and tester, but those agents were not registered in AgentManager. This caused any execution of the default plan to fail when it reached those agents. The following agents were added and registered in novacoder/agents/manager.py:

  • architect
  • tester
  • debugger
  • documentation

All agents referenced in the default plan are now runnable. The registration test in tests/test_agents.py verifies the complete set of default agents.

Future Agents

(None currently - all planned agents have been implemented)

  • Planner
  • Tools
  • AI Runtime
  • Agent Communication
  • Agent Learning
  • Agent Orchestration
  • Agent Testing
  • Agent Error Recovery
  • Agent State Management
  • Agent Monitoring
  • Agent Security Validation
  • Agent Cost Tracking
  • Agent Collaboration
  • Agent Performance Optimization
  • Agent Documentation Automation
  • Agent DevOps
  • Agent Database
  • Agent Mobile
  • Agent UI/UX
  • Agent Data Science
  • Agent API Design
  • Agent Git
  • Agent Compliance
  • Agent Marketplace
  • Agent Versioning
  • Agent Sandboxing
  • Agent Task Distribution
  • Agent Access Control
  • Agent Input Validation
  • Agent Pooling
  • Agent Execution Pool
  • Agent Memory Management
  • Agent Profiling
  • Agent Benchmarks

REST API, Enablement & Distribution

Agent enablement is runtime-toggleable via AgentService.set_agent_enabled(name, enabled) (registration is driven by a _build_agent_factories() name→factory map):

Method Path Description
GET /api/agents/states Per-agent enabled/registered state
POST /api/agents/{name}/enable / disable Register/unregister at runtime; persists agents.<name> to user.yaml
GET /api/agents/distribution/statistics TaskDistributor strategy/queue/outcome stats (404 when agents.enable_task_distribution=false)
POST /api/agents/distribution/strategy Set distribution strategy (round_robin, least_loaded, capability_match, performance_based, priority_queue, affinity, distributed)

UI: Enablement card on the Agents page; the Chat agent selector reads GET /api/agents dynamically. ChatRequest and POST /api/stream validate/route against the live registry.

Source: wiki/agents.md · rendered 2026-11-10