架构与安全(2/2)

High-level architecture of action security analysis and validation

The Security system evaluates agent actions for potential risks before execution. It provides pluggable security analyzers that assess action risk levels and enforce confirmation policies based on security characteristics.

Source: openhands-sdk/penhands/sdk/security/

Core Responsibilities

The Security system has four primary responsibilities:

  1. Risk Assessment - Capture and validate LLM-provided risk levels for actions
  2. Confirmation Policy - Determine when user approval is required based on risk
  3. Action Validation - Enforce security policies before execution
  4. Audit Trail - Record security decisions in event history

Architecture

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 25, "rankSpacing": 50}} }%%
flowchart TB
    subgraph Interface["Abstract Interface"]
        Base["SecurityAnalyzerBase<br><i>Abstract analyzer</i>"]
    end

    subgraph Implementations["Concrete Analyzers"]
        LLM["LLMSecurityAnalyzer<br><i>Inline risk prediction</i>"]
        NoOp["NoOpSecurityAnalyzer<br><i>No analysis</i>"]
    end

    subgraph Risk["Risk Levels"]
        Low["LOW<br><i>Safe operations</i>"]
        Medium["MEDIUM<br><i>Moderate risk</i>"]
        High["HIGH<br><i>Dangerous ops</i>"]
        Unknown["UNKNOWN<br><i>Unanalyzed</i>"]
    end

    subgraph Policy["Confirmation Policy"]
        Check["should_require_confirmation()"]
        Mode["Confirmation Mode"]
        Decision["Require / Allow"]
    end

    Base --> LLM
    Base --> NoOp

    Implementations --> Low
    Implementations --> Medium
    Implementations --> High
    Implementations --> Unknown

    Low --> Check
    Medium --> Check
    High --> Check
    Unknown --> Check

    Check --> Mode
    Mode --> Decision

    classDef primary fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px
    classDef secondary fill:#e8f3ff,stroke:#2b6cb0,stroke-width:2px
    classDef tertiary fill:#fff4df,stroke:#b7791f,stroke-width:2px
    classDef danger fill:#ffe8e8,stroke:#dc2626,stroke-width:2px

    class Base primary
    class LLM secondary
    class High danger
    class Check tertiary

Key Components

Component Purpose Design
SecurityAnalyzerBase Abstract interface Defines security_risk() contract
LLMSecurityAnalyzer Inline risk assessment Returns LLM-provided risk from action arguments
NoOpSecurityAnalyzer Passthrough analyzer Always returns UNKNOWN
SecurityRisk Risk enum LOW, MEDIUM, HIGH, UNKNOWN
ConfirmationPolicy Decision logic Maps risk levels to confirmation requirements

Risk Levels

Security analyzers return one of four risk levels:

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30}} }%%
flowchart TB
    Action["ActionEvent"]
    Analyze["Security Analyzer"]

    subgraph Levels["Risk Levels"]
        Low["LOW<br><i>Read-only, safe</i>"]
        Medium["MEDIUM<br><i>Modify files</i>"]
        High["HIGH<br><i>Delete, execute</i>"]
        Unknown["UNKNOWN<br><i>Not analyzed</i>"]
    end

    Action --> Analyze
    Analyze --> Low
    Analyze --> Medium
    Analyze --> High
    Analyze --> Unknown

    style Low fill:#d1fae5,stroke:#10b981,stroke-width:2px
    style Medium fill:#fef3c7,stroke:#f59e0b,stroke-width:2px
    style High fill:#ffe8e8,stroke:#dc2626,stroke-width:2px
    style Unknown fill:#f3f4f6,stroke:#6b7280,stroke-width:2px

Risk Level Definitions

Level Characteristics Examples
LOW Read-only, no state changes File reading, directory listing, search
MEDIUM Modifies user data File editing, creating files, API calls
HIGH Dangerous operations File deletion, system commands, privilege escalation
UNKNOWN Not analyzed or indeterminate Complex commands, ambiguous operations

Security Analyzers

LLMSecurityAnalyzer

