Agentra LabsAgentra Labs DocsPublic Documentation

AgenticContract

API Reference

Complete API reference for AgenticContract

Complete reference for the AgenticContract Rust and Python APIs. Version 0.1.

ContractEngine

The main entry point for the policy engine. All operations go through this struct.

Constructor

let engine = ContractEngine::new();

Creates an empty contract engine with no entities.

open(path: &str) -> ContractResult<ContractEngine>

Opens an existing .acon file from disk. Returns an error if the file doesn't exist or has an invalid format.

let engine = ContractEngine::open("~/.agentic/contract.acon")?;

save() -> ContractResult<()>

Writes the current state to the file path set during open(). Computes BLAKE3 checksum and updates the header.

engine.save()?;

Policy Methods

add_policy(policy: Policy) -> ContractId

Adds a policy to the engine. Returns the policy's unique ID.

ParameterTypeDescription
policyPolicyThe policy to add
use agentic_contract::{Policy, PolicyScope, PolicyAction};

let policy = Policy::new("No deploys on Friday", PolicyScope::Global, PolicyAction::Deny);
let id = engine.add_policy(policy);

check_policy(action_type: &str, scope: Option<PolicyScope>) -> PolicyAction

Evaluates all active policies against the given action description. Returns the most restrictive matching action.

ParameterTypeRequiredDescription
action_type&strYesThe action being attempted
scopeOption<PolicyScope>NoFilter to specific scope
let result = engine.check_policy("deploy to production", None);
match result {
    PolicyAction::Deny => println!("Blocked"),
    PolicyAction::RequireApproval => println!("Needs approval"),
    _ => println!("Allowed"),
}

list_policies(scope: Option<PolicyScope>) -> Vec<&Policy>

Returns all policies, optionally filtered by scope.

get_policy(id: ContractId) -> ContractResult<&Policy>

Returns a specific policy by ID. Returns ContractError::NotFound if the ID doesn't exist.

Risk Limit Methods

add_risk_limit(limit: RiskLimit) -> ContractId

Adds a risk limit to the engine.

use agentic_contract::{RiskLimit, LimitType};

let limit = RiskLimit::new("API calls per hour", LimitType::Rate, 100.0)
    .with_window(3600);
let id = engine.add_risk_limit(limit);

check_risk_limit(label_pattern: &str, amount: f64) -> Option<&RiskLimit>

Checks whether adding amount to the matching risk limit would exceed the maximum. Returns the first limit that would be exceeded, or None if all limits are within bounds.

ParameterTypeRequiredDescription
label_pattern&strYesText pattern to match limit labels
amountf64YesProposed increment amount

increment_risk_limit(id: ContractId, amount: f64) -> ContractResult<()>

Increments a risk limit's current value. Call this after the guarded action succeeds.

list_risk_limits() -> &[RiskLimit]

Returns all risk limits.

Approval Methods

add_approval_rule(rule: ApprovalRule) -> ContractId

Adds an approval rule.

use agentic_contract::ApprovalRule;

let rule = ApprovalRule::new("Production deploy approval", "deploy.*production")
    .with_approver("ops-lead")
    .with_timeout(3600);
let id = engine.add_approval_rule(rule);

request_approval(rule_id: ContractId, action_description: &str, requestor: &str) -> ContractResult<ContractId>

Creates a pending approval request linked to a rule.

ParameterTypeRequiredDescription
rule_idContractIdYesThe rule triggering this request
action_description&strYesWhat the agent wants to do
requestor&strYesWho is requesting

decide_approval(request_id: ContractId, decision: DecisionType, decider: &str, reason: &str) -> ContractResult<ContractId>

Approves or denies a pending request. Returns the decision ID.

ParameterTypeRequiredDescription
request_idContractIdYesWhich request to decide
decisionDecisionTypeYesApprove or Deny
decider&strYesWho is deciding
reason&strYesJustification

list_approval_requests(status: Option<ApprovalStatus>) -> Vec<&ApprovalRequest>

Returns approval requests, optionally filtered by status.

Condition Methods

add_condition(condition: Condition) -> ContractId

Adds a conditional execution rule.

use agentic_contract::{Condition, ConditionType};

let cond = Condition::new("Business hours", ConditionType::TimeBased, "09:00-17:00 UTC");
let id = engine.add_condition(cond);

evaluate_condition(id: ContractId) -> ContractResult<bool>

Evaluates a condition and updates its status. Returns whether the condition is met.

Obligation Methods

add_obligation(obligation: Obligation) -> ContractId

Adds an obligation with optional deadline.

use agentic_contract::Obligation;

let ob = Obligation::new(
    "Weekly report",
    "Submit compliance summary",
    "compliance-agent"
).with_deadline(deadline_time);
let id = engine.add_obligation(ob);

check_obligations() -> Vec<&Obligation>

Returns obligations that are overdue (deadline passed, status still Pending).

fulfill_obligation(id: ContractId) -> ContractResult<()>

Marks an obligation as fulfilled.

waive_obligation(id: ContractId) -> ContractResult<()>

Marks an obligation as waived (explicitly excused).

Violation Methods

report_violation(description: &str, severity: ViolationSeverity, actor: &str) -> ContractId

Records a violation.

ParameterTypeRequiredDescription
description&strYesWhat happened
severityViolationSeverityYesInfo, Warning, Critical, or Fatal
actor&strYesWho committed the violation
use agentic_contract::ViolationSeverity;

let id = engine.report_violation(
    "Budget exceeded by $12.50",
    ViolationSeverity::Critical,
    "data-agent-3"
);

