⚡ Enterprise Autonomous Agent OS · PyPI v0.4.1

Give any LLM the Transactional Agent Loop & Verifiable Context OS.

agent-saga v0.4.1 introduces the Transactional Agent Loop (goal-oriented execution with stall detection & token budgeting), ContextBroker (HOT/WARM/COLD verifiable receipts), Codemod-as-Transaction (`kill -9` recoverable restores), and production hardening across multi-model setups.

$pip install agent-saga
Test Custom Input Sandbox → View Documentation Star on GitHub
Tamper-Evident WAL · hash-chained SAGA_LIVE
001SAGA_START checkout_402_h a1f9…
002STEP_COMMITTED stripe.chargecompensable
003STEP_INTENT email.send_receiptirreversible
004PRE_FLIGHT_GATE requires human approvalblocked
005ROLLBACK stripe.refund↺ LIFO

New in v0.3.0 · AgentKit

One object. Three verbs. A safety net an agent can read.

The whole engine — the gate, typed compensation, the tamper-evident log, the audit proofs — behind one import. An agent wraps a tool once, runs work inside a transaction, and (the genuinely new part) can ask the system what it is guaranteed and whether it is safe to act right now.

# wrap any tool once — gated + logged + compensable inside a transaction, # and a plain function everywhere else. from agent_saga import AgentKit kit = AgentKit(name="research-agent") charge = kit.safe_tool(stripe_charge, semantics="COMPENSABLE", compensate=lambda r: {"handler": "refund", "kwargs": {"id": r["id"]}}) # any exception inside rolls the whole thing back, in reverse order async with kit.transaction(): await charge(amount=4200) await ship_order(...) # if this throws, the charge is refunded

📜 guarantees() — a manifest it can trust

A versioned, JSON-serialisable statement of exactly what is enforced before an effect and guaranteed after — including an explicit not_claimed clause. A safety surface that hides its limits is a liability; this one states them.

Click to inspect the manifest →

🚦 status() — fail-closed live posture

Before a burst of effectful work, an agent asks kit.status(). If a global kill-switch is halting effects — or if that signal simply can't be read — it reports not ready. Never a confident green when the truth is unknown.

Click to inspect code →

🔌 Zero-ceremony pass-through

The same wrapped tool runs untouched outside a transaction — so it works identically in a script, a notebook, or a test with no saga boundary and no special-casing.

Click to inspect code →

Core Design Philosophy

The 5 Fundamental Principles of agent-saga.

The core contract that separates true transactional safety from post-disaster cleanup scripts.

Principle 1

🎯 Auditable Consistency is the Contract

“A bank does not buy a post-disaster cleanup script — it buys a control that refuses to enter an uncompensable boundary without a human on the hook.”

Principle 2

⚡ Runtime-Derived Compensations

AI agents choose forward tools dynamically at runtime. The inverse action can only be derived after the forward step executes and returns concrete state parameters (e.g., charge IDs, row IDs).

Principle 3

🔍 Honest Rollbacks (clean vs. partial)

Swallowing partial failures is a critical vulnerability. Operators must always distinguish a 100% clean rollback from a partial failure requiring human intervention (RollbackReport.clean).

Principle 4

🛑 Pre-Flight Gates over Post-Cleanup

High-risk or non-compensable actions trigger policy gates before any side-effect is modified — the only point at which refusal is completely free.

Principle 5

💥 Fail Loud, Never Silent

Write-Ahead Logs must never silently swallow unreadable or corrupted records. If a recovery daemon cannot parse an entry, it halts and alerts immediately.

Universal Spectrum Coverage

From Hobby Makers & Coders to High-Precision Aerospace.

Whether building an indie side project, auto-refactoring code, executing $10M banking transfers, or diagnosing patient treatments, agent-saga powers mission-critical reliability everywhere.

Hobbyists & Makers 🛠️

IoT & Hardware Robotics

Enforces hardware actuator angle limits and battery voltage bounds, preventing physical servo burnout or runaway robot motor commands.

Coders & Software Engineers 💻

GitHub & Cloud Infrastructure

Plug-and-play GitHub/GitLab PR auto-reverts and AWS/GCP/K8s infrastructure auto-cleanup if deployment or coding agent tasks fail.

Banking & FinTech 🏦

High-Value Wire & Billing

Enforces 3/3 Triple Redundant Consensus before executing multi-million dollar transfers, preventing hallucinated refunds or duplicated wire charges.

Medical & Healthcare 🩺

Prescription & Diagnosis Safety

Intersects LLM treatment recommendations against strict clinical boundary range rules (0.1mg - 50mg), blocking lethal medication overdose attempts pre-flight.

Observability & Tracing 📊

LangSmith, Phoenix & OTEL

Stamps Saga UUID and prompt context into OpenTelemetry spans and LLM trace providers, linking hallucinated prompts directly to rollback causes.

Risk Team Dashboard 🛡️

Interactive Web UI & Replay

Clean Web UI (agent-saga ui) and CLI Time-Travel Replay (agent-saga replay <id>) for risk teams to inspect, approve, or debug failed sagas.

Interactive Practical Playground

Practically test your own input data: Before vs. After agent-saga.

Type custom input parameters below. Use the prominent toggle switch to compare how raw AI models crash and corrupt data (BEFORE) versus how agent-saga verifies and auto-restores state (AFTER).