Leverages the LLM's inline risk assessment during action generation:

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30, "rankSpacing": 40}} }%%
flowchart TB
    Schema["Tool Schema<br><i>+ security_risk param</i>"]
    LLM["LLM generates action<br>with security_risk"]
    ToolCall["Tool Call Arguments<br>{command: 'rm -rf', security_risk: 'HIGH'}"]
    Extract["Extract security_risk<br>from arguments"]
    ActionEvent["ActionEvent<br>with security_risk set"]
    Analyzer["LLMSecurityAnalyzer<br>returns security_risk"]

    Schema --> LLM
    LLM --> ToolCall
    ToolCall --> Extract
    Extract --> ActionEvent
    ActionEvent --> Analyzer

    style Schema fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px
    style Extract fill:#e8f3ff,stroke:#2b6cb0,stroke-width:2px
    style Analyzer fill:#fff4df,stroke:#b7791f,stroke-width:2px

Analysis Process:

  1. Schema Enhancement: A required security_risk parameter is added to each tool's schema
  2. LLM Generation: The LLM generates tool calls with security_risk as part of the arguments
  3. Risk Extraction: The agent extracts the security_risk value from the tool call arguments
  4. ActionEvent Creation: The security risk is stored on the ActionEvent
  5. Analyzer Query: LLMSecurityAnalyzer.security_risk() returns the pre-assigned risk level
  6. No Additional LLM Calls: Risk assessment happens inline—no separate analysis step

Example Tool Call:

{
  "name": "execute_bash",
  "arguments": {
    "command": "rm -rf /tmp/cache",
    "security_risk": "HIGH"
  }
}

The LLM reasons about risk in context when generating the action, eliminating the need for a separate security analysis call.

Configuration:

  • Enabled When: A LLMSecurityAnalyzer is configured for the agent
  • Schema Modification: Automatically adds security_risk field to non-read-only tools
  • Zero Overhead: No additional LLM calls or latency beyond normal action generation

NoOpSecurityAnalyzer

Passthrough analyzer that skips analysis:

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30}} }%%
flowchart LR
    Action["ActionEvent"]
    NoOp["NoOpSecurityAnalyzer"]
    Unknown["SecurityRisk.UNKNOWN"]

    Action --> NoOp --> Unknown

    style NoOp fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px

Use Case: Development, trusted environments, or when confirmation mode handles all actions

Confirmation Policy

The confirmation policy determines when user approval is required. There are three policy implementations:

Source: confirmation_policy.py

Policy Types

Policy Behavior Use Case
AlwaysConfirm Requires confirmation for all actions Maximum safety, interactive workflows
NeverConfirm Never requires confirmation Fully autonomous agents, trusted environments
ConfirmRisky Configurable risk-based policy Balanced approach, production use

ConfirmRisky (Default Policy)

The most flexible policy with configurable thresholds:

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30, "rankSpacing": 40}} }%%
flowchart TB
    Risk["SecurityRisk"]
    CheckUnknown{"Risk ==<br>UNKNOWN?"}
    UseConfirmUnknown{"confirm_unknown<br>setting?"}
    CheckThreshold{"risk.is_riskier<br>(threshold)?"}

    Confirm["Require Confirmation"]
    Allow["Allow Execution"]

    Risk --> CheckUnknown
    CheckUnknown -->|Yes| UseConfirmUnknown
    CheckUnknown -->|No| CheckThreshold

    UseConfirmUnknown -->|True| Confirm
    UseConfirmUnknown -->|False| Allow

    CheckThreshold -->|Yes| Confirm
    CheckThreshold -->|No| Allow

    style CheckUnknown fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px
    style Confirm fill:#ffe8e8,stroke:#dc2626,stroke-width:2px
    style Allow fill:#d1fae5,stroke:#10b981,stroke-width:2px

Configuration:

  • threshold (default: HIGH) - Risk level at or above which confirmation is required
  • Cannot be set to UNKNOWN
  • Uses reflexive comparison: risk.is_riskier(threshold) returns True if risk >= threshold
  • confirm_unknown (default: True) - Whether UNKNOWN risk requires confirmation

Confirmation Rules by Policy

ConfirmRisky with threshold=HIGH (Default)
Risk Level confirm_unknown=True (default) confirm_unknown=False
LOW ✅ Allow ✅ Allow
MEDIUM ✅ Allow ✅ Allow
HIGH 🔒 Require confirmation 🔒 Require confirmation
UNKNOWN 🔒 Require confirmation ✅ Allow
ConfirmRisky with threshold=MEDIUM
Risk Level confirm_unknown=True confirm_unknown=False
LOW ✅ Allow ✅ Allow
MEDIUM 🔒 Require confirmation 🔒 Require confirmation
HIGH 🔒 Require confirmation 🔒 Require confirmation
UNKNOWN 🔒 Require confirmation ✅ Allow
ConfirmRisky with threshold=LOW
Risk Level confirm_unknown=True confirm_unknown=False
LOW 🔒 Require confirmation 🔒 Require confirmation
MEDIUM 🔒 Require confirmation 🔒 Require confirmation
HIGH 🔒 Require confirmation 🔒 Require confirmation
UNKNOWN 🔒 Require confirmation ✅ Allow

Key Rules:

  • Risk comparison is reflexive: HIGH.is_riskier(HIGH) returns True
  • UNKNOWN handling is configurable via confirm_unknown flag
  • Threshold cannot be UNKNOWN - validated at policy creation time

Component Relationships

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30}} }%%
flowchart LR
    Security["Security Analyzer"]
    Agent["Agent"]
    Conversation["Conversation"]
    Tools["Tools"]
    MCP["MCP Tools"]

    Agent -->|Validates actions| Security
    Security -->|Checks| Tools
    Security -->|Uses hints| MCP
    Conversation -->|Pauses for confirmation| Agent

    style Security fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px
    style Agent fill:#e8f3ff,stroke:#2b6cb0,stroke-width:2px
    style Conversation fill:#fff4df,stroke:#b7791f,stroke-width:2px

Relationship Characteristics:

  • Agent → Security: Validates actions before execution
  • Security → Tools: Examines tool characteristics (annotations)
  • Security → MCP: Uses MCP hints for risk assessment
  • Conversation → Agent: Pauses for user confirmation when required
  • Optional Component: Security analyzer can be disabled for trusted environments

See Also


API reference for openhands.sdk.security module

class AlwaysConfirm

Bases: ConfirmationPolicyBase

Methods
model_config = (configuration object)

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

should_confirm()

Determine if an action with the given risk level requires confirmation.

This method defines the core logic for determining whether user confirmation is required before executing an action based on its security risk level.

  • Parameters: risk – The security risk level of the action to be evaluated. Defaults to SecurityRisk.UNKNOWN if not specified.
  • Returns: True if the action requires user confirmation before execution, False if the action can proceed without confirmation.

class ConfirmRisky

Bases: ConfirmationPolicyBase

Properties
Methods
model_config = (configuration object)

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

should_confirm()

Determine if an action with the given risk level requires confirmation.

This method defines the core logic for determining whether user confirmation is required before executing an action based on its security risk level.

  • Parameters: risk – The security risk level of the action to be evaluated. Defaults to SecurityRisk.UNKNOWN if not specified.
  • Returns: True if the action requires user confirmation before execution, False if the action can proceed without confirmation.
classmethod validate_threshold()

class ConfirmationPolicyBase

Bases: DiscriminatedUnionMixin, ABC

Methods
model_config = (configuration object)

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

abstractmethod should_confirm()

Determine if an action with the given risk level requires confirmation.

This method defines the core logic for determining whether user confirmation is required before executing an action based on its security risk level.

  • Parameters: risk – The security risk level of the action to be evaluated. Defaults to SecurityRisk.UNKNOWN if not specified.
  • Returns: True if the action requires user confirmation before execution, False if the action can proceed without confirmation.

class GraySwanAnalyzer

Bases: SecurityAnalyzerBase

Security analyzer using GraySwan’s Cygnal API for AI safety monitoring.

