← Back to Home

HaltState AI: The Guard Pattern

The guard() context manager is the core of HaltState SDK. It handles the full approval lifecycle automatically.

Basic Usage

from haltstate import HaltStateClient, ApprovalPending, ActionDenied

client = HaltStateClient(
    tenant_id="your-tenant-id",
    api_key="hs_your_api_key"
)

try:
    with client.guard(
        action="payment.transfer",
        params={"amount": 5000, "recipient": "vendor-123"},
        idempotency_key="payment-vendor-123-2026-01-05"
    ) as permit:
        # This block ONLY executes if the action is APPROVED
        transfer_money(5000, "vendor-123")
        print(f"Approved by: {permit.approver}")
        print(f"Approved at: {permit.approved_at}")

except ApprovalPending as e:
    print(f"Awaiting approval: {e.approval_id}")
    sys.exit(0)

except ActionDenied as e:
    print(f"Action denied: {e}")

The Permit Object

When an action is approved, you receive a Permit inside the guard block:

with client.guard(...) as permit:
    print(permit.approval_id)     # "87fc7b00-c037-4f90-..."
    print(permit.action)          # "payment.transfer"
    print(permit.idempotency_key) # "payment-vendor-123-2026-01-05"
    print(permit.approver)        # "admin@company.com"
    print(permit.approved_at)     # "2026-01-05T10:30:00Z"

Guard Parameters

Parameter Required Description
action Yes Action identifier (e.g., "database.delete")
params Yes Dictionary of action parameters
idempotency_key Yes Unique key for this operation
agent_id No Identifier for the calling agent
metadata No Additional context for approvers