● MODE: AFTER (+ agent-saga v0.3.0 Active Protection)
Toggle OFF to test Raw AI Failure Mode
PROTECTION: ON (+ agent-saga)
REAL-TIME TRANSACTION EXECUTION LOG (WAL v0.3.0) READY
Enter your custom parameters on the left and click Execute AI Simulation.

Core Capabilities

Click any capability to inspect its real code & architecture.

Every card below maps to shipping, tested code in the package — not a roadmap. The suite is 2007 tests green.

✅ Rollback-Safety Certificates

Machine-checkable proof that every committed effect was accounted for. agent-saga certify returns non-zero in CI, so a release that could strand an uncompensated charge can't ship.

Click to inspect code →

🌳 Selective-Disclosure Audit Proofs

Prove one saga to an auditor without revealing any other. A Merkle tree with domain-separated leaves yields a compact inclusion proof under a published root.

Click to inspect code →

⚡ Predictive Pre-Execution

Speculatively run REVERSIBLE-only steps ahead of confirmation behind an HMAC lease bound to (intent, tool, expiry). Stale, forged, or cross-intent speculations can never be redeemed.

Click to inspect code →

🔐 Passkey / Hardware Approvals

An IRREVERSIBLE step can demand a hardware-bound Ed25519 signature over a digest of the exact action — so an approval can't be replayed onto a different call.

Click to inspect code →

🕸️ Offline Mesh Sagas (CRDT)

Agents acting offline on separate devices keep local WALs that merge with a commutative, idempotent, associative G-Set CRDT — any sync order converges to the same history.

Click to inspect code →

🛰️ Edge / Async Storage Sink

The engine is separable from disk: point the WAL at any async store (proven, not asserted) to run the same guarantees at the edge or in a WASM sandbox.

Click to inspect code →

☁️ Self-Hosted Control Plane (cloud-server)

Run your own control plane backend (agent-saga cloud-server) matching the sagaops.dev SaaS REST API for audit ingest, approvals, and fleet budget sync.

Click to inspect code →

📐 BPMN 2.0 Visual Workflow Designer

Interactive web canvas tab on the dashboard to visually design agent compensation flows and export typed @saga_scope Python code in 1 click.

Click to inspect code →

🧪 Standalone pytest-agent-saga Package

Dedicated Pytest companion package (pip install pytest-agent-saga) providing isolated WAL fixtures, multi-point chaos runners, and deterministic replay assertions.

Click to inspect code →

🛡️ Array & Dotted Redaction (redact_path)

Surgically mask nested fields including list indices (e.g. redact_path(records, "kwargs.items.0.cvv")) without writing custom lambda functions.

Click to inspect code →

🔄 Multi-Turn Agent Self-Healing Loop

Bounded correction loop (SelfHealingLoop) that feeds gate refusal reasons back to the agent with exponential backoff and human escalation fallback.

Click to inspect code →

🧠 Zero-Config Embedding Risk Scorer

Dynamic anomaly risk scoring against known-bad tool calls (EmbeddingRiskScorer) with zero external dependencies and offline execution.

Click to inspect code →

💬 Slack OAuth & Slash Command Integration

Interactive Slack Block Kit app with OAuth URL construction (build_oauth_install_url) and /saga-approve slash command handling.

Click to inspect code →

📊 OpenTelemetry & LangSmith Tracing

Binds Saga UUIDs to OpenTelemetry spans, LangChain callbacks, and Phoenix traces, identifying the exact prompt context that caused a rollback.

Click to inspect code →

💻 Protected Web Dashboard (agent-saga ui)

Web UI dashboard serving visual approval queues, SSE live WAL streaming, spend limit gauges, and token authentication.

Click to inspect code →

Developer Documentation

Quickstart & Integration Reference.

Get started in 30 seconds. Wrap your agent loops in a single decorator or context manager.

1. Installation

pip install agent-saga

2. 30-second quickstart — the AgentKit SDK

from agent_saga import AgentKit kit = AgentKit(name="my-agent") charge = kit.safe_tool(stripe_charge, semantics="COMPENSABLE", compensate=lambda r: {"handler": "refund", "kwargs": {"id": r["id"]}}) async with kit.transaction(): # a saga boundary await charge(amount=4200) # gated, logged, and refunded on any failure await ship_order(...) kit.guarantees() # machine-readable: exactly what is enforced, versioned kit.status() # live posture — fail-closed if a safety signal can't be read

3. Prove it in CI — rollback-safety gate

# fails the build (non-zero exit) if any committed effect was left stranded agent-saga verify --wal ./agent-saga.wal # the log was not altered/truncated agent-saga certify --wal ./agent-saga.wal # every effect is accounted for

4. OpenTelemetry & LangSmith Tracing Setup

from agent_saga.observability import setup_telemetry, link_llm_trace # Enable OpenTelemetry tracing setup_telemetry() # Link LLM prompt trace to Saga UUID link_llm_trace(saga_id="saga_123", trace_id="tr_9988", prompt_context="Refactor payment engine")

5. GitHub & Cloud Connector Safety

from agent_saga.connectors import GitHubConnector, CloudConnector gh = GitHubConnector() pr = await gh.create_pull_request(repo="org/app", title="Auto Patch", head="fix-branch") # Auto-closes PR if downstream step fails!