Agent Models Documentation
Overview​
The Agent models form the core of CODITECT's autonomous development system, enabling AI-powered software creation through orchestrated agent teams. The system consists of three interconnected models:
- AgentConfig: Defines agent capabilities, AI provider configurations, and team structures
- AgentInstance: Manages runtime instances of agents with resource tracking and health monitoring
- AgentExecution: Tracks individual task executions with detailed inputs, outputs, and metrics
AgentConfig Model​
Purpose​
AgentConfig represents the blueprint for AI agents, defining their type, capabilities, provider settings, and team compositions. It supports multiple AI providers (Claude, Gemini, Ollama, HuggingFace) with provider-specific configurations.
Model Structure​
Core Fields​
| Field | Type | Description | Constraints |
|---|---|---|---|
agent_id | UUID | Unique agent configuration identifier | Primary key, auto-generated |
tenant_id | UUID | Associated tenant | Foreign key to Tenant |
name | String | Agent display name | Required, human-readable |
agent_type | AgentType (Enum) | Functional category | Required, determines capabilities |
provider | AIProvider (Enum) | AI service provider | Required, includes model settings |
capabilities | Vec | What the agent can do | Auto-set based on type |
status | AgentStatus (Enum) | Current availability | Required |
settings | AgentSettings | Configuration parameters | Required, provider-specific |
created_at | DateTime | Creation timestamp | Auto-set |
updated_at | DateTime | Last modification | Auto-updated |
last_active_at | DateTime | Last task execution | Updated on task assignment |
AgentType Enum​
enum AgentType {
TestWriter, // Creates comprehensive test suites following TDD principles
Coder, // Implements code to pass tests
Reviewer, // Reviews code for quality and security
Security, // Detects and analyzes security vulnerabilities
Architecture, // Makes architectural decisions and generates ADRs
Documenter, // Maintains documentation and guides
Orchestrator, // Orchestrates multi-agent workflows
QualityControl // Final quality assurance checks
}
AgentCapability Enum​
enum AgentCapability {
WriteUnitTests, // Can write unit tests
WriteIntegrationTests, // Can write integration tests
ImplementCode, // Can implement code features
ReviewCode, // Can review code for quality
AnalyzeSecurity, // Can analyze security vulnerabilities
DesignArchitecture, // Can make architectural decisions
GenerateDocumentation, // Can generate documentation
OrchestrateAgents, // Can orchestrate other agents
QualityAssurance, // Can perform quality checks
OptimizePerformance // Can optimize performance
}
AgentStatus Enum​
enum AgentStatus {
Available, // Agent is available for new tasks
Busy, // Agent is currently working on a task
Starting, // Agent is starting up
Stopping, // Agent is shutting down
Error, // Agent encountered an error
Offline // Agent is offline
}
AIProvider Enum​
enum AIProvider {
Claude { model: String, max_tokens: u32 },
Gemini { model: String, max_tokens: u32 },
Ollama { model: String, endpoint: String },
HuggingFace { model: String, api_key: String }
}
AgentSettings Structure​
| Field | Type | Description | Default |
|---|---|---|---|
temperature | f32 | AI model temperature (0.0-1.0) | Varies by agent type |
max_tokens | u32 | Maximum tokens per request | 4096 |
cost_per_1k_tokens | f32 | Cost per 1000 tokens (cents) | Provider-specific |
max_retries | u32 | Maximum retries on failure | 3 |
timeout_seconds | u64 | Request timeout | 120 |
custom_prompts | HashMap<String, String> | Custom instructions | Empty |
Agent Teams​
AgentTeam Structure​
| Field | Type | Description |
|---|---|---|
team_id | UUID | Unique team identifier |
tenant_id | UUID | Associated tenant |
name | String | Team name |
description | String | Team purpose |
members | Vec | Team composition |
workflow_stages | Vec | Execution stages |
created_at | DateTime | Creation timestamp |
updated_at | DateTime | Last modification |
Default Capabilities by Type​
- TestWriter: WriteUnitTests, WriteIntegrationTests
- Coder: ImplementCode, OptimizePerformance
- Reviewer: ReviewCode, QualityAssurance
- Security: AnalyzeSecurity, ReviewCode
- Architecture: DesignArchitecture, ReviewCode
- Documenter: GenerateDocumentation
- Orchestrator: OrchestrateAgents
- QualityControl: QualityAssurance, ReviewCode
AgentInstance Model​
Purpose​
AgentInstance represents a running instance of an agent configuration, managing lifecycle, resource usage, health monitoring, and task assignments. Instances can run on various platforms (Cloud Run, Kubernetes, Docker, Local).
Model Structure​
Core Fields​
| Field | Type | Description | Constraints |
|---|---|---|---|
instance_id | UUID | Unique instance identifier | Primary key, auto-generated |
agent_id | UUID | Reference to agent configuration | Foreign key to AgentConfig |
tenant_id | UUID | Associated tenant | Foreign key to Tenant |
state | InstanceState (Enum) | Current runtime state | Required |
assigned_task_id | UUID (Optional) | Currently assigned task | Foreign key to Task |
metadata | InstanceMetadata | Runtime information | Required |
resources | ResourceUsage | Resource tracking | Auto-updated |
created_at | DateTime | Instance creation | Auto-set |
updated_at | DateTime | Last state change | Auto-updated |
task_started_at | DateTime | Task start time | Set on task assignment |
health | HealthStatus | Health monitoring | Auto-updated |
InstanceState Enum​
enum InstanceState {
Provisioning, // Instance is being created
Starting, // Instance is starting up
Idle, // Instance is ready for work
Working, // Instance is working on a task
Paused, // Instance is paused
Stopping, // Instance is shutting down
Terminated, // Instance has been terminated
Failed // Instance encountered an error
}
Valid State Transitions​
Provisioning -> Starting -> Idle <-> Working
| |
v v
Paused -> Working
|
v
Any State -> Stopping -> Terminated
Any State -> Failed
InstanceMetadata Structure​
| Field | Type | Description |
|---|---|---|
runtime_id | String | Container/process identifier |
region | String | Deployment region |
runtime_type | RuntimeType | Execution environment |
environment | HashMap<String, String> | Environment variables |
agent_version | String | Agent code version |
provider_metadata | HashMap<String, Value> | Provider-specific data |
ResourceUsage Structure​
| Field | Type | Description | Updated |
|---|---|---|---|
cpu_percent | f32 | CPU usage (0-100) | Real-time |
memory_mb | u32 | Memory usage in MB | Real-time |
tokens_used | u64 | Total tokens consumed | Cumulative |
api_calls | u32 | Total API calls made | Cumulative |
cost_accrued | f32 | Total cost in dollars | Cumulative |
last_updated | DateTime | Last metric update | On update |
HealthStatus Structure​
| Field | Type | Description |
|---|---|---|
is_healthy | bool | Current health state |
last_check | DateTime | Last health check time |
failure_count | u32 | Consecutive failures |
error_message | String (Optional) | Error details if unhealthy |
Lifecycle Management​
- Automatic Termination: Instances idle for >N minutes
- Health Monitoring: Failed health checks after 3 attempts → Failed state
- Resource Limits: Configurable CPU, memory, and token limits
- Audit Trail: All state changes logged as LifecycleEvents
AgentExecution Model​
Purpose​
AgentExecution tracks individual task executions by agent instances, capturing detailed inputs, outputs, tool usage, quality metrics, and resource consumption. It provides complete traceability for AI-generated code and decisions.
Model Structure​
Core Fields​
| Field | Type | Description | Constraints |
|---|---|---|---|
execution_id | UUID | Unique execution identifier | Primary key, auto-generated |
instance_id | UUID | Executing instance | Foreign key to AgentInstance |
task_id | UUID | Task being executed | Foreign key to Task |
tenant_id | UUID | Associated tenant | Foreign key to Tenant |
status | ExecutionStatus (Enum) | Current state | Required |
input | ExecutionInput | Task input details | Required |
output | ExecutionOutput (Optional) | Execution results | Set on completion |
error | ExecutionError (Optional) | Error information | Set on failure |
metadata | ExecutionMetadata | Execution context | Required |
resource_usage | ExecutionResourceUsage | Resource tracking | Auto-updated |
created_at | DateTime | Creation timestamp | Auto-set |
started_at | DateTime | Execution start | Set on start |
completed_at | DateTime | Completion time | Set on finish |
ExecutionStatus Enum​
enum ExecutionStatus {
Queued, // Execution is queued
Starting, // Execution is starting
Running, // Execution is running
Completed, // Execution completed successfully
Failed, // Execution failed
Cancelled, // Execution was cancelled
TimedOut // Execution timed out
}
ExecutionInput Structure​
| Field | Type | Description |
|---|---|---|
prompt | String | Main instruction to agent |
system_message | String (Optional) | System-level context |
context | Vec | Files, docs, previous results |
parameters | ExecutionParameters | Execution settings |
tools | Vec | Available tools |
ContextItem Structure​
struct ContextItem {
context_type: ContextType, // Type of context
name: String, // Identifier
content: String, // Content
mime_type: Option<String> // MIME type
}
enum ContextType {
SourceCode, // Source code file
Documentation, // Documentation
Configuration, // Config file
TestFile, // Test file
DataFile, // Data file
PreviousResult, // Previous execution result
ApiResponse // External API response
}
ExecutionOutput Structure​
| Field | Type | Description |
|---|---|---|
result | String | Primary text output |
data | Value (Optional) | Structured data |
files | Vec | Files created/modified |
tool_calls | Vec | Tools used during execution |
reasoning | String (Optional) | Agent's thought process |
quality_metrics | QualityMetrics | Output quality scores |
QualityMetrics Structure​
| Field | Type | Description | Range |
|---|---|---|---|
confidence | f32 | Confidence in output | 0.0-1.0 |
completeness | f32 | Task completion | 0.0-1.0 |
code_quality | f32 (Optional) | Code quality score | 0.0-1.0 |
test_coverage | f32 (Optional) | Test coverage | 0.0-1.0 |
performance | f32 | Performance score | 0.0-1.0 |
Tool Integration​
struct ToolDefinition {
name: String,
description: String,
schema: JsonValue, // JSON Schema
handler: ToolHandler
}
enum ToolHandler {
Http { url: String, method: String, headers: HashMap<String, String> },
Internal { function: String, module: String },
External { service: String, endpoint: String, auth: Option<String> }
}
struct ToolCall {
tool: String,
input: JsonValue,
output: JsonValue,
duration_ms: u64,
success: bool,
error: Option<String>
}
Database Schema​
Primary Storage Patterns​
# Agent Configurations
Key: /{tenant_id}/agents/{agent_id}
Value: JSON serialized AgentConfig
# Agent Instances
Key: /{tenant_id}/agent_instances/{instance_id}
Value: JSON serialized AgentInstance
# Agent Executions
Key: /{tenant_id}/agent_executions/{execution_id}
Value: JSON serialized AgentExecution
# Agent Teams
Key: /{tenant_id}/agent_teams/{team_id}
Value: JSON serialized AgentTeam
Secondary Indexes​
# Agents by type
/{tenant_id}/agents_by_type/{agent_type} -> [agent_ids]
# Agents by status
/{tenant_id}/agents_by_status/{status} -> [agent_ids]
# Instances by agent
/{tenant_id}/instances_by_agent/{agent_id} -> [instance_ids]
# Active instances
/{tenant_id}/active_instances -> [instance_ids]
# Executions by task
/{tenant_id}/executions_by_task/{task_id} -> [execution_ids]
# Executions by instance
/{tenant_id}/executions_by_instance/{instance_id} -> [execution_ids]
Lifecycle Event Storage​
Key: /{tenant_id}/agent_lifecycle/{instance_id}/{timestamp}:{event_id}
Value: LifecycleEvent object
Related Code​
Source Files​
- Models:
/src/models/agent_config.rs- AgentConfig and team definitions/src/models/agent_instance.rs- AgentInstance and lifecycle/src/models/agent_execution.rs- AgentExecution tracking
- Repositories:
/src/db/repositories/agent_config_repository.rs/src/db/repositories/agent_instance_repository.rs/src/db/repositories/agent_execution_repository.rs
- API Handlers:
/src/api/handlers/agent_handlers.rs- REST endpoints
- Services:
/src/services/agent_orchestration_service.rs/src/services/agent_execution_service.rs
Key Methods​
AgentConfig​
impl AgentConfig {
fn new(tenant_id: Uuid, name: String, agent_type: AgentType, provider: AIProvider) -> Self
fn default_capabilities(agent_type: AgentType) -> Vec<AgentCapability>
fn default_settings(provider: &AIProvider, agent_type: AgentType) -> AgentSettings
fn update_status(&mut self, status: AgentStatus)
fn add_capability(&mut self, capability: AgentCapability) -> bool
fn estimate_cost(&self, tokens: u32) -> f32
}
AgentInstance​
impl AgentInstance {
fn new(...) -> Self
fn transition_state(&mut self, new_state: InstanceState) -> Result<()>
fn assign_task(&mut self, task_id: Uuid) -> Result<()>
fn complete_task(&mut self) -> Result<()>
fn update_resources(&mut self, ...)
fn update_health(&mut self, is_healthy: bool, error: Option<String>)
fn should_terminate_for_inactivity(&self, timeout_minutes: i64) -> bool
}
AgentExecution​
impl AgentExecution {
fn new(...) -> Self
fn start(&mut self) -> Result<()>
fn mark_running(&mut self) -> Result<()>
fn complete(&mut self, output: ExecutionOutput) -> Result<()>
fn fail(&mut self, error: ExecutionError) -> Result<()>
fn cancel(&mut self) -> Result<()>
fn is_finished(&self) -> bool
fn duration_seconds(&self) -> Option<f64>
}
API Endpoints​
Agent Configuration Management​
- POST
/api/agents- Create new agent configuration - GET
/api/agents/{agent_id}- Get agent details - PUT
/api/agents/{agent_id}- Update agent configuration - DELETE
/api/agents/{agent_id}- Delete agent (if no active instances) - GET
/api/agents?type={type}&status={status}- List agents
Agent Instance Management​
- POST
/api/agents/{agent_id}/instances- Create new instance - GET
/api/agent-instances/{instance_id}- Get instance details - PUT
/api/agent-instances/{instance_id}/state- Update instance state - DELETE
/api/agent-instances/{instance_id}- Terminate instance - GET
/api/agent-instances?agent_id={id}&state={state}- List instances
Agent Execution Tracking​
- GET
/api/agent-executions/{execution_id}- Get execution details - GET
/api/agent-executions?task_id={id}&status={status}- List executions - POST
/api/agent-executions/{execution_id}/cancel- Cancel execution
Agent Teams​
- POST
/api/agent-teams- Create team - GET
/api/agent-teams/{team_id}- Get team details - PUT
/api/agent-teams/{team_id}/members- Update team members - POST
/api/agent-teams/{team_id}/execute- Execute team workflow
Use Cases​
TDD Development Workflow​
1. TestWriter agent creates comprehensive test suite
2. Coder agent implements code to pass tests
3. Reviewer agent checks code quality
4. Security agent scans for vulnerabilities
5. QualityControl agent performs final checks
Architecture Design​
1. Architecture agent analyzes requirements
2. Generates ADR (Architecture Decision Record)
3. Creates system design diagrams
4. Documenter agent creates technical docs
Bug Fix Workflow​
1. Orchestrator agent analyzes bug report
2. TestWriter creates failing test case
3. Coder implements fix
4. Reviewer validates solution
5. Documenter updates relevant docs
Security Considerations​
Agent Isolation​
- Each instance runs in isolated container
- Limited network access (allowlisted endpoints)
- No access to production data
- Audit trail for all actions
Resource Limits​
- Token limits per execution
- Memory and CPU caps
- Timeout enforcement
- Cost tracking and limits
Access Control​
- Agents inherit tenant isolation
- API key rotation for providers
- Encrypted storage of credentials
- Role-based agent management
Performance Optimizations​
Instance Pooling​
- Pre-warmed instances for common agent types
- Automatic scaling based on load
- Regional deployment for latency
- Instance recycling after N executions
Caching​
- Model response caching for similar inputs
- Tool result caching
- Context embedding reuse
- Compiled prompt templates
Resource Management​
- Automatic instance termination on idle
- Resource usage monitoring
- Cost optimization algorithms
- Provider failover support
Monitoring & Observability​
Metrics​
- Execution success/failure rates
- Average execution duration
- Token usage by agent type
- Cost per task category
- Instance utilization
Alerts​
- High failure rate
- Resource limit approaching
- Provider API errors
- Instance health degradation
- Cost threshold exceeded
Future Enhancements​
Advanced Capabilities​
- Multi-modal Agents: Support for image/video processing
- Long-running Tasks: Checkpoint and resume support
- Agent Learning: Feedback incorporation for improvement
- Custom Agent Types: User-defined agent configurations
Integration Features​
- IDE Plugins: Direct agent invocation from IDEs
- CI/CD Integration: Agents in build pipelines
- External Tool Support: Broader tool ecosystem
- Agent Marketplace: Sharing agent configurations
Optimization​
- Fine-tuned Models: Task-specific model training
- Edge Deployment: Local agent execution
- Hybrid Execution: Mix of cloud and local agents
- Predictive Scaling: ML-based resource prediction
Last Updated: 2025-08-29 Version: 1.0