ActionGuard
The main entry point. Assembles the evaluation pipeline, audit log, rollback system, and multi-agent trust ledger.Constructor
A
GuardConfig Pydantic model. If None, uses GuardConfig() defaults.ActionGuard.default()
Create an instance with sensible defaults. No config file needed — good for quick starts and testing.ActionGuard.from_config()
Create an instance from a YAML config file.Path to a YAML configuration file.
A configured
ActionGuard instance.guard.protect()
Decorator to protect a function with ActionGuard.Hierarchical action descriptor (e.g.
"file.delete", "db.execute").Baseline risk level for this action. One of
LOW, MEDIUM, HIGH, CRITICAL.Whether to capture a snapshot before execution for rollback support.
Optional tags for categorization and filtering.
Decorator function. The wrapped function gains
_plyra_guard_protected = True.guard.wrap()
Wrap framework-native tools with ActionGuard protection. Auto-detects the framework and routes to the appropriate adapter.List of framework-native tool objects (LangChain tools, plain functions, etc.).
Wrapped tools in their native format.
guard.evaluate()
Evaluate anActionIntent without executing (dry-run).
The action to evaluate.
The final result with the most restrictive verdict from all evaluators.
guard.evaluate_async()
Async version. Runs the evaluation pipeline in a thread to avoid blocking the event loop.guard.explain()
Run the full evaluation pipeline in dry-run mode and return a rich, human-readable explanation string. Never executes the action.The action to explain.
Human-readable explanation of which evaluators ran and why.
guard.explain_async()
Async version ofexplain().
guard.get_audit_log()
Query the audit log with optional filters.Optional filter criteria. If
None, returns all entries up to the default limit.Matching audit entries, newest first.
guard.get_metrics()
Get a snapshot of aggregate metrics.Aggregate statistics for all actions evaluated by this guard instance.
guard.add_exporter()
Register an audit log exporter. Exporters receive everyAuditEntry as it
is written.
An object implementing
export(entry: AuditEntry) -> None.guard.register_agent()
Register an agent with a trust level for multi-agent systems.Unique agent identifier.
Trust classification for this agent.
guard.rollback()
Roll back a single action by its ID.The
action_id from an ActionIntent or AuditEntry.True if rollback succeeded.guard.rollback_last()
Roll back the last N actions.Number of actions to roll back.
Optionally filter to one agent.
Per-action rollback results.
guard.rollback_task()
Roll back all actions for a task across all agents.The task identifier.
Summary with
task_id, total_actions, rolled_back, failed, skipped lists.guard.serve()
Start the HTTP sidecar server (dashboard + REST API).Bind address.
Port number.
Requires
pip install "plyra-guard[sidecar]". Raises ImportError if
FastAPI or uvicorn are not installed.Data classes
ActionIntent
The primary data structure that flows through the evaluation pipeline.| Field | Type | Default | Description |
|---|---|---|---|
action_type | str | — | Hierarchical action descriptor, e.g. "file.delete" |
tool_name | str | — | Name of the tool being invoked |
parameters | dict[str, Any] | — | Arguments to the tool call |
agent_id | str | — | Identity of the calling agent |
task_context | str | "" | Human-readable description of what the agent is doing |
action_id | str | uuid4() | Unique ID for this intent (auto-generated) |
task_id | str | None | None | Optional task grouping for multi-step workflows |
timestamp | datetime | now(UTC) | When the intent was created |
estimated_cost | float | 0.0 | Estimated monetary cost in USD |
risk_level | RiskLevel | MEDIUM | Pre-declared risk classification |
instruction_chain | list[AgentCall] | [] | Full delegation chain for multi-agent provenance |
metadata | dict[str, Any] | {} | Arbitrary metadata bag for extensibility |
EvaluatorResult
The output of a single evaluator in the pipeline.| Field | Type | Default | Description |
|---|---|---|---|
verdict | Verdict | — | The evaluator’s decision |
reason | str | — | Human-readable explanation |
confidence | float | 1.0 | Confidence score (0.0–1.0) |
evaluator_name | str | "" | Name of the evaluator class |
suggested_action | str | None | None | Optional remediation suggestion |
metadata | dict[str, Any] | {} | Arbitrary metadata |
AuditEntry
Immutable audit record written for every action evaluated.| Field | Type | Default | Description |
|---|---|---|---|
action_id | str | — | Matches the originating ActionIntent |
agent_id | str | — | Agent that initiated the action |
action_type | str | — | Hierarchical action descriptor |
verdict | Verdict | — | Final verdict |
risk_score | float | 0.0 | Computed risk score |
task_id | str | None | None | Task grouping |
policy_triggered | str | None | None | Name of the policy that matched |
evaluator_results | list[EvaluatorResult] | [] | Results from all evaluators that ran |
instruction_chain | list[AgentCall] | [] | Delegation chain |
parameters | dict[str, Any] | {} | Tool call parameters |
duration_ms | int | 0 | Execution time in milliseconds |
timestamp | datetime | now(UTC) | When the action was evaluated |
rolled_back | bool | False | Whether this action was rolled back |
error | str | None | None | Error message, if any |
AuditFilter
Filter criteria for querying the audit log.| Field | Type | Default | Description |
|---|---|---|---|
agent_id | str | None | None | Filter by agent |
task_id | str | None | None | Filter by task |
verdict | Verdict | None | None | Filter by verdict |
action_type | str | None | None | Filter by action type |
from_time | datetime | None | None | Start of time range |
to_time | datetime | None | None | End of time range |
limit | int | 100 | Max entries to return |
GuardMetrics
Prometheus-style metrics snapshot.| Field | Type | Default | Description |
|---|---|---|---|
total_actions | int | 0 | Total actions evaluated |
allowed_actions | int | 0 | Actions with ALLOW verdict |
blocked_actions | int | 0 | Actions with BLOCK verdict |
escalated_actions | int | 0 | Actions escalated |
warned_actions | int | 0 | Actions warned |
deferred_actions | int | 0 | Actions deferred |
rollbacks | int | 0 | Successful rollbacks |
rollback_failures | int | 0 | Failed rollbacks |
total_cost | float | 0.0 | Cumulative cost in USD |
avg_risk_score | float | 0.0 | Average risk score |
avg_duration_ms | float | 0.0 | Average evaluation duration |
actions_by_agent | dict[str, int] | {} | Per-agent action counts |
actions_by_type | dict[str, int] | {} | Per-action-type counts |
verdicts_by_policy | dict[str, int] | {} | Per-policy verdict counts |
RollbackReport
Summary of a batch rollback operation.| Field | Type | Default | Description |
|---|---|---|---|
task_id | str | — | Task that was rolled back |
total_actions | int | 0 | Total actions in the task |
rolled_back | list[str] | [] | Action IDs successfully rolled back |
failed | list[str] | [] | Action IDs where rollback failed |
skipped | list[str] | [] | Action IDs skipped |
report.success → True if no failures and at least one rollback.
AgentCall
One hop in a multi-agent delegation chain.| Field | Type | Default | Description |
|---|---|---|---|
agent_id | str | — | Agent making the call |
trust_level | float | — | Numeric trust score (0.0–1.0) |
instruction | str | — | Instruction given to this agent |
timestamp | datetime | now(UTC) | When this delegation occurred |
Enums
Verdict
| Value | Description |
|---|---|
Verdict.ALLOW | Action may proceed |
Verdict.BLOCK | Action is denied |
Verdict.ESCALATE | Requires higher authority or human approval |
Verdict.DEFER | Deferred for async approval |
Verdict.WARN | May proceed with a warning logged |
verdict.is_permissive()→TrueforALLOWandWARNverdict.is_blocking()→TrueforBLOCK,ESCALATE, andDEFER
RiskLevel
| Value | Base score |
|---|---|
RiskLevel.LOW | 0.1 |
RiskLevel.MEDIUM | 0.3 |
RiskLevel.HIGH | 0.6 |
RiskLevel.CRITICAL | 0.9 |
risk_level.base_score() → returns the float value.
TrustLevel
| Value | Trust score |
|---|---|
TrustLevel.HUMAN | 1.0 |
TrustLevel.ORCHESTRATOR | 0.8 |
TrustLevel.PEER | 0.5 |
TrustLevel.SUB_AGENT | 0.3 |
TrustLevel.UNKNOWN | 0.0 |
trust_level.score() → returns the float value.
Exceptions
All exceptions inherit fromActionGuardError.
Execution exceptions
| Exception | When |
|---|---|
ExecutionBlockedError | Action blocked by evaluation pipeline. Has verdict, reason, what_happened, policy_triggered, how_to_fix. |
ActionEscalatedError | Action requires escalation. Has reason, escalate_to. |
ActionDeferredError | Action deferred. Has reason, defer_seconds. |
ExecutionTimeoutError | Action execution exceeded timeout |
TrustViolationError | Agent trust too low. Has agent_id, required_trust, actual_trust. |
CascadeDepthExceededError | Delegation chain too deep. Has current_depth, max_depth. |
Policy exceptions
| Exception | When |
|---|---|
PolicyError | Base for policy errors |
PolicyParseError | YAML policy file cannot be parsed |
PolicyConditionError | Policy condition expression is invalid |
Config exceptions
| Exception | When |
|---|---|
ConfigError | Base for config errors |
ConfigFileNotFoundError | Config file not found |
ConfigValidationError | Config values fail validation |
ConfigSchemaError | Config structure doesn’t match schema |
Budget and rate limit exceptions
| Exception | When |
|---|---|
RateLimitExceededError | Agent or tool exceeds rate limit. Has agent_id, tool_name, limit. |
BudgetExceededError | Action would exceed budget. Has current_spend, budget_limit. |
HumanApprovalTimeoutError | Human-in-the-loop approval timed out |
Other exceptions
| Exception | When |
|---|---|
RollbackError | Base for rollback errors |
RollbackHandlerNotFoundError | No handler registered for action type |
SnapshotNotFoundError | Snapshot not found for action |
RollbackFailedError | Rollback failed to restore state |
AgentNotRegisteredError | Unregistered agent_id referenced |
AdapterNotFoundError | No adapter for the given tool type |
AdapterWrappingError | Tool wrapping failed |
ExporterError | Exporter error |
SidecarError | Sidecar server error |
SidecarStartupError | Sidecar failed to start |
Structured error messages
All blocking exceptions (ExecutionBlockedError, ActionEscalatedError,
RateLimitExceededError, BudgetExceededError, TrustViolationError,
CascadeDepthExceededError, ActionDeferredError) provide three structured fields:
what_happened— clear plain-English descriptionpolicy_triggered— name of the policy or evaluatorhow_to_fix— concrete, actionable steps
Environment variables
| Variable | Default | Description |
|---|---|---|
PLYRA_SNAPSHOT_PATH | ~/.plyra/snapshots.db | SQLite database path for action snapshots |
Configuration schema
The YAML config file maps to theGuardConfig Pydantic model: