AgentRuntime
The AgentRuntime is the central orchestrator that manages all agent lifecycles. It provides a registry of running agents and coordinates their execution.Creating a Runtime
Key Responsibilities
The runtime handles:- Agent Spawning: Creates new agent tasks
- Registry Management: Tracks running agents by session ID
- Global Permissions: Shares permission rules across all agents
- Lifecycle Control: Shutdown individual or all agents
Spawning Agents
Basic Spawn
Spawn with Local Rules
Add agent-specific permission rules:What Happens During Spawn
- Task Creation: Agent is spawned as a
tokio::task - Registry Entry: Session ID is added to the runtime’s registry
- Handle Creation: Returns an
AgentHandlefor communication - Async Execution: Agent starts running in the background
Agent Lifecycle States
State Enum
State Transitions
Monitoring State
State Change Events
Subscribe to state changes:Registry Management
Getting Agents
Checking Existence
Shutdown
Shutdown Individual Agent
- Agent receives
InputMessage::Shutdown - Current operation completes (if safe)
- Session is saved to disk
- Agent task exits
- Registry entry is removed
Shutdown All Agents
Interrupt vs Shutdown
Interrupt (temporary):- Cancels current operation
- Agent stays alive
- Can receive new input
- Terminates the agent
- Must spawn new agent to continue
- Saves final state
Multiple Agents
Independent Agents
Multiple agents run completely independently:Shared Resources
Agents can share resources safely:Parent-Child Relationships
Agents can spawn subagents:Global Permissions
Setting Global Rules
Global rules apply to ALL agents:Adding Rules at Runtime
Permission Hierarchy
Error Handling
Spawn Errors
- Session ID already in use
- Invalid session configuration
- Resource allocation failure
Agent Errors
Monitor for errors during execution:Graceful Degradation
Thread Safety
Runtime Cloning
The runtime is thread-safe and can be cloned:Concurrent Access
Multiple threads can safely:- Spawn agents
- Get agents from registry
- List running agents
- Shutdown agents
Best Practices
1. One Runtime Per Application
2. Check Before Spawning
3. Clean Shutdown
4. Handle Errors
5. Monitor State
Advanced Patterns
Lazy Agent Initialization
Agent Pool
Health Checks
Next Steps
Sessions & Persistence
Learn how conversation state is persisted
Message Flow
Understand input/output communication
Agent States
Deep dive into all agent states
AgentHandle API
Complete handle API reference