list_violations(severity: Option<ViolationSeverity>) -> Vec<&Violation>

Returns violations, optionally filtered by minimum severity.

Statistics

stats() -> ContractStats

Returns summary statistics for all entity types.

let s = engine.stats();
println!("Policies: {}, Limits: {}, Violations: {}", s.policies, s.risk_limits, s.violations);

Core Types

Policy

pub struct Policy {
    pub id: ContractId,
    pub label: String,
    pub description: String,
    pub scope: PolicyScope,
    pub action: PolicyAction,
    pub conditions: Vec<String>,
    pub status: PolicyStatus,
    pub tags: Vec<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub expires_at: Option<DateTime<Utc>>,
}

Builder methods: with_description(), with_condition(), with_tag(), expires_at().

RiskLimit

pub struct RiskLimit {
    pub id: ContractId,
    pub label: String,
    pub limit_type: LimitType,
    pub current_value: f64,
    pub max_value: f64,
    pub window_secs: Option<u64>,
    pub window_start: Option<DateTime<Utc>>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

Utility methods: would_exceed(amount), remaining(), usage_ratio(), window_expired(), reset().

ApprovalRule

pub struct ApprovalRule {
    pub id: ContractId,
    pub label: String,
    pub action_pattern: String,
    pub approvers: Vec<String>,
    pub timeout_secs: Option<u64>,
    pub created_at: DateTime<Utc>,
}

ApprovalRequest

pub struct ApprovalRequest {
    pub id: ContractId,
    pub rule_id: ContractId,
    pub action_description: String,
    pub requestor: String,
    pub status: ApprovalStatus,
    pub created_at: DateTime<Utc>,
    pub expires_at: Option<DateTime<Utc>>,
}

ApprovalDecision

pub struct ApprovalDecision {
    pub id: ContractId,
    pub request_id: ContractId,
    pub decision: DecisionType,
    pub decider: String,
    pub reason: String,
    pub decided_at: DateTime<Utc>,
}

Condition

pub struct Condition {
    pub id: ContractId,
    pub label: String,
    pub condition_type: ConditionType,
    pub expression: String,
    pub status: ConditionStatus,
    pub last_result: Option<String>,
    pub created_at: DateTime<Utc>,
    pub evaluated_at: Option<DateTime<Utc>>,
}

Obligation

pub struct Obligation {
    pub id: ContractId,
    pub label: String,
    pub description: String,
    pub assignee: String,
    pub deadline: Option<DateTime<Utc>>,
    pub status: ObligationStatus,
    pub created_at: DateTime<Utc>,
    pub resolved_at: Option<DateTime<Utc>>,
}

Violation

pub struct Violation {
    pub id: ContractId,
    pub policy_id: Option<ContractId>,
    pub description: String,
    pub severity: ViolationSeverity,
    pub actor: String,
    pub detected_at: DateTime<Utc>,
    pub context: serde_json::Value,
}

Enums

PolicyScope

pub enum PolicyScope { Global, Session, Agent }

PolicyAction

pub enum PolicyAction { Allow, Deny, RequireApproval, AuditOnly }

PolicyStatus

pub enum PolicyStatus { Active, Disabled, Expired }

LimitType

pub enum LimitType { Rate, Threshold, Budget, Count }

ApprovalStatus

pub enum ApprovalStatus { Pending, Approved, Denied, Expired }

DecisionType

pub enum DecisionType { Approve, Deny }

ConditionType

pub enum ConditionType { Threshold, TimeBased, Dependency, Custom }

ConditionStatus

pub enum ConditionStatus { Unevaluated, Met, NotMet, Unknown }

ObligationStatus

pub enum ObligationStatus { Pending, Fulfilled, Overdue, Waived }

ViolationSeverity

pub enum ViolationSeverity { Info, Warning, Critical, Fatal }

Implements Ord for severity comparison. Fatal > Critical > Warning > Info.

Error Types

pub enum ContractError {
    NotFound(String),
    PolicyViolation(String),
    RiskLimitExceeded(String),
    ApprovalRequired(String),
    ApprovalDenied(String),
    ConditionNotMet(String),
    ObligationUnfulfilled(String),
    ContractExpired(String),
    InvalidContract(String),
    FileFormat(String),
    Io(std::io::Error),
    Serialization(String),
}

All variants carry a human-readable message. Io wraps std::io::Error for file operations. Serialization wraps serde errors.

ContractResult

pub type ContractResult<T> = Result<T, ContractError>;

Python SDK

ContractEngine (Python)

from agentic_contract import ContractEngine

engine = ContractEngine()               # New empty engine
engine = ContractEngine(path="my.acon") # Open existing file

Methods

MethodParametersReturnsDescription
add_policy(label, scope, action)str, str, strstr (id)Add a policy
check_policy(action)strstrCheck action against policies
list_policies()listList all policies
set_risk_limit(label, max, type)str, float, strstr (id)Set a risk limit
check_risk_limit(label, amount)str, floatdictCheck risk limit
request_approval(rule_id, desc, who)str, str, strstr (id)Request approval
decide_approval(req_id, decision, who, reason)str, str, str, strstr (id)Decide approval
add_obligation(label, desc, assignee)str, str, strstr (id)Add obligation
report_violation(desc, severity, actor)str, str, strstr (id)Report violation
stats()dictSummary statistics

The Python SDK wraps the acon CLI binary via subprocess. It requires the CLI to be installed on the system.

FFI Reference

See the FFI Reference for C/Python interop via the shared library.