This analyzer sends conversation history and pending actions to the GraySwan Cygnal API for security analysis. The API returns a violation score which is mapped to SecurityRisk levels.

Environment Variables: : GRAYSWAN_API_KEY: Required API key for GraySwan authentication GRAYSWAN_POLICY_ID: Optional policy ID for custom GraySwan policy

Example
>>> from openhands.sdk.security.grayswan import GraySwanAnalyzer
>>> analyzer = GraySwanAnalyzer()
>>> risk = analyzer.security_risk(action_event)
Properties
  • api_key: SecretStr | None
  • api_url: str
  • history_limit: int
  • low_threshold: float
  • max_message_chars: int
  • medium_threshold: float
  • policy_id: str | None
  • timeout: float
Methods
close()

Clean up resources.

model_config = (configuration object)

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init()

Initialize the analyzer after model creation.

security_risk()

Analyze action for security risks using GraySwan API.

This method converts the conversation history and the pending action to OpenAI message format and sends them to the GraySwan Cygnal API for security analysis.

  • Parameters: action – The ActionEvent to analyze
  • Returns: SecurityRisk level based on GraySwan analysis
set_events()

Set the events for context when analyzing actions.

  • Parameters: events – Sequence of events to use as context for security analysis
validate_thresholds()

Validate that thresholds are properly ordered.

class LLMSecurityAnalyzer

Bases: SecurityAnalyzerBase

LLM-based security analyzer.

This analyzer respects the security_risk attribute that can be set by the LLM when generating actions, similar to OpenHands’ LLMRiskAnalyzer.

It provides a lightweight security analysis approach that leverages the LLM’s understanding of action context and potential risks.

Methods
model_config = (configuration object)

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

security_risk()

Evaluate security risk based on LLM-provided assessment.

This method checks if the action has a security_risk attribute set by the LLM and returns it. The LLM may not always provide this attribute but it defaults to UNKNOWN if not explicitly set.

class NeverConfirm

Bases: ConfirmationPolicyBase

Methods
model_config = (configuration object)

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

should_confirm()

Determine if an action with the given risk level requires confirmation.

This method defines the core logic for determining whether user confirmation is required before executing an action based on its security risk level.

  • Parameters: risk – The security risk level of the action to be evaluated. Defaults to SecurityRisk.UNKNOWN if not specified.
  • Returns: True if the action requires user confirmation before execution, False if the action can proceed without confirmation.

class SecurityAnalyzerBase

Bases: DiscriminatedUnionMixin, ABC

Abstract base class for security analyzers.

Security analyzers evaluate the risk of actions before they are executed and can influence the conversation flow based on security policies.

This is adapted from OpenHands SecurityAnalyzer but designed to work with the agent-sdk’s conversation-based architecture.

Methods
analyze_event()

Analyze an event for security risks.

This is a convenience method that checks if the event is an action and calls security_risk() if it is. Non-action events return None.

  • Parameters: event – The event to analyze
  • Returns: ActionSecurityRisk if event is an action, None otherwise
analyze_pending_actions()

Analyze all pending actions in a conversation.

This method gets all unmatched actions from the conversation state and analyzes each one for security risks.

  • Parameters: conversation – The conversation to analyze
  • Returns: List of tuples containing (action, risk_level) for each pending action
model_config = (configuration object)

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

abstractmethod security_risk()

Evaluate the security risk of an ActionEvent.

This is the core method that analyzes an ActionEvent and returns its risk level. Implementations should examine the action’s content, context, and potential impact to determine the appropriate risk level.

  • Parameters: action – The ActionEvent to analyze for security risks
  • Returns: ActionSecurityRisk enum indicating the risk level
should_require_confirmation()

Determine if an action should require user confirmation.

This implements the default confirmation logic based on risk level and confirmation mode settings.

  • Parameters:
  • risk – The security risk level of the action
  • confirmation_mode – Whether confirmation mode is enabled
  • Returns: True if confirmation is required, False otherwise

class SecurityRisk

Bases: str, Enum

Security risk levels for actions.

