Skip to main content

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:
  1. Agent Spawning: Creates new agent tasks
  2. Registry Management: Tracks running agents by session ID
  3. Global Permissions: Shares permission rules across all agents
  4. Lifecycle Control: Shutdown individual or all agents

Spawning Agents

Basic Spawn

Spawn with Local Rules

Add agent-specific permission rules:
Local rules only apply to this specific agent.

What Happens During Spawn

  1. Task Creation: Agent is spawned as a tokio::task
  2. Registry Entry: Session ID is added to the runtime’s registry
  3. Handle Creation: Returns an AgentHandle for communication
  4. 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

What happens during shutdown:
  1. Agent receives InputMessage::Shutdown
  2. Current operation completes (if safe)
  3. Session is saved to disk
  4. Agent task exits
  5. Registry entry is removed

Shutdown All Agents

Useful for application cleanup.

Interrupt vs Shutdown

Interrupt (temporary):
  • Cancels current operation
  • Agent stays alive
  • Can receive new input
Shutdown (permanent):
  • 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

Common 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
Internal synchronization is handled automatically.

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