> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Managed Runtime Protocol

> Protocol for remote agent runtime where the entire loop runs on managed infrastructure

Managed Runtime Protocol defines the interface for remote agent execution where the entire agent loop runs on provider infrastructure.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TD
    subgraph "Protocol Decision Tree"
        A[🚀 Agent Execution Need] --> B{Where should agent loop run?}
        B -->|Local| C[ManagedBackendProtocol]
        B -->|Remote| D[ManagedRuntimeProtocol]
        
        C --> E[🖥️ SandboxedAgent<br/>Local loop, optional tool sandboxing]
        D --> F[☁️ AnthropicManagedAgent<br/>Remote loop + tools]
        D --> G[☁️ E2BManagedAgent<br/>Remote loop + tools]
        D --> H[☁️ ModalManagedAgent<br/>Remote loop + tools]
    end
    
    classDef decision fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef local fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef remote fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef provider fill:#189AB4,stroke:#7C90A0,color:#fff
    
    class A,B decision
    class C,E local
    class D,F,G,H remote
```

## Quick Start

<Steps>
  <Step title="Basic Lifecycle">
    Create agent, environment, session, then send events and stream responses.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import AnthropicManagedAgent, ManagedConfig

    runtime = AnthropicManagedAgent(config=ManagedConfig(
        model="claude-sonnet-4-6",
        system="You are a coding assistant.",
    ))

    # Create infrastructure
    agent_id = await runtime.create_agent(config)
    env_id = await runtime.create_environment(config)
    session_id = await runtime.create_session(agent_id, env_id)

    # Send message and stream responses
    await runtime.send_event(session_id, {
        "type": "user.message",
        "content": [{"type": "text", "text": "Hello!"}]
    })

    async for event in runtime.stream_events(session_id):
        if event["type"] == "agent.message":
            print(event["content"])
    ```
  </Step>

  <Step title="With Advanced Configuration">
    Full configuration with packages, networking, and vaults.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import AnthropicManagedAgent, ManagedConfig, NetworkingConfig, PackagesConfig

    runtime = AnthropicManagedAgent(config=ManagedConfig(
        model="claude-sonnet-4-6",
        system="You are a data analysis expert.",
        packages=PackagesConfig(
            pip=["pandas", "numpy", "matplotlib"],
            npm=["express"]
        ),
        networking=NetworkingConfig(
            type="limited",
            allowed_hosts=["api.example.com"],
            allow_mcp_servers=True
        ),
        vault_ids=["vault_github_123"]  # OAuth credentials
    ))

    # Full lifecycle with session management
    agent_id = await runtime.create_agent(config)
    env_id = await runtime.create_environment(config) 
    session_id = await runtime.create_session(agent_id, env_id)

    await runtime.send_event(session_id, {
        "type": "user.message",
        "content": [{"type": "text", "text": "Analyze sales data from GitHub repo"}]
    })

    # Handle events
    async for event in runtime.stream_events(session_id):
        if event["type"] == "agent.message":
            print(f"Agent: {event['content']}")
        elif event["type"] == "session.status_idle":
            break
    ```
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Runtime
    participant Agent
    participant Environment
    participant Session
    
    User->>Runtime: create_agent(config)
    Runtime->>Agent: Deploy agent definition
    Agent-->>Runtime: agent_id
    
    User->>Runtime: create_environment(config)
    Runtime->>Environment: Provision container/sandbox
    Environment-->>Runtime: environment_id
    
    User->>Runtime: create_session(agent_id, env_id)
    Runtime->>Session: Start agent in environment
    Session-->>Runtime: session_id
    
    User->>Runtime: send_event(session_id, message)
    Runtime->>Session: Forward user message
    Session->>Session: Agent processes message
    Session-->>Runtime: Stream events
    Runtime-->>User: Event stream
```

| Component       | Responsibility                           | Location          |
| --------------- | ---------------------------------------- | ----------------- |
| **Agent**       | Model, system prompt, tool definitions   | Remote provider   |
| **Environment** | Runtime container, packages, networking  | Remote provider   |
| **Session**     | Running instance of agent-in-environment | Remote provider   |
| **Runtime**     | Protocol implementation, API client      | Local (your code) |

***

## Protocol Methods

### Agent Management

| Method                     | Purpose                 | Returns                |
| -------------------------- | ----------------------- | ---------------------- |
| `create_agent(config)`     | Deploy agent definition | `agent_id: str`        |
| `retrieve_agent(agent_id)` | Get agent metadata      | `Dict[str, Any]`       |
| `list_agents(**filters)`   | List all agents         | `List[Dict[str, Any]]` |
| `archive_agent(agent_id)`  | Mark agent inactive     | `None`                 |