Based on OpenHands security risk levels but adapted for agent-sdk. Integer values allow for easy comparison and ordering.

Properties
  • description: str Get a human-readable description of the risk level.
  • visualize: Text Return Rich Text representation of this risk level.
Methods
HIGH = 'HIGH'
LOW = 'LOW'
MEDIUM = 'MEDIUM'
UNKNOWN = 'UNKNOWN'
get_color()

Get the color for displaying this risk level in Rich text.

is_riskier()

Check if this risk level is riskier than another.

Risk levels follow the natural ordering: LOW is less risky than MEDIUM, which is less risky than HIGH. UNKNOWN is not comparable to any other level.

To make this act like a standard well-ordered domain, we reflexively consider risk levels to be riskier than themselves. That is:

for risk_level in list(SecurityRisk): : assert risk_level.is_riskier(risk_level)

More concretely:

assert SecurityRisk.HIGH.is_riskier(SecurityRisk.HIGH) assert SecurityRisk.MEDIUM.is_riskier(SecurityRisk.MEDIUM) assert SecurityRisk.LOW.is_riskier(SecurityRisk.LOW)

This can be disabled by setting the reflexive parameter to False.

  • Parameters: other (SecurityRisk*) – The other risk level to compare against. reflexive (bool*) – Whether the relationship is reflexive.
  • Raises: ValueError – If either risk level is UNKNOWN.

Understand how Agent Canvas connects to execution, automation, and sandbox services.

Agent Canvas is the open-source browser client and control center for OpenHands conversations and automations. It presents backend state and sends requests to backend services; it is not an agent runtime or sandbox. Agent Server or an ACP agent CLI executes tools, and the selected workspace or sandbox provides the execution boundary.

Core Components

Component Responsibility Source
Agent Canvas Browser interface for conversations, files, settings, backends, and automations OpenHands/OpenHands
Agent Server Runs conversations, agents, tools, and workspace operations; streams events to clients OpenHands/software-agent-sdk
Automation Server Stores schedules and event triggers, tracks runs, and dispatches conversations OpenHands/automation
Workspace or sandbox Defines which files, processes, credentials, and networks an agent can access Deployment-specific

Sandbox Server is a community-driven standalone API and sandbox control plane. Learn more about Sandbox Server.

Service Relationships

The normal browser path is Browser → Agent Canvas → selected backend. Agent Server owns conversation execution. Automation Server owns scheduled and event-driven run lifecycle. A backend distribution can expose both services behind one URL, but they remain separate responsibilities.

A remote backend uses the same Agent Server API as a local backend. The Agent Server can run on another machine, or in a separate container on the same machine as Canvas. OpenHands Cloud and OpenHands Enterprise are managed backend platforms: their platform control planes create conversation sandboxes that host Agent Server.

Client And Launcher Boundaries

Agent Canvas can refer to two related surfaces:

  • Canvas client — The React browser application. It renders state and sends requests to backend services.
  • agent-canvas launcher and distributions — Packaging that can start the Canvas client, Agent Server, Automation Server, and ingress together.

The launcher supports split modes:

Mode Services started
agent-canvas Canvas client, Agent Server, Automation Server, and ingress
agent-canvas --frontend-only Canvas client and ingress
agent-canvas --backend-only Agent Server, Automation Server, and ingress

Docker and Helm packages can also bundle the client and backend services. A bundled deployment changes how services are installed, not which component owns execution or isolation.

Execution and Isolation

When you send a message, Agent Canvas sends it to the selected backend. Agent Server starts or resumes the conversation, runs the selected agent, invokes tools, updates backend state, and streams events to Canvas.

The workspace determines the execution boundary:

Execution environment Execution and isolation boundary
Host process Agent Server and tools run directly on the backend host without container isolation. If the backend is remote, that host—not the browser's machine—is the execution boundary.
Docker or Kubernetes Agent Server and tools run inside the configured container or pod with its mounts and network policy.
OpenHands Cloud or Enterprise The managed platform creates and operates the conversation sandbox that hosts Agent Server.

Connecting Canvas to a remote backend does not grant the browser direct access to that backend's filesystem. Canvas displays files and terminal output returned by Agent Server.

State Ownership

State belongs to backend services rather than the browser client:

  • Agent Server stores conversation history, agent and LLM profiles, secrets, MCP configuration, and related settings.
  • Automation Server stores automation definitions, schedules, events, and run history.
  • The workspace or sandbox stores files produced or changed by the agent.
  • Agent Canvas stores connection information needed to reach configured backends.

Switching backends changes which backend-managed conversations, settings, automations, and workspaces Canvas displays.

Deployment Patterns

Pattern Relationship
Local all-in-one The launcher starts Canvas and local backend services on one machine.
Self-hosted backend services You deploy Agent Server, and optionally Automation Server, in another process, on a VM, in Docker or Kubernetes, or on Modal. Canvas connects to the deployment as a remote backend.
Managed platform Canvas connects to OpenHands Cloud or OpenHands Enterprise, which operate their backend and sandbox infrastructure.

Next Steps


Core architectural principles guiding the OpenHands Software Agent SDK's development.

The OpenHands Software Agent SDK is part of the OpenHands V1 effort — a complete architectural rework based on lessons from OpenHands V0, one of the most widely adopted open-source coding agents.

Over the last eighteen months, OpenHands V0 evolved from a scrappy prototype into a widely used open-source coding agent. The project grew to tens of thousands of GitHub stars, hundreds of contributors, and multiple production deployments. That growth exposed architectural tensions — tight coupling between research and production, mandatory sandboxing, mutable state, and configuration sprawl — which informed the design principles of agent-sdk in V1.

Optional Isolation over Mandatory Sandboxing

V0 Challenge:\ Every tool call in V0 executed in a sandboxed Docker container by default. While this guaranteed reproducibility and security, it also created friction — the agent and sandbox ran as separate processes, states diverged easily, and multi-tenant workloads could crash each other.\ Moreover, with the rise of the Model Context Protocol (MCP), which assumes local execution and direct access to user environments, V0's rigid isolation model became incompatible.

V1 Principle:\ Sandboxing should be opt-in, not universal.\ V1 unifies agent and tool execution within a single process by default, aligning with MCP's local-execution model.\ When isolation is needed, the same stack can be transparently containerized, maintaining flexibility without complexity.

Stateless by Default, One Source of Truth for State

V0 Challenge:\ V0 relied on mutable Python objects and dynamic typing, which led to silent inconsistencies — failed session restores, version drift, and non-deterministic behavior. Each subsystem tracked its own transient state, making debugging and recovery painful.

V1 Principle:\ Keep everything stateless, with exactly one mutable state.\ All components (agents, tools, LLMs, and configurations) are immutable Pydantic models validated at construction.\ The only mutable entity is the conversation state, a single source of truth that enables deterministic replay and robust persistence across sessions or distributed systems.

Clear Boundaries between Agent and Applications

V0 Challenge:\ The same codebase powered the CLI, web interface, and integrations (e.g., Github, Gitlab, etc). Over time, application-specific conditionals and prompts polluted the agent core, making it brittle.\ Heavy research dependencies and benchmark integrations further bloated production builds.

V1 Principle:\ Maintain strict separation of concerns.\ V1 divides the system into stable, isolated layers: the SDK (agent core), tools (set of tools), workspace (sandbox), and agent server (server that runs inside sandbox).\ Applications communicate with the agent via APIs rather than embedding it directly, ensuring research and production can evolve independently.

Composable Components for Extensibility

V0 Challenge:\ Because agent logic was hard-coded into the core application, extending behavior (e.g., adding new tools or entry points) required branching logic for different entrypoints. This rigidity limited experimentation and discouraged contributions.

V1 Principle:\ Everything should be composable and safe to extend.\ Agents are defined as graphs of interchangeable components—tools, prompts, LLMs, and contexts—each described declaratively with strong typing.\ Developers can reconfigure capabilities (e.g., swap toolsets, override prompts, add delegation logic) without modifying core code, preserving stability while fostering rapid innovation.