### Environment Management

| Method                         | Purpose                   | Returns                |
| ------------------------------ | ------------------------- | ---------------------- |
| `create_environment(config)`   | Provision sandbox         | `environment_id: str`  |
| `retrieve_environment(env_id)` | Get environment metadata  | `Dict[str, Any]`       |
| `list_environments(**filters)` | List all environments     | `List[Dict[str, Any]]` |
| `archive_environment(env_id)`  | Mark environment inactive | `None`                 |
| `delete_environment(env_id)`   | Destroy environment       | `None`                 |

### Session Management

| Method                             | Purpose               | Returns                |
| ---------------------------------- | --------------------- | ---------------------- |
| `create_session(agent_id, env_id)` | Start agent session   | `session_id: str`      |
| `retrieve_session(session_id)`     | Get session status    | `Dict[str, Any]`       |
| `list_sessions(**filters)`         | List all sessions     | `List[Dict[str, Any]]` |
| `archive_session(session_id)`      | Mark session inactive | `None`                 |
| `delete_session(session_id)`       | Delete session data   | `None`                 |

### Event Handling

| Method                          | Purpose                 | Returns                         |
| ------------------------------- | ----------------------- | ------------------------------- |
| `send_event(session_id, event)` | Send message to session | `None`                          |
| `stream_events(session_id)`     | Stream responses        | `AsyncIterator[Dict[str, Any]]` |
| `interrupt(session_id)`         | Stop current processing | `None`                          |

***

## Common Patterns

### Multi-Turn Conversation

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Create infrastructure once
agent_id = await runtime.create_agent(config)
env_id = await runtime.create_environment(config)
session_id = await runtime.create_session(agent_id, env_id)

# Multiple turns
for user_input in conversation:
    await runtime.send_event(session_id, {
        "type": "user.message",
        "content": [{"type": "text", "text": user_input}]
    })
    
    async for event in runtime.stream_events(session_id):
        if event["type"] == "agent.message":
            print(event["content"])
        elif event["type"] == "session.status_idle":
            break  # Ready for next input
```

### Agent Version Pinning

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Pin to specific agent version
runtime = AnthropicManagedAgent(config=config)
runtime.agent_version = 5  # Use version 5

# Session will use pinned version
session_id = await runtime.create_session(agent_id, env_id)
```

### Session Cleanup

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Archive preserves data but marks inactive
await runtime.archive_session(session_id)

# Delete removes all data permanently
await runtime.delete_session(session_id)

# List sessions with filters
active_sessions = await runtime.list_sessions(status="active")
archived_sessions = await runtime.list_sessions(status="archived")
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Resource Management">
    Create agents and environments once, reuse across sessions:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Create once
    agent_id = await runtime.create_agent(config)
    env_id = await runtime.create_environment(config)

    # Reuse for multiple sessions
    session1 = await runtime.create_session(agent_id, env_id)
    session2 = await runtime.create_session(agent_id, env_id)
    ```
  </Accordion>

  <Accordion title="Error Handling">
    Handle network failures and provider errors gracefully:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    try:
        await runtime.send_event(session_id, event)
    except Exception as e:
        # Check if session still exists
        try:
            session = await runtime.retrieve_session(session_id)
            # Session exists, retry
        except:
            # Session lost, recreate
            session_id = await runtime.create_session(agent_id, env_id)
    ```
  </Accordion>

  <Accordion title="Event Processing">
    Handle different event types appropriately:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    async for event in runtime.stream_events(session_id):
        match event["type"]:
            case "agent.message":
                handle_message(event["content"])
            case "agent.tool_use":
                handle_tool_call(event)
            case "session.status_idle":
                break  # Agent finished processing
            case "session.error":
                handle_error(event)
    ```
  </Accordion>

  <Accordion title="Performance Optimization">
    * Reuse agent/environment definitions across sessions
    * Use appropriate session cleanup (archive vs delete)
    * Pin agent versions for consistent behavior
    * Filter list operations to reduce API calls
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Sandboxed Agent" icon="sandbox" href="/docs/features/sandboxed-agent">
    Local agent loop with optional tool sandboxing
  </Card>

  <Card title="Managed Agent Lifecycle" icon="recycle" href="/docs/features/managed-agent-lifecycle">
    Complete CRUD operations for agents, environments, sessions
  </Card>
</CardGroup>
