[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HKSXAX892VJH63MM72TE8":3,"skill-same:01M77HKSXAX892VJH63MM72TE8":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":39,"commitSha":40,"skillDirectory":41,"forksCount":42,"repositoryHtmlUrl":43,"repositoryHomepageUrl":44,"ownerHtmlUrl":45,"ownerBlogUrl":6,"ownerDescription":46,"updatedAt":47,"install":48,"resources":61},"01M77HKSXAX892VJH63MM72TE8","greenhelix-async-agent-commerce",null,"Async Agent Commerce: Event-Driven Patterns for Autonomous Transactions. Build event-driven agent commerce systems using saga patterns, compensating transactions, dead letter handling, exactly-once processing, backpressure, and async escrow settlement. Covers event bus architecture and webhook integration with detailed code examples with code.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-async-agent-commerce\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-async-agent-commerce\nversion: \"1.3.1\"\ndescription: \"Async Agent Commerce: Event-Driven Patterns for Autonomous Transactions. Build event-driven agent commerce systems using saga patterns, compensating transactions, dead letter handling, exactly-once processing, backpressure, and async escrow settlement. Covers event bus architecture and webhook integration with detailed code examples with code.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [async, event-driven, saga, agent-commerce, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 39.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: none\n---\n# Async Agent Commerce: Event-Driven Patterns for Autonomous Transactions\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code, require credentials, or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n\n\nThe entire GreenHelix companion library is synchronous -- request, wait, response. You call `create_escrow`, the HTTP connection blocks for 200 milliseconds, and you get back an escrow ID. You call `release_escrow`, the connection blocks again, and the funds move. This works perfectly for simple two-party transactions that settle in seconds. But real-world agent commerce is inherently asynchronous. An escrow evaluation takes 30 days. A dispute resolution takes hours. A multi-agent negotiation involves back-and-forth over minutes. A compliance check depends on a third-party regulatory API that responds in 8 seconds on a good day and 90 seconds on a bad one. Synchronous polling wastes resources and misses events. A buyer agent that polls `get_escrow_status` every 5 seconds for 30 days makes 518,400 API calls to learn about a single state change. Multiply that by a fleet of 500 agents, each managing 20 active escrows, and you are burning 5.18 billion API calls per month on polling alone -- most returning \"no change.\" This guide rebuilds agent commerce on event-driven foundations using GreenHelix's event bus, webhooks, and messaging tools. It covers the patterns that production distributed systems have relied on for decades -- saga orchestration, compensating transactions, dead letter handling, exactly-once processing, and backpressure -- adapted specifically for autonomous agent transactions. Every pattern is implemented in Python using asyncio, every example uses the GreenHelix API, and every class is designed to run in production without human intervention.\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## What You'll Learn\n- Chapter 1: Why Async Matters for Agent Commerce\n- Chapter 2: AsyncEventBus Class\n- Chapter 3: Saga Orchestrator Pattern\n- Chapter 4: Compensating Transactions\n- Chapter 5: Dead Letter Handling\n- Chapter 6: Exactly-Once Processing\n- Chapter 7: Backpressure\n- Chapter 8: Async Escrow Settlement\n- Next Steps\n- What's Next\n\n## Full Guide\n\n# Async Agent Commerce: Event-Driven Patterns for Autonomous Transactions\n\nThe entire GreenHelix companion library is synchronous -- request, wait, response. You call `create_escrow`, the HTTP connection blocks for 200 milliseconds, and you get back an escrow ID. You call `release_escrow`, the connection blocks again, and the funds move. This works perfectly for simple two-party transactions that settle in seconds. But real-world agent commerce is inherently asynchronous. An escrow evaluation takes 30 days. A dispute resolution takes hours. A multi-agent negotiation involves back-and-forth over minutes. A compliance check depends on a third-party regulatory API that responds in 8 seconds on a good day and 90 seconds on a bad one. Synchronous polling wastes resources and misses events. A buyer agent that polls `get_escrow_status` every 5 seconds for 30 days makes 518,400 API calls to learn about a single state change. Multiply that by a fleet of 500 agents, each managing 20 active escrows, and you are burning 5.18 billion API calls per month on polling alone -- most returning \"no change.\" This guide rebuilds agent commerce on event-driven foundations using GreenHelix's event bus, webhooks, and messaging tools. It covers the patterns that production distributed systems have relied on for decades -- saga orchestration, compensating transactions, dead letter handling, exactly-once processing, and backpressure -- adapted specifically for autonomous agent transactions. Every pattern is implemented in Python using asyncio, every example uses the GreenHelix API, and every class is designed to run in production without human intervention.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [Why Async Matters for Agent Commerce](#chapter-1-why-async-matters-for-agent-commerce)\n2. [AsyncEventBus Class](#chapter-2-asynceventbus-class)\n3. [Saga Orchestrator Pattern](#chapter-3-saga-orchestrator-pattern)\n4. [Compensating Transactions](#chapter-4-compensating-transactions)\n5. [Dead Letter Handling](#chapter-5-dead-letter-handling)\n6. [Exactly-Once Processing](#chapter-6-exactly-once-processing)\n7. [Backpressure](#chapter-7-backpressure)\n8. [Async Escrow Settlement](#chapter-8-async-escrow-settlement)\n\n---\n\n## Chapter 1: Why Async Matters for Agent Commerce\n\n### The Polling Tax\n\nEvery synchronous agent commerce system pays a hidden tax: the cost of asking \"has anything changed?\" repeatedly until the answer is yes. Consider the lifecycle of a single escrow-protected service transaction. The buyer creates an escrow via `create_escrow`. The seller delivers the service. The buyer evaluates delivery quality. The buyer releases the escrow via `release_escrow`. In a synchronous model, the buyer must poll for two state transitions: \"has the seller acknowledged the escrow?\" and \"has delivery been confirmed by the SLA monitor?\" Each poll is an HTTP request. Each request consumes compute on the buyer's side, network bandwidth in transit, and compute on the GreenHelix gateway.\n\nThe numbers scale badly. A single agent managing 50 active transactions, polling each at 10-second intervals, generates 432,000 API calls per day. A fleet of 200 agents generates 86.4 million. At GreenHelix's free tier rate limit of 100 calls per minute, a single agent would exhaust its entire rate budget on polling alone, leaving zero capacity for actual commerce operations. Even at the pro tier (1,000 calls per minute), polling 50 transactions at 10-second intervals consumes 300 calls per minute -- 30% of the agent's total capacity wasted on \"has anything changed? no.\"\n\n```\nSynchronous Polling Cost Model\n====================================\n\n                          FREE TIER    PRO TIER     ENTERPRISE\nRate limit (calls\u002Fmin)    100          1,000        10,000\nActive transactions        50           50           50\nPoll interval (seconds)    10           10           10\nPolls per minute           300          300          300\nBudget consumed            300%         30%          3%\nRemaining for commerce     0%           70%          97%\n\nWith 200 agents:\nTotal polls\u002Fday            86.4M        86.4M        86.4M\nAPI cost at $0.001\u002Fcall    $86,400      $86,400      $86,400\nUseful information gained  ~200         ~200         ~200\nCost per useful event      $432         $432         $432\n```\n\nThe last row is the damning one. Of 86.4 million polls per day, approximately 200 return an actual state change. The cost per useful event is $432. Event-driven architecture inverts this: instead of asking 432,000 times and getting one answer, the system notifies you once when the answer changes. The cost per useful event drops to the cost of processing one webhook callback -- effectively zero.\n\n### Real-World Async Scenarios in Agent Commerce\n\nNot every agent transaction is a simple request-response. These are the scenarios where async patterns become essential:\n\n**Multi-day escrow evaluation.** A buyer agent creates an escrow for a data pipeline service with a 30-day evaluation period. The SLA requires 99.95% uptime measured over the full 30 days. The escrow cannot be released or disputed until the evaluation window closes. Synchronous polling for 30 days is absurd. An event-driven system subscribes to `escrow.evaluation_complete` and processes the release when the event fires.\n\n**Multi-party negotiation.** Three agents negotiate a supply chain arrangement. Agent A offers raw data. Agent B offers transformation services. Agent C wants transformed data. The negotiation involves six message exchanges over 12 minutes. In a synchronous model, each agent blocks a thread waiting for the next message. In an async model, each agent subscribes to `message.received` events and processes them as they arrive, freeing resources between exchanges.\n\n**Cascading service provisioning.** Agent A buys a service from Agent B, which in turn provisions a dependency from Agent C. Agent B cannot confirm delivery to Agent A until Agent C confirms delivery to Agent B. This is a distributed transaction that spans three agents and two escrows. Synchronous orchestration requires nested blocking calls. Async orchestration uses a saga pattern that coordinates the steps through events.\n\n**Dispute resolution.** Agent A opens a dispute against Agent B via `open_dispute`. Resolution may take hours -- it could involve automated evidence evaluation, third-party arbitration, or manual review. The disputing agent should not block a thread for hours waiting for `get_dispute` to return a resolved status. An event-driven system subscribes to `dispute.resolved` and handles the outcome when it arrives.\n\n**Batch settlement.** At the end of a billing cycle, an agent needs to settle 500 transactions simultaneously. Synchronous sequential processing takes 500 x 200ms = 100 seconds. Async concurrent processing with backpressure-controlled parallelism takes 10 seconds at 50 concurrent requests.\n\n### GreenHelix Async Primitives\n\nGreenHelix provides four primitives that enable event-driven architectures:\n\n**`publish_event`** -- Publishes a structured event to the GreenHelix event bus. Events are typed, timestamped, and associated with an agent ID. Other agents can subscribe to event streams filtered by type, agent, or custom attributes.\n\n**`subscribe_events`** -- Registers a subscription to an event stream. Returns events matching the subscription criteria. Supports long-polling (block until an event arrives or timeout) and cursor-based pagination for catching up on missed events.\n\n**Webhooks** -- GreenHelix can deliver events to an HTTPS endpoint you control. When an event matching your subscription fires, GreenHelix sends an HTTP POST to your webhook URL with the event payload. This is the lowest-latency notification mechanism -- you learn about state changes in milliseconds rather than polling intervals.\n\n**`send_message` \u002F `get_messages`** -- The messaging system provides point-to-point async communication between agents. Messages are stored until retrieved, providing natural buffering for agents that process messages at different rates.\n\n```\nEvent-Driven Architecture vs Synchronous Polling\n==================================================\n\nSYNCHRONOUS                          EVENT-DRIVEN\n┌──────────┐                        ┌──────────┐\n│  Agent A  │                        │  Agent A  │\n│           │  poll poll poll poll   │           │  subscribe once\n│  while:   │──────────────────────► │  await:   │──────────┐\n│    poll() │  \"changed?\" \"no\"      │    event  │          │\n│    sleep  │  \"changed?\" \"no\"      │           │          │\n│    poll() │  \"changed?\" \"yes!\"    │  (idle)   │          │\n│    sleep  │                        │           │          │\n│    poll() │                        │  handle() │◄─────────┘\n│    ...    │                        │           │  event fires\n└──────────┘                        └──────────┘\n\nAPI calls: 432,000\u002Fday              API calls: ~200\u002Fday\nLatency: up to poll interval        Latency: milliseconds\nCPU: constant                        CPU: on-demand\n```\n\nThese four primitives are the building blocks. The rest of this guide shows how to compose them into production-grade patterns for saga orchestration, compensating transactions, dead letter handling, exactly-once processing, backpressure management, and async escrow settlement.\n\n---\n\n## Chapter 2: AsyncEventBus Class\n\n### Event Publishing and Subscription\n\nThe `AsyncEventBus` class wraps the GreenHelix event primitives in an asyncio-native interface. It manages subscriptions, delivers events to registered handlers, acknowledges processed events, and handles connection failures gracefully.\n\nThe design follows the observer pattern: handlers register interest in specific event types, and the bus dispatches matching events to the appropriate handlers. Events are typed using a dot-notation hierarchy (`escrow.created`, `escrow.released`, `dispute.opened`, `sla.breached`) that supports both exact matching and prefix matching (subscribe to `escrow.*` to receive all escrow-related events).\n\n### Event Schemas and Typing\n\nEvery event on the bus conforms to a standard envelope schema:\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Any, Optional\nfrom datetime import datetime, timezone\nimport hashlib\nimport json\n\n\n@dataclass\nclass Event:\n    \"\"\"Standard event envelope for the GreenHelix event bus.\"\"\"\n    event_type: str                   # e.g. \"escrow.created\"\n    source_agent_id: str              # Agent that produced the event\n    payload: dict                      # Event-specific data\n    event_id: str = \"\"                 # Unique event identifier\n    timestamp: str = \"\"                # ISO 8601 timestamp\n    correlation_id: str = \"\"           # Links related events across a saga\n    sequence_number: int = 0           # Ordering within a partition\n\n    def __post_init__(self):\n        if not self.timestamp:\n            self.timestamp = datetime.now(timezone.utc).isoformat()\n        if not self.event_id:\n            raw = f\"{self.event_type}:{self.source_agent_id}:{self.timestamp}\"\n            self.event_id = hashlib.sha256(raw.encode()).hexdigest()[:24]\n\n    def to_dict(self) -> dict:\n        return {\n            \"event_id\": self.event_id,\n            \"event_type\": self.event_type,\n            \"source_agent_id\": self.source_agent_id,\n            \"timestamp\": self.timestamp,\n            \"correlation_id\": self.correlation_id,\n            \"sequence_number\": self.sequence_number,\n            \"payload\": self.payload,\n        }\n\n    @classmethod\n    def from_dict(cls, data: dict) -> \"Event\":\n        return cls(\n            event_id=data.get(\"event_id\", \"\"),\n            event_type=data[\"event_type\"],\n            source_agent_id=data[\"source_agent_id\"],\n            timestamp=data.get(\"timestamp\", \"\"),\n            correlation_id=data.get(\"correlation_id\", \"\"),\n            sequence_number=data.get(\"sequence_number\", 0),\n            payload=data.get(\"payload\", {}),\n        )\n```\n\n### The Complete AsyncEventBus\n\nThe bus maintains a registry of handlers keyed by event type pattern. When an event arrives, the bus matches it against all registered patterns and dispatches to matching handlers concurrently. Acknowledgments are sent after successful processing. Failed events are routed to a dead letter handler if one is registered.\n\n```python\nimport asyncio\nimport aiohttp\nimport logging\nfrom typing import Callable, Awaitable, Dict, List, Set\nfrom collections import defaultdict\n\nlogger = logging.getLogger(__name__)\n\nEventHandler = Callable[[Event], Awaitable[None]]\n\n\nclass AsyncEventBus:\n    \"\"\"Event bus client for GreenHelix with guaranteed delivery\n    and ordered processing.\n\n    Usage:\n        bus = AsyncEventBus(api_key=\"...\", agent_id=\"...\",)\n        bus.subscribe(\"escrow.created\", handle_escrow_created)\n        bus.subscribe(\"escrow.*\", handle_any_escrow_event)\n        await bus.start()\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n                 poll_interval: float = 1.0,\n                 max_concurrent_handlers: int = 10):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.poll_interval = poll_interval\n\n        # Handler registry: pattern -> list of handlers\n        self._handlers: Dict[str, List[EventHandler]] = defaultdict(list)\n        self._dead_letter_handler: Optional[EventHandler] = None\n\n        # Processing state\n        self._cursors: Dict[str, str] = {}   # subscription -> cursor\n        self._processed_ids: Set[str] = set()\n        self._semaphore = asyncio.Semaphore(max_concurrent_handlers)\n        self._running = False\n        self._session: Optional[aiohttp.ClientSession] = None\n        self._tasks: List[asyncio.Task] = []\n\n    def subscribe(self, event_pattern: str,\n                  handler: EventHandler) -> None:\n        \"\"\"Register a handler for an event pattern.\n\n        Patterns support trailing wildcards:\n          \"escrow.created\"  -- exact match\n          \"escrow.*\"        -- matches escrow.created, escrow.released, etc.\n          \"*\"               -- matches everything\n        \"\"\"\n        self._handlers[event_pattern].append(handler)\n        logger.info(f\"Subscribed handler to '{event_pattern}'\")\n\n    def set_dead_letter_handler(self,\n                                handler: EventHandler) -> None:\n        \"\"\"Register a handler for events that fail processing.\"\"\"\n        self._dead_letter_handler = handler\n\n    async def start(self) -> None:\n        \"\"\"Start the event bus. Polls for events and dispatches\n        to handlers.\"\"\"\n        self._running = True\n        self._session = aiohttp.ClientSession(\n            headers={\n                \"Content-Type\": \"application\u002Fjson\",\n                \"Authorization\": f\"Bearer {self.api_key}\",\n            }\n        )\n\n        # Register subscriptions with GreenHelix\n        for pattern in self._handlers:\n            await self._register_subscription(pattern)\n\n        # Start the polling loop\n        self._tasks.append(\n            asyncio.create_task(self._poll_loop())\n        )\n        logger.info(\"AsyncEventBus started\")\n\n    async def stop(self) -> None:\n        \"\"\"Gracefully stop the event bus.\"\"\"\n        self._running = False\n        for task in self._tasks:\n            task.cancel()\n        if self._session:\n            await self._session.close()\n        logger.info(\"AsyncEventBus stopped\")\n\n    async def publish(self, event: Event) -> dict:\n        \"\"\"Publish an event to the GreenHelix event bus.\"\"\"\n        async with self._session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\n                \"tool\": \"publish_event\",\n                \"input\": {\n                    \"agent_id\": self.agent_id,\n                    \"event_type\": event.event_type,\n                    \"payload\": json.dumps(event.to_dict()),\n                },\n            },\n        ) as resp:\n            resp.raise_for_status()\n            result = await resp.json()\n            logger.debug(f\"Published event: {event.event_type} \"\n                         f\"[{event.event_id}]\")\n            return result\n\n    async def _register_subscription(self, pattern: str) -> None:\n        \"\"\"Register an event subscription with GreenHelix.\"\"\"\n        async with self._session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\n                \"tool\": \"subscribe_events\",\n                \"input\": {\n                    \"agent_id\": self.agent_id,\n                    \"event_type\": pattern,\n                },\n            },\n        ) as resp:\n            resp.raise_for_status()\n            result = await resp.json()\n            cursor = result.get(\"cursor\", \"\")\n            self._cursors[pattern] = cursor\n            logger.info(f\"Registered subscription: {pattern} \"\n                        f\"(cursor: {cursor})\")\n\n    async def _poll_loop(self) -> None:\n        \"\"\"Continuously poll for new events.\"\"\"\n        while self._running:\n            try:\n                for pattern, cursor in list(self._cursors.items()):\n                    events = await self._fetch_events(pattern, cursor)\n                    for event_data in events:\n                        event = Event.from_dict(event_data)\n                        if event.event_id in self._processed_ids:\n                            continue\n                        await self._dispatch(event)\n            except asyncio.CancelledError:\n                break\n            except Exception as e:\n                logger.error(f\"Poll loop error: {e}\")\n            await asyncio.sleep(self.poll_interval)\n\n    async def _fetch_events(self, pattern: str,\n                            cursor: str) -> List[dict]:\n        \"\"\"Fetch new events from the subscription.\"\"\"\n        try:\n            async with self._session.post(\n                f\"{self.base_url}\u002Fv1\",\n                json={\n                    \"tool\": \"subscribe_events\",\n                    \"input\": {\n                        \"agent_id\": self.agent_id,\n                        \"event_type\": pattern,\n                        \"cursor\": cursor,\n                    },\n                },\n                timeout=aiohttp.ClientTimeout(total=30),\n            ) as resp:\n                resp.raise_for_status()\n                result = await resp.json()\n                # Update cursor for next poll\n                if result.get(\"cursor\"):\n                    self._cursors[pattern] = result[\"cursor\"]\n                return result.get(\"events\", [])\n        except asyncio.TimeoutError:\n            logger.debug(f\"Long-poll timeout for {pattern} (normal)\")\n            return []\n        except aiohttp.ClientError as e:\n            logger.warning(f\"Fetch error for {pattern}: {e}\")\n            return []\n\n    async def _dispatch(self, event: Event) -> None:\n        \"\"\"Dispatch an event to all matching handlers.\"\"\"\n        handlers = self._find_handlers(event.event_type)\n        if not handlers:\n            logger.warning(f\"No handlers for event type: \"\n                           f\"{event.event_type}\")\n            return\n\n        for handler in handlers:\n            async with self._semaphore:\n                try:\n                    await handler(event)\n                    self._processed_ids.add(event.event_id)\n                    await self._acknowledge(event)\n                except Exception as e:\n                    logger.error(\n                        f\"Handler failed for {event.event_id}: {e}\"\n                    )\n                    if self._dead_letter_handler:\n                        try:\n                            await self._dead_letter_handler(event)\n                        except Exception as dle:\n                            logger.error(\n                                f\"Dead letter handler failed: {dle}\"\n                            )\n\n    def _find_handlers(self, event_type: str) -> List[EventHandler]:\n        \"\"\"Find all handlers that match an event type.\"\"\"\n        matched = []\n        for pattern, handlers in self._handlers.items():\n            if self._pattern_matches(pattern, event_type):\n                matched.extend(handlers)\n        return matched\n\n    @staticmethod\n    def _pattern_matches(pattern: str, event_type: str) -> bool:\n        \"\"\"Check if an event type matches a subscription pattern.\"\"\"\n        if pattern == \"*\":\n            return True\n        if pattern.endswith(\".*\"):\n            prefix = pattern[:-2]\n            return event_type.startswith(prefix + \".\")\n        return pattern == event_type\n\n    async def _acknowledge(self, event: Event) -> None:\n        \"\"\"Acknowledge successful processing of an event.\"\"\"\n        try:\n            async with self._session.post(\n                f\"{self.base_url}\u002Fv1\",\n                json={\n                    \"tool\": \"publish_event\",\n                    \"input\": {\n                        \"agent_id\": self.agent_id,\n                        \"event_type\": \"system.event_ack\",\n                        \"payload\": json.dumps({\n                            \"acknowledged_event_id\": event.event_id,\n                            \"acknowledged_at\": datetime.now(\n                                timezone.utc\n                            ).isoformat(),\n                        }),\n                    },\n                },\n            ) as resp:\n                resp.raise_for_status()\n        except Exception as e:\n            logger.warning(f\"Ack failed for {event.event_id}: {e}\")\n```\n\n### Event Ordering and Partitioning\n\nEvents within a single agent's stream are ordered by sequence number. The bus processes them in order within a partition (defined by the source agent ID). Events from different agents can be processed concurrently because they belong to different partitions and have no ordering guarantees relative to each other.\n\nThe `max_concurrent_handlers` parameter controls how many events can be processed simultaneously across all partitions. Setting this to 1 gives you strict serial processing. Setting it to 50 gives you high throughput but requires your handlers to be safe for concurrent execution. The default of 10 is a reasonable starting point for most agent workloads.\n\n```python\n# Usage: start the event bus and register handlers\n\nasync def handle_escrow_created(event: Event) -> None:\n    \"\"\"React to a new escrow being created.\"\"\"\n    escrow_id = event.payload.get(\"escrow_id\")\n    amount = event.payload.get(\"amount\")\n    logger.info(f\"Escrow created: {escrow_id} for ${amount}\")\n    # Begin monitoring the escrow lifecycle...\n\n\nasync def handle_escrow_released(event: Event) -> None:\n    \"\"\"React to escrow funds being released.\"\"\"\n    escrow_id = event.payload.get(\"escrow_id\")\n    logger.info(f\"Escrow released: {escrow_id}\")\n    # Record the settlement in the ledger...\n\n\nasync def handle_sla_breached(event: Event) -> None:\n    \"\"\"React to an SLA breach detection.\"\"\"\n    sla_id = event.payload.get(\"sla_id\")\n    metric = event.payload.get(\"metric\")\n    actual = event.payload.get(\"actual_value\")\n    threshold = event.payload.get(\"threshold\")\n    logger.warning(f\"SLA breach: {sla_id} -- {metric} \"\n                   f\"is {actual}, threshold {threshold}\")\n    # Trigger compensating transaction...\n\n\nasync def main():\n    bus = AsyncEventBus(\n        api_key=\"your-api-key\",\n        agent_id=\"agent-buyer-042\",\n        poll_interval=2.0,\n        max_concurrent_handlers=10,\n    )\n\n    bus.subscribe(\"escrow.created\", handle_escrow_created)\n    bus.subscribe(\"escrow.released\", handle_escrow_released)\n    bus.subscribe(\"sla.breached\", handle_sla_breached)\n\n    await bus.start()\n\n    # Publish an event\n    await bus.publish(Event(\n        event_type=\"order.placed\",\n        source_agent_id=\"agent-buyer-042\",\n        correlation_id=\"saga-purchase-001\",\n        payload={\n            \"seller_id\": \"agent-seller-099\",\n            \"service\": \"data-pipeline-etl\",\n            \"amount\": \"500.00\",\n        },\n    ))\n\n    # Keep running until interrupted\n    try:\n        await asyncio.Event().wait()\n    finally:\n        await bus.stop()\n\n\n# asyncio.run(main())\n```\n\n---\n\n## Chapter 3: Saga Orchestrator Pattern\n\n### What Is a Saga?\n\nA saga is a distributed transaction decomposed into a sequence of local transactions, where each step has a corresponding compensating transaction that undoes its effect if a later step fails. The term comes from Hector Garcia-Molina's 1987 paper, but the pattern has become the standard approach for managing multi-step operations in microservice architectures -- and it maps perfectly onto multi-agent commerce.\n\nConsider a purchase transaction that involves five steps: (1) verify the buyer has sufficient balance, (2) create an escrow to hold funds, (3) register the service delivery SLA, (4) notify the seller to begin delivery, (5) record the transaction in the ledger. If step 4 fails -- the seller's agent is unreachable -- you cannot simply \"rollback\" the way a database transaction does. The escrow has already been created on the GreenHelix platform. The SLA has been registered. You need to explicitly undo each completed step in reverse order: cancel the SLA, release the escrow back to the buyer, and credit the balance reservation.\n\n```\nSaga: Purchase-Verify-Escrow-Deliver-Release\n==============================================\n\nFORWARD PATH (happy path):\n  Step 1: verify_balance ──► Step 2: create_escrow ──►\n  Step 3: create_sla ──► Step 4: notify_seller ──►\n  Step 5: record_transaction\n\nCOMPENSATING PATH (step 4 fails):\n  Step 4 fails ──►\n  Compensate 3: cancel_sla ──►\n  Compensate 2: release_escrow (refund) ──►\n  Compensate 1: unreserve_balance ──►\n  Saga FAILED (all effects reversed)\n```\n\n### The SagaOrchestrator Class\n\nThe orchestrator manages the state machine for a saga. Each saga instance tracks its current step, completed steps, and the compensation stack. The orchestrator advances through steps sequentially, pushing each completed step onto the compensation stack. If any step fails, it pops the stack and executes compensations in reverse order.\n\n```python\nimport asyncio\nimport json\nimport logging\nimport time\nfrom dataclasses import dataclass, field\nfrom datetime import datetime, timezone\nfrom enum import Enum\nfrom typing import (\n    Any, Awaitable, Callable, Dict, List, Optional, Tuple,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass SagaState(Enum):\n    PENDING = \"pending\"\n    RUNNING = \"running\"\n    COMPLETED = \"completed\"\n    COMPENSATING = \"compensating\"\n    FAILED = \"failed\"\n    COMPENSATION_FAILED = \"compensation_failed\"\n\n\n@dataclass\nclass SagaStep:\n    \"\"\"A single step in a saga with its compensating action.\"\"\"\n    name: str\n    execute: Callable[[dict], Awaitable[dict]]\n    compensate: Callable[[dict], Awaitable[None]]\n    timeout_seconds: float = 30.0\n    max_retries: int = 3\n    retry_delay_seconds: float = 1.0\n\n\n@dataclass\nclass SagaInstance:\n    \"\"\"Runtime state of a saga execution.\"\"\"\n    saga_id: str\n    correlation_id: str\n    state: SagaState = SagaState.PENDING\n    current_step: int = 0\n    context: dict = field(default_factory=dict)\n    completed_steps: List[str] = field(default_factory=list)\n    compensation_stack: List[Tuple[str, dict]] = field(\n        default_factory=list\n    )\n    error: Optional[str] = None\n    started_at: Optional[str] = None\n    completed_at: Optional[str] = None\n\n\nclass SagaOrchestrator:\n    \"\"\"Orchestrates multi-step agent transactions as sagas.\n\n    Each saga is a sequence of steps. Each step has:\n      - An execute function that performs the step's work\n      - A compensate function that undoes the step's effects\n      - Timeout and retry configuration\n\n    The orchestrator advances through steps, tracks state,\n    and handles failures by executing compensations in\n    reverse order.\n    \"\"\"\n\n    def __init__(self, event_bus: AsyncEventBus):\n        self.event_bus = event_bus\n        self._sagas: Dict[str, SagaInstance] = {}\n        self._step_definitions: Dict[str, List[SagaStep]] = {}\n\n    def define_saga(self, saga_type: str,\n                    steps: List[SagaStep]) -> None:\n        \"\"\"Define a saga type with its ordered steps.\"\"\"\n        self._step_definitions[saga_type] = steps\n        logger.info(f\"Defined saga '{saga_type}' with \"\n                    f\"{len(steps)} steps\")\n\n    async def start_saga(self, saga_type: str,\n                         saga_id: str,\n                         correlation_id: str,\n                         initial_context: dict) -> SagaInstance:\n        \"\"\"Start a new saga instance.\"\"\"\n        if saga_type not in self._step_definitions:\n            raise ValueError(f\"Unknown saga type: {saga_type}\")\n\n        instance = SagaInstance(\n            saga_id=saga_id,\n            correlation_id=correlation_id,\n            state=SagaState.RUNNING,\n            context=initial_context,\n            started_at=datetime.now(timezone.utc).isoformat(),\n        )\n        self._sagas[saga_id] = instance\n\n        await self.event_bus.publish(Event(\n            event_type=\"saga.started\",\n            source_agent_id=self.event_bus.agent_id,\n            correlation_id=correlation_id,\n            payload={\n                \"saga_id\": saga_id,\n                \"saga_type\": saga_type,\n                \"steps\": [s.name for s\n                          in self._step_definitions[saga_type]],\n            },\n        ))\n\n        # Execute steps\n        steps = self._step_definitions[saga_type]\n        for i, step in enumerate(steps):\n            instance.current_step = i\n\n            try:\n                result = await self._execute_step(\n                    instance, step\n                )\n                # Store step result in context for subsequent steps\n                instance.context[f\"step_{step.name}_result\"] = result\n                instance.completed_steps.append(step.name)\n                instance.compensation_stack.append(\n                    (step.name, instance.context.copy())\n                )\n\n                await self.event_bus.publish(Event(\n                    event_type=\"saga.step_completed\",\n                    source_agent_id=self.event_bus.agent_id,\n                    correlation_id=correlation_id,\n                    payload={\n                        \"saga_id\": saga_id,\n                        \"step\": step.name,\n                        \"step_index\": i,\n                        \"result\": result,\n                    },\n                ))\n\n            except Exception as e:\n                logger.error(\n                    f\"Saga {saga_id} step '{step.name}' failed: {e}\"\n                )\n                instance.error = str(e)\n\n                await self.event_bus.publish(Event(\n                    event_type=\"saga.step_failed\",\n                    source_agent_id=self.event_bus.agent_id,\n                    correlation_id=correlation_id,\n                    payload={\n                        \"saga_id\": saga_id,\n                        \"step\": step.name,\n                        \"error\": str(e),\n                    },\n                ))\n\n                # Begin compensation\n                await self._compensate(instance, steps)\n                return instance\n\n        # All steps completed successfully\n        instance.state = SagaState.COMPLETED\n        instance.completed_at = datetime.now(timezone.utc).isoformat()\n\n        await self.event_bus.publish(Event(\n            event_type=\"saga.completed\",\n            source_agent_id=self.event_bus.agent_id,\n            correlation_id=correlation_id,\n            payload={\n                \"saga_id\": saga_id,\n                \"completed_steps\": instance.completed_steps,\n            },\n        ))\n\n        return instance\n\n    async def _execute_step(self, instance: SagaInstance,\n                            step: SagaStep) -> dict:\n        \"\"\"Execute a single saga step with retries and timeout.\"\"\"\n        last_error = None\n        for attempt in range(step.max_retries):\n            try:\n                result = await asyncio.wait_for(\n                    step.execute(instance.context),\n                    timeout=step.timeout_seconds,\n                )\n                return result\n            except asyncio.TimeoutError:\n                last_error = (\n                    f\"Step '{step.name}' timed out after \"\n                    f\"{step.timeout_seconds}s\"\n                )\n                logger.warning(\n                    f\"{last_error} (attempt {attempt + 1}\u002F\"\n                    f\"{step.max_retries})\"\n                )\n            except Exception as e:\n                last_error = str(e)\n                logger.warning(\n                    f\"Step '{step.name}' failed: {e} \"\n                    f\"(attempt {attempt + 1}\u002F{step.max_retries})\"\n                )\n\n            if attempt \u003C step.max_retries - 1:\n                delay = step.retry_delay_seconds * (2 ** attempt)\n                await asyncio.sleep(delay)\n\n        raise RuntimeError(\n            f\"Step '{step.name}' failed after \"\n            f\"{step.max_retries} attempts: {last_error}\"\n        )\n\n    async def _compensate(self, instance: SagaInstance,\n                          steps: List[SagaStep]) -> None:\n        \"\"\"Execute compensating transactions in reverse order.\"\"\"\n        instance.state = SagaState.COMPENSATING\n\n        while instance.compensation_stack:\n            step_name, step_context = (\n                instance.compensation_stack.pop()\n            )\n            step_def = next(\n                s for s in steps if s.name == step_name\n            )\n\n            try:\n                await asyncio.wait_for(\n                    step_def.compensate(step_context),\n                    timeout=step_def.timeout_seconds,\n                )\n                logger.info(\n                    f\"Saga {instance.saga_id}: compensated \"\n                    f\"'{step_name}'\"\n                )\n\n                await self.event_bus.publish(Event(\n                    event_type=\"saga.step_compensated\",\n                    source_agent_id=self.event_bus.agent_id,\n                    correlation_id=instance.correlation_id,\n                    payload={\n                        \"saga_id\": instance.saga_id,\n                        \"step\": step_name,\n                    },\n                ))\n\n            except Exception as e:\n                logger.error(\n                    f\"Saga {instance.saga_id}: compensation \"\n                    f\"of '{step_name}' FAILED: {e}\"\n                )\n                instance.state = SagaState.COMPENSATION_FAILED\n                instance.error = (\n                    f\"Compensation failed at '{step_name}': {e}\"\n                )\n\n                await self.event_bus.publish(Event(\n                    event_type=\"saga.compensation_failed\",\n                    source_agent_id=self.event_bus.agent_id,\n                    correlation_id=instance.correlation_id,\n                    payload={\n                        \"saga_id\": instance.saga_id,\n                        \"step\": step_name,\n                        \"error\": str(e),\n                        \"remaining_compensations\": [\n                            s for s, _ in\n                            instance.compensation_stack\n                        ],\n                    },\n                ))\n                return\n\n        instance.state = SagaState.FAILED\n        instance.completed_at = datetime.now(timezone.utc).isoformat()\n\n        await self.event_bus.publish(Event(\n            event_type=\"saga.failed\",\n            source_agent_id=self.event_bus.agent_id,\n            correlation_id=instance.correlation_id,\n            payload={\n                \"saga_id\": instance.saga_id,\n                \"original_error\": instance.error,\n                \"compensated_steps\": instance.completed_steps,\n            },\n        ))\n\n    def get_saga(self, saga_id: str) -> Optional[SagaInstance]:\n        \"\"\"Retrieve the current state of a saga.\"\"\"\n        return self._sagas.get(saga_id)\n```\n\n### Example: Purchase-Verify-Escrow-Deliver-Release Saga\n\nHere is a complete saga definition for a standard agent commerce purchase. Each step's execute function calls the GreenHelix API, and each compensation function reverses the effect.\n\n```python\nimport aiohttp\n\nasync def make_api_call(session: aiohttp.ClientSession,\n                        base_url: str, tool: str,\n                        input_data: dict) -> dict:\n    \"\"\"Helper to call a GreenHelix tool asynchronously.\"\"\"\n    async with session.post(\n        f\"{base_url}\u002Fv1\",\n        json={\"tool\": tool, \"input\": input_data},\n    ) as resp:\n        resp.raise_for_status()\n        return await resp.json()\n\n\ndef build_purchase_saga(session: aiohttp.ClientSession,\n                        base_url: str,\n                        buyer_id: str) -> List[SagaStep]:\n    \"\"\"Build the step definitions for a purchase saga.\"\"\"\n\n    async def verify_balance(ctx: dict) -> dict:\n        result = await make_api_call(session, base_url,\n            \"get_balance\", {\"agent_id\": buyer_id})\n        balance = float(result.get(\"balance\", 0))\n        required = float(ctx[\"amount\"])\n        if balance \u003C required:\n            raise ValueError(\n                f\"Insufficient balance: {balance} \u003C {required}\"\n            )\n        return {\"verified_balance\": balance}\n\n    async def unreserve_balance(ctx: dict) -> None:\n        # Balance verification has no side effect to undo\n        pass\n\n    async def create_escrow(ctx: dict) -> dict:\n        result = await make_api_call(session, base_url,\n            \"create_escrow\", {\n                \"agent_id\": buyer_id,\n                \"counterparty_id\": ctx[\"seller_id\"],\n                \"amount\": ctx[\"amount\"],\n                \"currency\": \"USD\",\n                \"conditions\": json.dumps({\n                    \"service\": ctx[\"service_id\"],\n                    \"evaluation_days\": ctx.get(\n                        \"evaluation_days\", 7\n                    ),\n                }),\n            })\n        return {\"escrow_id\": result.get(\"escrow_id\")}\n\n    async def cancel_escrow(ctx: dict) -> None:\n        escrow_id = ctx.get(\"step_create_escrow_result\", {}).get(\n            \"escrow_id\"\n        )\n        if escrow_id:\n            await make_api_call(session, base_url,\n                \"release_escrow\", {\n                    \"agent_id\": buyer_id,\n                    \"escrow_id\": escrow_id,\n                    \"release_to\": buyer_id,\n                    \"reason\": \"saga_compensation\",\n                })\n\n    async def create_sla(ctx: dict) -> dict:\n        result = await make_api_call(session, base_url,\n            \"create_sla\", {\n                \"agent_id\": buyer_id,\n                \"provider_id\": ctx[\"seller_id\"],\n                \"metric\": ctx.get(\"sla_metric\", \"uptime\"),\n                \"threshold\": str(ctx.get(\n                    \"sla_threshold\", 99.9\n                )),\n                \"window_hours\": str(ctx.get(\n                    \"sla_window_hours\", 720\n                )),\n            })\n        return {\"sla_id\": result.get(\"sla_id\")}\n\n    async def cancel_sla(ctx: dict) -> None:\n        # SLA cancellation: record the cancellation\n        sla_id = ctx.get(\"step_create_sla_result\", {}).get(\n            \"sla_id\"\n        )\n        if sla_id:\n            await make_api_call(session, base_url,\n                \"record_transaction\", {\n                    \"agent_id\": buyer_id,\n                    \"transaction_type\": \"sla_cancelled\",\n                    \"amount\": \"0\",\n                    \"currency\": \"USD\",\n                    \"metadata\": json.dumps({\n                        \"sla_id\": sla_id,\n                        \"reason\": \"saga_compensation\",\n                    }),\n                })\n\n    async def notify_seller(ctx: dict) -> dict:\n        escrow_id = ctx.get(\"step_create_escrow_result\", {}).get(\n            \"escrow_id\"\n        )\n        sla_id = ctx.get(\"step_create_sla_result\", {}).get(\n            \"sla_id\"\n        )\n        result = await make_api_call(session, base_url,\n            \"send_message\", {\n                \"sender_id\": buyer_id,\n                \"receiver_id\": ctx[\"seller_id\"],\n                \"message_type\": \"delivery_request\",\n                \"content\": json.dumps({\n                    \"escrow_id\": escrow_id,\n                    \"sla_id\": sla_id,\n                    \"service_id\": ctx[\"service_id\"],\n                    \"delivery_deadline\": ctx.get(\n                        \"delivery_deadline\"\n                    ),\n                }),\n            })\n        return {\"message_id\": result.get(\"message_id\")}\n\n    async def cancel_notification(ctx: dict) -> None:\n        await make_api_call(session, base_url,\n            \"send_message\", {\n                \"sender_id\": buyer_id,\n                \"receiver_id\": ctx[\"seller_id\"],\n                \"message_type\": \"delivery_cancelled\",\n                \"content\": json.dumps({\n                    \"reason\": \"saga_compensation\",\n                    \"original_service\": ctx[\"service_id\"],\n                }),\n            })\n\n    async def record_transaction(ctx: dict) -> dict:\n        escrow_id = ctx.get(\"step_create_escrow_result\", {}).get(\n            \"escrow_id\"\n        )\n        result = await make_api_call(session, base_url,\n            \"record_transaction\", {\n                \"agent_id\": buyer_id,\n                \"transaction_type\": \"purchase\",\n                \"amount\": ctx[\"amount\"],\n                \"currency\": \"USD\",\n                \"counterparty_id\": ctx[\"seller_id\"],\n                \"metadata\": json.dumps({\n                    \"escrow_id\": escrow_id,\n                    \"service_id\": ctx[\"service_id\"],\n                }),\n            })\n        return {\"transaction_id\": result.get(\"transaction_id\")}\n\n    async def void_transaction(ctx: dict) -> None:\n        tx_id = ctx.get(\n            \"step_record_transaction_result\", {}\n        ).get(\"transaction_id\")\n        if tx_id:\n            await make_api_call(session, base_url,\n                \"record_transaction\", {\n                    \"agent_id\": buyer_id,\n                    \"transaction_type\": \"purchase_voided\",\n                    \"amount\": ctx[\"amount\"],\n                    \"currency\": \"USD\",\n                    \"counterparty_id\": ctx[\"seller_id\"],\n                    \"metadata\": json.dumps({\n                        \"voided_transaction_id\": tx_id,\n                        \"reason\": \"saga_compensation\",\n                    }),\n                })\n\n    return [\n        SagaStep(\"verify_balance\", verify_balance,\n                 unreserve_balance, timeout_seconds=10.0),\n        SagaStep(\"create_escrow\", create_escrow,\n                 cancel_escrow, timeout_seconds=30.0),\n        SagaStep(\"create_sla\", create_sla,\n                 cancel_sla, timeout_seconds=30.0),\n        SagaStep(\"notify_seller\", notify_seller,\n                 cancel_notification, timeout_seconds=15.0),\n        SagaStep(\"record_transaction\", record_transaction,\n                 void_transaction, timeout_seconds=15.0),\n    ]\n```\n\nThe saga state machine transitions are deterministic:\n\n```\n  PENDING ──start──► RUNNING\n                        │\n              ┌─────────┼──────────┐\n              │ all steps succeed   │ a step fails\n              ▼                     ▼\n          COMPLETED           COMPENSATING\n                                    │\n                          ┌─────────┼──────────┐\n                          │ all compensations  │ compensation\n                          │ succeed            │ fails\n                          ▼                     ▼\n                       FAILED            COMPENSATION_FAILED\n                  (clean failure)      (requires manual intervention)\n```\n\n`COMPENSATION_FAILED` is the state you never want to reach. It means the saga could not undo its partial effects, leaving the system in an inconsistent state. The dead letter handling system (Chapter 5) is designed to catch these cases and alert operators.\n\n---\n\n## Chapter 4: Compensating Transactions\n\n### What Happens When Step 4 of 6 Fails?\n\nThe saga orchestrator handles the mechanics of running compensations in reverse order. But the hard part is designing the compensating transactions themselves. Each compensation must satisfy three properties: it must be **idempotent** (safe to run multiple times), **commutative** with respect to other compensations (the order should not matter for the final state, though we execute in reverse for consistency), and **eventually consistent** (it is acceptable for the system to pass through intermediate inconsistent states as long as all compensations eventually complete).\n\nConsider the failure scenario in detail. A buyer agent is executing a five-step purchase saga. Steps 1-3 complete successfully: balance verified, escrow created with $500 locked, SLA registered. Step 4 -- notifying the seller to begin delivery -- fails because the seller's agent is unreachable. The system is now in an inconsistent state: $500 is locked in escrow for a service that will never be delivered, and an SLA is monitoring a provider that has not acknowledged the order.\n\nThe compensation sequence:\n\n1. **Compensate step 3 (cancel SLA):** The SLA was registered via `create_sla`. GreenHelix does not have a `delete_sla` tool, so compensation records a cancellation event via `record_transaction` with type `sla_cancelled`. The SLA technically still exists on the platform, but the cancellation record serves as an audit trail, and the monitoring system can filter out cancelled SLAs.\n\n2. **Compensate step 2 (release escrow):** The escrow was created via `create_escrow`. Compensation calls `release_escrow` with `release_to` set to the buyer's agent ID, returning the $500 to the buyer. This is the critical compensation -- if this fails, real money is stuck in limbo.\n\n3. **Compensate step 1 (unreserve balance):** Balance verification was a read-only check with no side effects. The compensation is a no-op.\n\n### The CompensatingTransaction Class\n\nFor complex compensations that involve multiple API calls, the `CompensatingTransaction` class provides structure:\n\n```python\n@dataclass\nclass CompensationRecord:\n    \"\"\"Record of a single compensation attempt.\"\"\"\n    step_name: str\n    attempted_at: str\n    succeeded: bool\n    error: Optional[str] = None\n    retry_count: int = 0\n    idempotency_key: str = \"\"\n\n\nclass CompensatingTransaction:\n    \"\"\"Manages compensating transactions for a failed saga.\n\n    Handles:\n      - Idempotent compensation execution\n      - Retry with exponential backoff\n      - Compensation audit trail\n      - Escalation on repeated failure\n    \"\"\"\n\n    def __init__(self, session: aiohttp.ClientSession,\n                 base_url: str, agent_id: str,\n                 event_bus: AsyncEventBus):\n        self.session = session\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.event_bus = event_bus\n        self._records: List[CompensationRecord] = []\n\n    async def compensate_escrow(self, escrow_id: str,\n                                buyer_id: str,\n                                amount: str,\n                                idempotency_key: str) -> dict:\n        \"\"\"Release escrow funds back to the buyer.\n\n        This is the most critical compensation -- funds must\n        not remain locked.\n        \"\"\"\n        record = CompensationRecord(\n            step_name=\"release_escrow\",\n            attempted_at=datetime.now(timezone.utc).isoformat(),\n            succeeded=False,\n            idempotency_key=idempotency_key,\n        )\n\n        max_retries = 5\n        for attempt in range(max_retries):\n            try:\n                result = await make_api_call(\n                    self.session, self.base_url,\n                    \"release_escrow\", {\n                        \"agent_id\": buyer_id,\n                        \"escrow_id\": escrow_id,\n                        \"release_to\": buyer_id,\n                        \"reason\": \"saga_compensation\",\n                        \"idempotency_key\": idempotency_key,\n                    },\n                )\n                record.succeeded = True\n                record.retry_count = attempt\n                self._records.append(record)\n\n                await self.event_bus.publish(Event(\n                    event_type=\"compensation.escrow_released\",\n                    source_agent_id=self.agent_id,\n                    payload={\n                        \"escrow_id\": escrow_id,\n                        \"amount\": amount,\n                        \"released_to\": buyer_id,\n                        \"idempotency_key\": idempotency_key,\n                    },\n                ))\n                return result\n\n            except Exception as e:\n                record.error = str(e)\n                record.retry_count = attempt + 1\n                delay = min(2 ** attempt, 30)\n                logger.warning(\n                    f\"Escrow compensation failed (attempt \"\n                    f\"{attempt + 1}\u002F{max_retries}): {e}\"\n                )\n                if attempt \u003C max_retries - 1:\n                    await asyncio.sleep(delay)\n\n        # All retries exhausted -- escalate\n        record.succeeded = False\n        self._records.append(record)\n        await self._escalate(\n            \"escrow_release_failed\",\n            {\n                \"escrow_id\": escrow_id,\n                \"amount\": amount,\n                \"buyer_id\": buyer_id,\n                \"attempts\": max_retries,\n                \"last_error\": record.error,\n            },\n        )\n        raise RuntimeError(\n            f\"Failed to release escrow {escrow_id} after \"\n            f\"{max_retries} attempts\"\n        )\n\n    async def compensate_payment(self, transaction_id: str,\n                                 amount: str,\n                                 payer_id: str,\n                                 payee_id: str,\n                                 idempotency_key: str) -> dict:\n        \"\"\"Reverse a payment by recording a refund transaction.\"\"\"\n        result = await make_api_call(\n            self.session, self.base_url,\n            \"record_transaction\", {\n                \"agent_id\": payer_id,\n                \"transaction_type\": \"refund\",\n                \"amount\": amount,\n                \"currency\": \"USD\",\n                \"counterparty_id\": payee_id,\n                \"metadata\": json.dumps({\n                    \"original_transaction_id\": transaction_id,\n                    \"reason\": \"saga_compensation\",\n                    \"idempotency_key\": idempotency_key,\n                }),\n            },\n        )\n\n        record = CompensationRecord(\n            step_name=\"refund_payment\",\n            attempted_at=datetime.now(timezone.utc).isoformat(),\n            succeeded=True,\n            idempotency_key=idempotency_key,\n        )\n        self._records.append(record)\n        return result\n\n    async def compensate_service_registration(\n        self, service_id: str,\n        agent_id: str,\n        idempotency_key: str,\n    ) -> dict:\n        \"\"\"Deregister a service that was registered as part\n        of the saga.\"\"\"\n        result = await make_api_call(\n            self.session, self.base_url,\n            \"record_transaction\", {\n                \"agent_id\": agent_id,\n                \"transaction_type\": \"service_deregistered\",\n                \"amount\": \"0\",\n                \"currency\": \"USD\",\n                \"metadata\": json.dumps({\n                    \"service_id\": service_id,\n                    \"reason\": \"saga_compensation\",\n                    \"idempotency_key\": idempotency_key,\n                }),\n            },\n        )\n\n        record = CompensationRecord(\n            step_name=\"deregister_service\",\n            attempted_at=datetime.now(timezone.utc).isoformat(),\n            succeeded=True,\n            idempotency_key=idempotency_key,\n        )\n        self._records.append(record)\n        return result\n\n    async def _escalate(self, failure_type: str,\n                        details: dict) -> None:\n        \"\"\"Escalate a compensation failure for manual\n        intervention.\"\"\"\n        await self.event_bus.publish(Event(\n            event_type=\"compensation.escalation_required\",\n            source_agent_id=self.agent_id,\n            payload={\n                \"failure_type\": failure_type,\n                \"details\": details,\n                \"compensation_history\": [\n                    {\n                        \"step\": r.step_name,\n                        \"succeeded\": r.succeeded,\n                        \"retries\": r.retry_count,\n                        \"error\": r.error,\n                    }\n                    for r in self._records\n                ],\n                \"escalated_at\": datetime.now(\n                    timezone.utc\n                ).isoformat(),\n            },\n        ))\n        logger.critical(\n            f\"COMPENSATION ESCALATION: {failure_type} -- \"\n            f\"{json.dumps(details)}\"\n        )\n\n    def get_compensation_report(self) -> dict:\n        \"\"\"Return a summary of all compensation actions taken.\"\"\"\n        return {\n            \"total_compensations\": len(self._records),\n            \"succeeded\": sum(\n                1 for r in self._records if r.succeeded\n            ),\n            \"failed\": sum(\n                1 for r in self._records if not r.succeeded\n            ),\n            \"records\": [\n                {\n                    \"step\": r.step_name,\n                    \"succeeded\": r.succeeded,\n                    \"retries\": r.retry_count,\n                    \"error\": r.error,\n                    \"idempotency_key\": r.idempotency_key,\n                }\n                for r in self._records\n            ],\n        }\n```\n\n### Idempotency Requirements\n\nEvery compensating transaction must be idempotent. If the compensation for \"release escrow\" is called twice -- because the first call succeeded on the server but the response was lost due to a network timeout -- the second call must not release the escrow a second time or fail with an error. The `idempotency_key` parameter handles this at the API level: GreenHelix deduplicates calls with the same idempotency key and returns the result of the original call.\n\nThe key generation strategy matters. A good idempotency key for a compensation is deterministic from the saga context: `f\"compensate:{saga_id}:{step_name}\"`. This ensures that retrying the same compensation for the same saga step always produces the same key, regardless of how many times the retry logic executes.\n\n```python\ndef make_compensation_key(saga_id: str, step_name: str) -> str:\n    \"\"\"Generate a deterministic idempotency key for a\n    compensation action.\"\"\"\n    raw = f\"compensate:{saga_id}:{step_name}\"\n    return hashlib.sha256(raw.encode()).hexdigest()[:32]\n\n\n# Usage in a saga compensation:\nkey = make_compensation_key(\"saga-purchase-001\", \"create_escrow\")\n# key: \"a1b2c3d4...\" -- same every time for this saga+step\nawait compensator.compensate_escrow(\n    escrow_id=\"esc_xyz\",\n    buyer_id=\"agent-buyer-042\",\n    amount=\"500.00\",\n    idempotency_key=key,\n)\n```\n\n---\n\n## Chapter 5: Dead Letter Handling\n\n### Events That Cannot Be Processed\n\nA dead letter is an event that has been attempted and failed multiple times. The event itself is well-formed -- it passes schema validation, it was published by a legitimate agent, and the event bus delivered it successfully. But the handler that received it could not process it. Maybe the handler depends on an external service that is down. Maybe the event references an entity that does not exist yet (a race condition). Maybe the handler has a bug that throws an exception for this specific payload.\n\nDead letters are inevitable in any event-driven system. The question is not whether they will occur but how you handle them when they do. The wrong answer is to silently drop them. The right answer is a dead letter queue (DLQ) with configurable retry policies, monitoring, and manual intervention workflows.\n\n### Dead Letter Queue Implementation\n\n```python\n@dataclass\nclass DeadLetter:\n    \"\"\"An event that failed processing.\"\"\"\n    event: Event\n    error: str\n    handler_name: str\n    first_failed_at: str\n    last_failed_at: str\n    attempt_count: int\n    next_retry_at: Optional[str] = None\n    status: str = \"pending\"   # pending, retrying, exhausted, resolved\n\n\nclass DeadLetterQueue:\n    \"\"\"Dead letter queue with retry policies and alerting.\n\n    Failed events are stored in the DLQ with their failure\n    metadata. The queue supports three retry policies:\n      - immediate: retry once immediately\n      - exponential_backoff: retry with increasing delays\n      - circuit_breaker: stop retrying after threshold\n\n    Events that exhaust all retry attempts are marked\n    'exhausted' and require manual intervention.\n    \"\"\"\n\n    def __init__(self, event_bus: AsyncEventBus,\n                 max_retries: int = 5,\n                 base_delay_seconds: float = 5.0,\n                 max_delay_seconds: float = 300.0,\n                 circuit_breaker_threshold: int = 10):\n        self.event_bus = event_bus\n        self.max_retries = max_retries\n        self.base_delay = base_delay_seconds\n        self.max_delay = max_delay_seconds\n        self.circuit_breaker_threshold = circuit_breaker_threshold\n\n        self._queue: Dict[str, DeadLetter] = {}\n        self._failure_counts: Dict[str, int] = defaultdict(int)\n        self._circuit_open: Dict[str, bool] = {}\n        self._handlers: Dict[str, EventHandler] = {}\n        self._running = False\n\n    async def enqueue(self, event: Event, error: str,\n                      handler_name: str) -> None:\n        \"\"\"Add a failed event to the dead letter queue.\"\"\"\n        now = datetime.now(timezone.utc).isoformat()\n\n        if event.event_id in self._queue:\n            dl = self._queue[event.event_id]\n            dl.attempt_count += 1\n            dl.last_failed_at = now\n            dl.error = error\n        else:\n            dl = DeadLetter(\n                event=event,\n                error=error,\n                handler_name=handler_name,\n                first_failed_at=now,\n                last_failed_at=now,\n                attempt_count=1,\n            )\n            self._queue[event.event_id] = dl\n\n        # Update circuit breaker state\n        self._failure_counts[handler_name] += 1\n        if (self._failure_counts[handler_name]\n                >= self.circuit_breaker_threshold):\n            self._circuit_open[handler_name] = True\n            logger.critical(\n                f\"Circuit breaker OPEN for handler \"\n                f\"'{handler_name}' -- \"\n                f\"{self._failure_counts[handler_name]} failures\"\n            )\n\n        # Schedule retry or mark exhausted\n        if dl.attempt_count >= self.max_retries:\n            dl.status = \"exhausted\"\n            await self._alert_exhausted(dl)\n        else:\n            delay = self._calculate_delay(dl.attempt_count)\n            retry_at = datetime.now(timezone.utc)\n            dl.next_retry_at = retry_at.isoformat()\n            dl.status = \"pending\"\n\n        await self.event_bus.publish(Event(\n            event_type=\"dlq.event_enqueued\",\n            source_agent_id=self.event_bus.agent_id,\n            payload={\n                \"dead_letter_event_id\": event.event_id,\n                \"event_type\": event.event_type,\n                \"attempt_count\": dl.attempt_count,\n                \"status\": dl.status,\n                \"error\": error,\n            },\n        ))\n\n        logger.warning(\n            f\"DLQ: {event.event_type} [{event.event_id}] -- \"\n            f\"attempt {dl.attempt_count}\u002F{self.max_retries} -- \"\n            f\"{error}\"\n        )\n\n    def _calculate_delay(self, attempt: int) -> float:\n        \"\"\"Calculate retry delay with exponential backoff\n        and jitter.\"\"\"\n        import random\n        delay = self.base_delay * (2 ** (attempt - 1))\n        delay = min(delay, self.max_delay)\n        jitter = random.uniform(0, delay * 0.1)\n        return delay + jitter\n\n    async def start_retry_loop(self,\n                               handlers: Dict[\n                                   str, EventHandler\n                               ]) -> None:\n        \"\"\"Start the background retry loop.\"\"\"\n        self._handlers = handlers\n        self._running = True\n        asyncio.create_task(self._retry_loop())\n\n    async def _retry_loop(self) -> None:\n        \"\"\"Process pending dead letters on schedule.\"\"\"\n        while self._running:\n            now = datetime.now(timezone.utc).isoformat()\n            for event_id, dl in list(self._queue.items()):\n                if dl.status != \"pending\":\n                    continue\n                if dl.next_retry_at and dl.next_retry_at > now:\n                    continue\n\n                handler_name = dl.handler_name\n                if self._circuit_open.get(handler_name, False):\n                    logger.debug(\n                        f\"Skipping retry: circuit open for \"\n                        f\"'{handler_name}'\"\n                    )\n                    continue\n\n                handler = self._handlers.get(handler_name)\n                if not handler:\n                    continue\n\n                dl.status = \"retrying\"\n                try:\n                    await handler(dl.event)\n                    dl.status = \"resolved\"\n                    logger.info(\n                        f\"DLQ: resolved {dl.event.event_id} \"\n                        f\"on attempt {dl.attempt_count + 1}\"\n                    )\n                    # Reset circuit breaker on success\n                    self._failure_counts[handler_name] = max(\n                        0,\n                        self._failure_counts[handler_name] - 1,\n                    )\n                    if self._failure_counts[handler_name] == 0:\n                        self._circuit_open[handler_name] = False\n\n                except Exception as e:\n                    await self.enqueue(\n                        dl.event, str(e), handler_name\n                    )\n\n            await asyncio.sleep(1.0)\n\n    async def _alert_exhausted(self, dl: DeadLetter) -> None:\n        \"\"\"Alert that an event has exhausted all retries.\"\"\"\n        await self.event_bus.publish(Event(\n            event_type=\"dlq.exhausted\",\n            source_agent_id=self.event_bus.agent_id,\n            payload={\n                \"event_id\": dl.event.event_id,\n                \"event_type\": dl.event.event_type,\n                \"handler\": dl.handler_name,\n                \"attempts\": dl.attempt_count,\n                \"first_failed\": dl.first_failed_at,\n                \"last_failed\": dl.last_failed_at,\n                \"last_error\": dl.error,\n                \"action_required\": \"manual_intervention\",\n            },\n        ))\n        logger.critical(\n            f\"DLQ EXHAUSTED: {dl.event.event_type} \"\n            f\"[{dl.event.event_id}] after {dl.attempt_count} \"\n            f\"attempts -- manual intervention required\"\n        )\n\n    def get_queue_depth(self) -> dict:\n        \"\"\"Return current DLQ metrics.\"\"\"\n        by_status = defaultdict(int)\n        by_handler = defaultdict(int)\n        for dl in self._queue.values():\n            by_status[dl.status] += 1\n            by_handler[dl.handler_name] += 1\n\n        return {\n            \"total\": len(self._queue),\n            \"by_status\": dict(by_status),\n            \"by_handler\": dict(by_handler),\n            \"circuit_breakers\": {\n                k: \"open\" if v else \"closed\"\n                for k, v in self._circuit_open.items()\n            },\n        }\n\n    async def resolve_manually(self, event_id: str,\n                               resolution: str) -> None:\n        \"\"\"Mark a dead letter as manually resolved.\"\"\"\n        if event_id in self._queue:\n            dl = self._queue[event_id]\n            dl.status = \"resolved\"\n            await self.event_bus.publish(Event(\n                event_type=\"dlq.manually_resolved\",\n                source_agent_id=self.event_bus.agent_id,\n                payload={\n                    \"event_id\": event_id,\n                    \"resolution\": resolution,\n                    \"resolved_at\": datetime.now(\n                        timezone.utc\n                    ).isoformat(),\n                },\n            ))\n```\n\n### Retry Policy Summary\n\n```\nRetry Policy: Exponential Backoff with Circuit Breaker\n=======================================================\n\nAttempt   Delay        Cumulative Wait\n────────────────────────────────────────\n1         5s           5s\n2         10s          15s\n3         20s          35s\n4         40s          75s (1m 15s)\n5         80s          155s (2m 35s)\n  ──── MAX RETRIES REACHED ────\n  Status: exhausted\n  Action: manual intervention required\n\nCircuit Breaker:\n  Threshold: 10 consecutive failures per handler\n  State: OPEN (all retries skipped)\n  Recovery: automatic on successful retry\n```\n\n### Alerting on Dead Letters\n\nThe `dlq.exhausted` event is the critical signal. Subscribe to it in your monitoring system and route it to an alerting channel -- PagerDuty, Slack, email, whatever your operations team monitors. An exhausted dead letter means automated recovery has failed and a human (or a supervisory agent) must intervene. The event payload contains everything needed to diagnose the problem: the original event, the handler that failed, the number of attempts, and the last error message.\n\n---\n\n## Chapter 6: Exactly-Once Processing\n\n### The Challenge\n\nDistributed systems offer three delivery guarantees: at-most-once (fire and forget), at-least-once (retry until acknowledged), and exactly-once (process each event exactly one time). At-most-once loses events. At-least-once duplicates events. Exactly-once is what you want -- and what everyone claims is impossible.\n\nThe practical answer is: exactly-once processing is achieved by combining at-least-once delivery with idempotent handlers. The event bus guarantees that every event is delivered at least once (it retries on failure). Your handlers guarantee that processing the same event twice produces the same result as processing it once (idempotency). Together, these two properties give you exactly-once semantics from the application's perspective, even though the underlying delivery mechanism may send duplicates.\n\n### Idempotency Key Patterns\n\nEvery GreenHelix API call that creates or modifies state should include an idempotency key. The key must be deterministic from the event that triggered the call. If the same event triggers the same handler twice, the same idempotency key is generated, and GreenHelix deduplicates the second call.\n\n```python\nclass IdempotencyKeyGenerator:\n    \"\"\"Generate deterministic idempotency keys from events.\"\"\"\n\n    @staticmethod\n    def for_event(event: Event, operation: str) -> str:\n        \"\"\"Generate an idempotency key for an operation\n        triggered by an event.\"\"\"\n        raw = (\n            f\"{event.event_id}:{operation}:\"\n            f\"{event.source_agent_id}\"\n        )\n        return hashlib.sha256(raw.encode()).hexdigest()[:32]\n\n    @staticmethod\n    def for_saga_step(saga_id: str, step_name: str,\n                      attempt: int = 0) -> str:\n        \"\"\"Generate an idempotency key for a saga step.\n\n        Note: attempt is NOT included by default. This ensures\n        retries of the same step produce the same key, which is\n        the correct behavior for idempotent operations.\n        \"\"\"\n        raw = f\"saga:{saga_id}:step:{step_name}\"\n        return hashlib.sha256(raw.encode()).hexdigest()[:32]\n\n    @staticmethod\n    def for_compensation(saga_id: str,\n                         step_name: str) -> str:\n        \"\"\"Generate an idempotency key for a compensating\n        transaction.\"\"\"\n        raw = f\"compensate:{saga_id}:{step_name}\"\n        return hashlib.sha256(raw.encode()).hexdigest()[:32]\n```\n\n### Deduplication Strategies\n\nClient-side deduplication provides an additional layer of protection. The `AsyncEventBus` already tracks processed event IDs in `_processed_ids`. For handlers that need stronger guarantees, a persistent deduplication store ensures that events are not reprocessed after a process restart.\n\n```python\nclass EventDeduplicator:\n    \"\"\"Client-side event deduplication with persistent storage.\n\n    Stores processed event IDs with timestamps. Supports\n    TTL-based expiry to prevent unbounded memory growth.\n    \"\"\"\n\n    def __init__(self, ttl_seconds: int = 86400):\n        self._processed: Dict[str, float] = {}\n        self.ttl_seconds = ttl_seconds\n\n    def is_duplicate(self, event_id: str) -> bool:\n        \"\"\"Check if an event has already been processed.\"\"\"\n        self._evict_expired()\n        return event_id in self._processed\n\n    def mark_processed(self, event_id: str) -> None:\n        \"\"\"Mark an event as processed.\"\"\"\n        self._processed[event_id] = time.time()\n\n    def _evict_expired(self) -> None:\n        \"\"\"Remove entries older than TTL.\"\"\"\n        cutoff = time.time() - self.ttl_seconds\n        expired = [\n            eid for eid, ts in self._processed.items()\n            if ts \u003C cutoff\n        ]\n        for eid in expired:\n            del self._processed[eid]\n\n    @property\n    def size(self) -> int:\n        return len(self._processed)\n\n\n# Usage in a handler:\ndedup = EventDeduplicator(ttl_seconds=86400)  # 24 hour window\n\n\nasync def handle_escrow_created(event: Event) -> None:\n    if dedup.is_duplicate(event.event_id):\n        logger.info(f\"Skipping duplicate: {event.event_id}\")\n        return\n\n    # Process the event...\n    escrow_id = event.payload.get(\"escrow_id\")\n    # ... do work ...\n\n    dedup.mark_processed(event.event_id)\n```\n\n### The Outbox Pattern\n\nThe outbox pattern solves a subtle but critical problem: how do you atomically update your local state AND publish an event? If you update your local state first and then publish the event, a crash between the two operations leaves you with updated state but no event (the outside world does not know). If you publish the event first and then update local state, a crash leaves you with an event published but no local state update (you will re-publish when you restart).\n\nThe outbox pattern writes the event to a local \"outbox\" table in the same database transaction as the state update. A separate process reads the outbox and publishes events to the event bus. If publishing succeeds, the outbox entry is marked as sent. If publishing fails, the entry remains and will be retried.\n\n```python\nclass OutboxPublisher:\n    \"\"\"Implements the outbox pattern for reliable event\n    publishing.\n\n    Events are written to a local outbox (in-memory for this\n    example; use a database in production). A background task\n    reads the outbox and publishes events to the event bus.\n    Sent events are marked and eventually cleaned up.\n    \"\"\"\n\n    def __init__(self, event_bus: AsyncEventBus,\n                 flush_interval: float = 0.5):\n        self.event_bus = event_bus\n        self.flush_interval = flush_interval\n        self._outbox: List[dict] = []\n        self._lock = asyncio.Lock()\n        self._running = False\n\n    async def write(self, event: Event) -> None:\n        \"\"\"Write an event to the outbox.\n\n        Call this inside the same 'transaction' as your\n        state update. In production, this would be an INSERT\n        into an outbox table within the same DB transaction.\n        \"\"\"\n        async with self._lock:\n            self._outbox.append({\n                \"event\": event,\n                \"status\": \"pending\",\n                \"created_at\": datetime.now(\n                    timezone.utc\n                ).isoformat(),\n                \"attempts\": 0,\n            })\n\n    async def start(self) -> None:\n        \"\"\"Start the background publisher.\"\"\"\n        self._running = True\n        asyncio.create_task(self._flush_loop())\n\n    async def stop(self) -> None:\n        \"\"\"Stop the background publisher.\"\"\"\n        self._running = False\n\n    async def _flush_loop(self) -> None:\n        \"\"\"Continuously publish pending outbox events.\"\"\"\n        while self._running:\n            async with self._lock:\n                pending = [\n                    entry for entry in self._outbox\n                    if entry[\"status\"] == \"pending\"\n                ]\n\n            for entry in pending:\n                try:\n                    await self.event_bus.publish(entry[\"event\"])\n                    entry[\"status\"] = \"sent\"\n                except Exception as e:\n                    entry[\"attempts\"] += 1\n                    logger.warning(\n                        f\"Outbox publish failed: {e} \"\n                        f\"(attempt {entry['attempts']})\"\n                    )\n                    if entry[\"attempts\"] >= 10:\n                        entry[\"status\"] = \"failed\"\n                        logger.error(\n                            f\"Outbox entry exhausted: \"\n                            f\"{entry['event'].event_id}\"\n                        )\n\n            # Clean up sent entries older than 1 hour\n            async with self._lock:\n                self._outbox = [\n                    e for e in self._outbox\n                    if e[\"status\"] != \"sent\"\n                ]\n\n            await asyncio.sleep(self.flush_interval)\n\n    @property\n    def pending_count(self) -> int:\n        return sum(\n            1 for e in self._outbox\n            if e[\"status\"] == \"pending\"\n        )\n```\n\nThe interaction between deduplication, idempotency keys, and the outbox pattern creates a three-layer defense against duplicate processing:\n\n```\nExactly-Once Processing: Three-Layer Defense\n=============================================\n\nLayer 1: OUTBOX PATTERN\n  State update + event write in same transaction\n  Guarantees: event is published if and only if\n              state was updated\n\nLayer 2: IDEMPOTENCY KEYS\n  Every API call includes a deterministic key\n  Guarantees: GreenHelix deduplicates repeated calls\n\nLayer 3: CLIENT-SIDE DEDUPLICATION\n  EventDeduplicator tracks processed event IDs\n  Guarantees: handler skips already-processed events\n\nTogether: exactly-once semantics from the\n          application's perspective\n```\n\n---\n\n## Chapter 7: Backpressure\n\n### What Happens When Events Arrive Faster Than Processing?\n\nBackpressure is what happens when a producer generates events faster than a consumer can process them. In agent commerce, this occurs during batch settlement (500 escrows releasing simultaneously), during market disruptions (every agent reacts to the same price signal at once), or during recovery from an outage (a backlog of unprocessed events floods the system when connectivity is restored).\n\nWithout backpressure management, the system fails in one of two ways. Either the event queue grows without bound until memory is exhausted, or the consumer falls so far behind that events become stale and the system processes outdated information. Both outcomes are catastrophic for financial operations where every event represents real money.\n\n### Rate Limiting Strategies\n\nThe `AsyncEventBus` already provides one form of backpressure through its `max_concurrent_handlers` semaphore. But that only controls concurrency within a single consumer. For fleet-wide backpressure, you need rate limiting at the API call level.\n\n```python\nclass RateLimiter:\n    \"\"\"Token bucket rate limiter for async operations.\n\n    Controls the rate of outbound API calls to stay within\n    GreenHelix tier limits and prevent overwhelming\n    downstream services.\n    \"\"\"\n\n    def __init__(self, rate: float, burst: int):\n        \"\"\"\n        Args:\n            rate: tokens per second (sustained rate)\n            burst: maximum tokens available (burst capacity)\n        \"\"\"\n        self.rate = rate\n        self.burst = burst\n        self._tokens = float(burst)\n        self._last_refill = time.monotonic()\n        self._lock = asyncio.Lock()\n\n    async def acquire(self, tokens: int = 1) -> float:\n        \"\"\"Acquire tokens, waiting if necessary.\n\n        Returns the time waited in seconds.\n        \"\"\"\n        waited = 0.0\n        async with self._lock:\n            self._refill()\n            while self._tokens \u003C tokens:\n                deficit = tokens - self._tokens\n                wait_time = deficit \u002F self.rate\n                await asyncio.sleep(wait_time)\n                waited += wait_time\n                self._refill()\n            self._tokens -= tokens\n        return waited\n\n    def _refill(self) -> None:\n        \"\"\"Refill tokens based on elapsed time.\"\"\"\n        now = time.monotonic()\n        elapsed = now - self._last_refill\n        self._tokens = min(\n            self.burst,\n            self._tokens + elapsed * self.rate,\n        )\n        self._last_refill = now\n\n    @property\n    def available_tokens(self) -> float:\n        self._refill()\n        return self._tokens\n\n\n# Usage: rate-limit GreenHelix API calls\n\n# Pro tier: 1000 calls\u002Fminute = ~16.7 calls\u002Fsecond\nlimiter = RateLimiter(rate=15.0, burst=50)\n\n\nasync def rate_limited_api_call(session, base_url,\n                                tool, input_data):\n    \"\"\"Make a GreenHelix API call with rate limiting.\"\"\"\n    wait = await limiter.acquire()\n    if wait > 0:\n        logger.debug(f\"Rate limited: waited {wait:.2f}s\")\n    return await make_api_call(session, base_url, tool,\n                               input_data)\n```\n\n### Queue Depth Monitoring\n\nMonitoring queue depth is essential for detecting backpressure before it becomes a problem. The metric to watch is the ratio of events arriving per second to events processed per second. When the ratio exceeds 1.0 for more than a few minutes, the queue is growing and backpressure management must engage.\n\n```python\nclass BackpressureMonitor:\n    \"\"\"Monitors event processing rate and queue depth.\n\n    Emits metrics and triggers load shedding when\n    the system is overwhelmed.\n    \"\"\"\n\n    def __init__(self, event_bus: AsyncEventBus,\n                 high_watermark: int = 1000,\n                 low_watermark: int = 100,\n                 check_interval: float = 5.0):\n        self.event_bus = event_bus\n        self.high_watermark = high_watermark\n        self.low_watermark = low_watermark\n        self.check_interval = check_interval\n\n        self._queue_depth = 0\n        self._events_received = 0\n        self._events_processed = 0\n        self._shedding = False\n        self._last_check = time.monotonic()\n        self._running = False\n\n    def record_received(self) -> None:\n        self._events_received += 1\n        self._queue_depth += 1\n\n    def record_processed(self) -> None:\n        self._events_processed += 1\n        self._queue_depth = max(0, self._queue_depth - 1)\n\n    @property\n    def is_shedding(self) -> bool:\n        return self._shedding\n\n    async def start(self) -> None:\n        self._running = True\n        asyncio.create_task(self._monitor_loop())\n\n    async def _monitor_loop(self) -> None:\n        while self._running:\n            now = time.monotonic()\n            elapsed = now - self._last_check\n\n            if elapsed > 0:\n                receive_rate = self._events_received \u002F elapsed\n                process_rate = self._events_processed \u002F elapsed\n            else:\n                receive_rate = 0\n                process_rate = 0\n\n            # Engage load shedding at high watermark\n            if (self._queue_depth >= self.high_watermark\n                    and not self._shedding):\n                self._shedding = True\n                logger.warning(\n                    f\"BACKPRESSURE: load shedding ENGAGED \"\n                    f\"(depth: {self._queue_depth})\"\n                )\n                await self.event_bus.publish(Event(\n                    event_type=\"system.backpressure_engaged\",\n                    source_agent_id=self.event_bus.agent_id,\n                    payload={\n                        \"queue_depth\": self._queue_depth,\n                        \"receive_rate\": round(receive_rate, 2),\n                        \"process_rate\": round(process_rate, 2),\n                    },\n                ))\n\n            # Disengage at low watermark\n            if (self._queue_depth \u003C= self.low_watermark\n                    and self._shedding):\n                self._shedding = False\n                logger.info(\n                    f\"BACKPRESSURE: load shedding DISENGAGED \"\n                    f\"(depth: {self._queue_depth})\"\n                )\n\n            # Reset counters\n            self._events_received = 0\n            self._events_processed = 0\n            self._last_check = now\n\n            await asyncio.sleep(self.check_interval)\n\n    def get_metrics(self) -> dict:\n        return {\n            \"queue_depth\": self._queue_depth,\n            \"shedding_active\": self._shedding,\n            \"high_watermark\": self.high_watermark,\n            \"low_watermark\": self.low_watermark,\n        }\n```\n\n### Load Shedding vs Buffering\n\nWhen backpressure engages, you have two choices: buffer events (accept them all and process them later) or shed load (reject or deprioritize low-priority events to protect high-priority processing).\n\nFor agent commerce, the answer is priority-based load shedding. Financial events (escrow releases, payments, dispute deadlines) must never be shed. Informational events (analytics updates, reputation refreshes, non-urgent notifications) can be deferred or dropped. The priority is encoded in the event type.\n\n```python\nclass PrioritizedEventProcessor:\n    \"\"\"Processes events with priority-based load shedding.\n\n    During backpressure, low-priority events are deferred\n    while high-priority events (financial operations) are\n    processed immediately.\n    \"\"\"\n\n    # Priority levels: lower number = higher priority\n    PRIORITY_MAP = {\n        \"escrow.*\": 1,\n        \"payment.*\": 1,\n        \"dispute.*\": 1,\n        \"saga.*\": 2,\n        \"sla.breached\": 2,\n        \"compensation.*\": 2,\n        \"sla.*\": 3,\n        \"message.*\": 3,\n        \"analytics.*\": 4,\n        \"reputation.*\": 4,\n        \"system.*\": 5,\n    }\n\n    def __init__(self, monitor: BackpressureMonitor,\n                 shed_threshold: int = 3):\n        \"\"\"\n        Args:\n            shed_threshold: events with priority >= this\n                            value are shed during backpressure.\n        \"\"\"\n        self.monitor = monitor\n        self.shed_threshold = shed_threshold\n        self._deferred: List[Event] = []\n\n    def should_process(self, event: Event) -> bool:\n        \"\"\"Determine if an event should be processed now.\"\"\"\n        if not self.monitor.is_shedding:\n            return True\n\n        priority = self._get_priority(event.event_type)\n        if priority \u003C self.shed_threshold:\n            return True  # High priority: always process\n\n        # Low priority during backpressure: defer\n        self._deferred.append(event)\n        logger.debug(\n            f\"Deferred event {event.event_type} \"\n            f\"(priority {priority}, depth \"\n            f\"{self.monitor.get_metrics()['queue_depth']})\"\n        )\n        return False\n\n    def _get_priority(self, event_type: str) -> int:\n        \"\"\"Get priority for an event type.\"\"\"\n        for pattern, priority in self.PRIORITY_MAP.items():\n            if pattern.endswith(\".*\"):\n                prefix = pattern[:-2]\n                if event_type.startswith(prefix + \".\"):\n                    return priority\n            elif pattern == event_type:\n                return priority\n        return 5  # Default: lowest priority\n\n    def get_deferred(self) -> List[Event]:\n        \"\"\"Return and clear deferred events for processing\n        when backpressure subsides.\"\"\"\n        events = self._deferred.copy()\n        self._deferred.clear()\n        return events\n```\n\n---\n\n## Chapter 8: Async Escrow Settlement\n\n### Event-Driven Escrow Lifecycle\n\nThe escrow is the financial backbone of agent commerce. Every escrow passes through a lifecycle: created, funded, conditions met (or breached), released (or disputed). In a synchronous model, the buyer polls `get_escrow_status` until the escrow transitions. In an event-driven model, the buyer subscribes to escrow lifecycle events and reacts to state changes as they occur.\n\n```\nEscrow Lifecycle Events\n========================\n\n  create_escrow\n       │\n       ▼\n  escrow.created ──────────────────────┐\n       │                                │\n       ▼                                │\n  escrow.funded                         │\n       │                                │\n  ┌────┴────┐                           │\n  │         │                           │\n  ▼         ▼                           ▼\nescrow.   escrow.                  escrow.expired\nconditions conditions              (timeout, no\n_met      _breached                 activity)\n  │         │\n  ▼         ▼\nescrow.   dispute.opened\nreleased       │\n               ▼\n          dispute.resolved\n               │\n          ┌────┴────┐\n          ▼         ▼\n     escrow.    escrow.\n     released   forfeited\n```\n\n### Webhook Handlers for Escrow State Changes\n\nFor the lowest latency notifications, register a webhook endpoint with GreenHelix. When an escrow state changes, GreenHelix sends an HTTP POST to your endpoint.\n\n```python\nfrom aiohttp import web\nimport hmac\n\n\nclass EscrowWebhookHandler:\n    \"\"\"HTTP server that receives GreenHelix webhook\n    notifications for escrow state changes.\n\n    Validates webhook signatures, deduplicates events,\n    and dispatches to registered handlers.\n    \"\"\"\n\n    def __init__(self, webhook_secret: str,\n                 event_bus: AsyncEventBus,\n                 deduplicator: EventDeduplicator):\n        self.webhook_secret = webhook_secret\n        self.event_bus = event_bus\n        self.dedup = deduplicator\n        self._handlers: Dict[str, EventHandler] = {}\n\n    def register_handler(self, escrow_state: str,\n                         handler: EventHandler) -> None:\n        \"\"\"Register a handler for an escrow state transition.\"\"\"\n        self._handlers[escrow_state] = handler\n\n    async def handle_webhook(self,\n                             request: web.Request) -> web.Response:\n        \"\"\"Process an incoming webhook from GreenHelix.\"\"\"\n        # Step 1: Verify signature\n        body = await request.read()\n        signature = request.headers.get(\n            \"X-GreenHelix-Signature\", \"\"\n        )\n        if not self._verify_signature(body, signature):\n            return web.Response(status=401, text=\"Invalid signature\")\n\n        # Step 2: Parse event\n        try:\n            data = json.loads(body)\n            event = Event.from_dict(data)\n        except (json.JSONDecodeError, KeyError) as e:\n            return web.Response(\n                status=400, text=f\"Invalid payload: {e}\"\n            )\n\n        # Step 3: Deduplicate\n        if self.dedup.is_duplicate(event.event_id):\n            # Return 200 to prevent GreenHelix from retrying\n            return web.Response(\n                status=200, text=\"Already processed\"\n            )\n\n        # Step 4: Dispatch to handler\n        escrow_state = event.payload.get(\"state\", \"\")\n        handler = self._handlers.get(escrow_state)\n\n        if handler:\n            try:\n                await handler(event)\n                self.dedup.mark_processed(event.event_id)\n                return web.Response(status=200, text=\"OK\")\n            except Exception as e:\n                logger.error(\n                    f\"Webhook handler failed: {e}\"\n                )\n                # Return 500 so GreenHelix retries\n                return web.Response(\n                    status=500,\n                    text=\"Processing failed\",\n                )\n        else:\n            # Unknown state -- accept but log\n            logger.warning(\n                f\"No handler for escrow state: {escrow_state}\"\n            )\n            self.dedup.mark_processed(event.event_id)\n            return web.Response(status=200, text=\"No handler\")\n\n    def _verify_signature(self, body: bytes,\n                          signature: str) -> bool:\n        \"\"\"Verify the webhook signature using HMAC-SHA256.\"\"\"\n        expected = hmac.new(\n            self.webhook_secret.encode(),\n            body,\n            hashlib.sha256,\n        ).hexdigest()\n        return hmac.compare_digest(expected, signature)\n\n    def create_app(self) -> web.Application:\n        \"\"\"Create an aiohttp web application for the webhook.\"\"\"\n        app = web.Application()\n        app.router.add_post(\n            \"\u002Fwebhooks\u002Fescrow\", self.handle_webhook\n        )\n        return app\n```\n\n### Automated Evaluation and Release\n\nThe most powerful application of async escrow settlement is automated evaluation. Instead of a buyer agent manually checking SLA status and deciding whether to release, an event handler monitors SLA events and releases escrow automatically when conditions are met.\n\n```python\nclass AsyncEscrowSettlement:\n    \"\"\"Automated escrow settlement driven by events.\n\n    Subscribes to SLA, delivery, and dispute events.\n    Automatically releases or disputes escrows based on\n    observed conditions.\n    \"\"\"\n\n    def __init__(self, session: aiohttp.ClientSession,\n                 base_url: str, agent_id: str,\n                 event_bus: AsyncEventBus):\n        self.session = session\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.event_bus = event_bus\n        self.keygen = IdempotencyKeyGenerator()\n\n        # Track active escrows and their conditions\n        self._escrows: Dict[str, dict] = {}\n\n        # Register event handlers\n        event_bus.subscribe(\n            \"escrow.created\", self._on_escrow_created\n        )\n        event_bus.subscribe(\n            \"sla.evaluation_complete\",\n            self._on_sla_evaluation_complete,\n        )\n        event_bus.subscribe(\n            \"delivery.confirmed\", self._on_delivery_confirmed\n        )\n        event_bus.subscribe(\n            \"escrow.expired\", self._on_escrow_expired\n        )\n\n    async def _on_escrow_created(self, event: Event) -> None:\n        \"\"\"Track a newly created escrow.\"\"\"\n        escrow_id = event.payload.get(\"escrow_id\")\n        self._escrows[escrow_id] = {\n            \"escrow_id\": escrow_id,\n            \"amount\": event.payload.get(\"amount\"),\n            \"counterparty_id\": event.payload.get(\n                \"counterparty_id\"\n            ),\n            \"conditions\": event.payload.get(\"conditions\", {}),\n            \"sla_met\": False,\n            \"delivery_confirmed\": False,\n            \"created_at\": event.timestamp,\n            \"correlation_id\": event.correlation_id,\n        }\n        logger.info(f\"Tracking escrow: {escrow_id}\")\n\n    async def _on_sla_evaluation_complete(\n        self, event: Event\n    ) -> None:\n        \"\"\"Handle SLA evaluation completion.\"\"\"\n        sla_id = event.payload.get(\"sla_id\")\n        escrow_id = event.payload.get(\"escrow_id\")\n        compliant = event.payload.get(\"compliant\", False)\n\n        if escrow_id not in self._escrows:\n            return\n\n        escrow = self._escrows[escrow_id]\n\n        if compliant:\n            escrow[\"sla_met\"] = True\n            logger.info(\n                f\"SLA met for escrow {escrow_id} \"\n                f\"(SLA: {sla_id})\"\n            )\n            await self._check_release_conditions(escrow_id)\n        else:\n            # SLA breached -- consider disputing\n            breach_data = event.payload.get(\"breach_data\", {})\n            await self._handle_sla_breach(\n                escrow_id, sla_id, breach_data\n            )\n\n    async def _on_delivery_confirmed(\n        self, event: Event\n    ) -> None:\n        \"\"\"Handle delivery confirmation.\"\"\"\n        escrow_id = event.payload.get(\"escrow_id\")\n        if escrow_id not in self._escrows:\n            return\n\n        self._escrows[escrow_id][\"delivery_confirmed\"] = True\n        logger.info(f\"Delivery confirmed for escrow {escrow_id}\")\n        await self._check_release_conditions(escrow_id)\n\n    async def _on_escrow_expired(self, event: Event) -> None:\n        \"\"\"Handle escrow expiration without settlement.\"\"\"\n        escrow_id = event.payload.get(\"escrow_id\")\n        if escrow_id in self._escrows:\n            logger.warning(f\"Escrow expired: {escrow_id}\")\n            del self._escrows[escrow_id]\n\n    async def _check_release_conditions(\n        self, escrow_id: str\n    ) -> None:\n        \"\"\"Check if all conditions are met to release\n        the escrow.\"\"\"\n        escrow = self._escrows.get(escrow_id)\n        if not escrow:\n            return\n\n        if escrow[\"sla_met\"] and escrow[\"delivery_confirmed\"]:\n            await self._release_escrow(escrow)\n\n    async def _release_escrow(self, escrow: dict) -> None:\n        \"\"\"Release escrow funds to the counterparty.\"\"\"\n        escrow_id = escrow[\"escrow_id\"]\n        counterparty_id = escrow[\"counterparty_id\"]\n\n        idempotency_key = self.keygen.for_event(\n            Event(\n                event_type=\"settlement\",\n                source_agent_id=self.agent_id,\n                event_id=f\"release-{escrow_id}\",\n                payload={},\n            ),\n            \"release_escrow\",\n        )\n\n        try:\n            result = await make_api_call(\n                self.session, self.base_url,\n                \"release_escrow\", {\n                    \"agent_id\": self.agent_id,\n                    \"escrow_id\": escrow_id,\n                    \"release_to\": counterparty_id,\n                    \"reason\": \"conditions_met\",\n                    \"idempotency_key\": idempotency_key,\n                },\n            )\n\n            await self.event_bus.publish(Event(\n                event_type=\"settlement.escrow_released\",\n                source_agent_id=self.agent_id,\n                correlation_id=escrow.get(\"correlation_id\", \"\"),\n                payload={\n                    \"escrow_id\": escrow_id,\n                    \"amount\": escrow[\"amount\"],\n                    \"released_to\": counterparty_id,\n                },\n            ))\n\n            # Record in ledger\n            await make_api_call(\n                self.session, self.base_url,\n                \"record_transaction\", {\n                    \"agent_id\": self.agent_id,\n                    \"transaction_type\": \"escrow_settlement\",\n                    \"amount\": str(escrow[\"amount\"]),\n                    \"currency\": \"USD\",\n                    \"counterparty_id\": counterparty_id,\n                    \"metadata\": json.dumps({\n                        \"escrow_id\": escrow_id,\n                        \"settlement_type\": \"automatic\",\n                        \"sla_compliant\": True,\n                        \"delivery_confirmed\": True,\n                    }),\n                },\n            )\n\n            logger.info(\n                f\"Escrow {escrow_id} released to \"\n                f\"{counterparty_id}: ${escrow['amount']}\"\n            )\n            del self._escrows[escrow_id]\n\n        except Exception as e:\n            logger.error(\n                f\"Failed to release escrow {escrow_id}: {e}\"\n            )\n            # The DLQ will handle retries\n\n    async def _handle_sla_breach(self, escrow_id: str,\n                                 sla_id: str,\n                                 breach_data: dict) -> None:\n        \"\"\"Handle an SLA breach by opening a dispute.\"\"\"\n        escrow = self._escrows.get(escrow_id)\n        if not escrow:\n            return\n\n        counterparty_id = escrow[\"counterparty_id\"]\n\n        result = await make_api_call(\n            self.session, self.base_url,\n            \"open_dispute\", {\n                \"agent_id\": self.agent_id,\n                \"counterparty_id\": counterparty_id,\n                \"dispute_type\": \"sla_breach\",\n                \"description\": json.dumps({\n                    \"escrow_id\": escrow_id,\n                    \"sla_id\": sla_id,\n                    \"breach_data\": breach_data,\n                }),\n            },\n        )\n\n        await self.event_bus.publish(Event(\n            event_type=\"settlement.dispute_opened\",\n            source_agent_id=self.agent_id,\n            correlation_id=escrow.get(\"correlation_id\", \"\"),\n            payload={\n                \"escrow_id\": escrow_id,\n                \"dispute_id\": result.get(\"dispute_id\"),\n                \"sla_id\": sla_id,\n            },\n        ))\n\n        logger.warning(\n            f\"Dispute opened for escrow {escrow_id}: \"\n            f\"{result.get('dispute_id')}\"\n        )\n\n    def get_active_escrows(self) -> dict:\n        \"\"\"Return summary of all active escrows being tracked.\"\"\"\n        return {\n            \"total\": len(self._escrows),\n            \"escrows\": [\n                {\n                    \"escrow_id\": e[\"escrow_id\"],\n                    \"amount\": e[\"amount\"],\n                    \"sla_met\": e[\"sla_met\"],\n                    \"delivery_confirmed\": e[\"delivery_confirmed\"],\n                    \"age_seconds\": (\n                        datetime.now(timezone.utc)\n                        - datetime.fromisoformat(\n                            e[\"created_at\"].replace(\n                                \"Z\", \"+00:00\"\n                            )\n                        )\n                    ).total_seconds(),\n                }\n                for e in self._escrows.values()\n            ],\n        }\n```\n\n---\n\n## Next Steps\n\nFor deployment patterns, monitoring, and production hardening, see the\n[Agent Production Hardening Guide](https:\u002F\u002Fclawhub.ai\u002Fskills\u002Fgreenhelix-agent-production-hardening).\n\n### Deployment Architecture\n\n```\nProduction Async Agent Commerce Architecture\n==============================================\n\nINBOUND                              OUTBOUND\n┌─────────────────────┐             ┌─────────────────────┐\n│  GreenHelix Webhooks │             │  GreenHelix API      │\n│  POST \u002Fwebhooks\u002F     │             │  the GreenHelix REST API    │\n│  escrow              │             │                      │\n└─────────┬───────────┘             └──────────┬──────────┘\n          │                                     ▲\n          ▼                                     │\n┌─────────────────────┐             ┌──────────┴──────────┐\n│  Webhook Handler     │             │  Rate Limiter        │\n│  ├─ Verify signature │             │  (token bucket)      │\n│  ├─ Deduplicate      │             └──────────┬──────────┘\n│  └─ Dispatch         │                        ▲\n└─────────┬───────────┘                        │\n          │                          ┌──────────┴──────────┐\n          ▼                          │  Outbox Publisher     │\n┌──────────────────────────────┐    │  (reliable delivery)  │\n│         AsyncEventBus         │    └──────────┬──────────┘\n│  ┌────────────────────────┐  │               ▲\n│  │  Subscription Manager   │  │               │\n│  │  Event Dispatcher       │  │    ┌──────────┴──────────┐\n│  │  Acknowledgment Tracker │  │    │  Saga Orchestrator    │\n│  └────────────────────────┘  │    │  ├─ Step execution     │\n│                               │    │  ├─ Compensation       │\n│  ┌────────────────────────┐  │    │  └─ State machine      │\n│  │  Backpressure Monitor   │  │    └──────────┬──────────┘\n│  │  ├─ Queue depth         │  │               ▲\n│  │  ├─ Load shedding       │  │               │\n│  │  └─ Priority routing    │  │    ┌──────────┴──────────┐\n│  └────────────────────────┘  │    │  Async Escrow         │\n│                               │    │  Settlement           │\n│  ┌────────────────────────┐  │    │  ├─ Condition tracker  │\n│  │  Dead Letter Queue      │  │    │  ├─ Auto-release      │\n│  │  ├─ Retry policies      │  │    │  └─ Dispute trigger   │\n│  │  ├─ Circuit breaker     │  │    └─────────────────────┘\n│  │  └─ Escalation          │  │\n│  └────────────────────────┘  │\n└──────────────────────────────┘\n```\n\n### Key Metrics for Production\n\n```\nAsync Commerce Agent Metrics\n==============================\n\nEVENT BUS\n──────────────────────────────────────────────────\nEvents received\u002Fsec          target \u003C 50\nEvents processed\u002Fsec         target >= receive rate\nQueue depth                  target \u003C 100\nAcknowledgment latency       target \u003C 500ms\n\nSAGAS\n──────────────────────────────────────────────────\nActive sagas                 monitor for growth\nSaga completion rate         target > 99%\nCompensation trigger rate    target \u003C 1%\nCompensation success rate    target > 99.9%\n\nDEAD LETTER QUEUE\n──────────────────────────────────────────────────\nDLQ depth                    target = 0\nEvents exhausted\u002Fday         target = 0\nCircuit breakers open        target = 0\n\nBACKPRESSURE\n──────────────────────────────────────────────────\nLoad shedding active         target: rarely\nEvents deferred\u002Fmin          monitor trend\nDeferred event age           target \u003C 60s\n\nESCROW SETTLEMENT\n──────────────────────────────────────────────────\nActive escrows tracked       monitor for leaks\nAuto-release success rate    target > 99%\nTime to settlement           monitor p95\nDisputes opened\u002Fday          monitor trend\n```\n\n---\n\n## What's Next\n\nThis guide covered the event-driven foundations: the bus, the patterns, the failure modes. From here, the natural extensions are:\n\n**Multi-agent choreography.** This guide focused on orchestration (a central coordinator drives the saga). Choreography is the alternative: each agent reacts to events independently, with no central coordinator. Choreography scales better but is harder to debug. Combine the `AsyncEventBus` with per-agent state machines for a choreographed approach.\n\n**Event sourcing.** Instead of storing the current state of an escrow or saga, store the complete sequence of events that produced that state. Replay the events to reconstruct state at any point in time. The `OutboxPublisher` is already halfway there -- extend it with a persistent event store and projection functions.\n\n**Cross-gateway federation.** When agents operate across multiple commerce gateways (not just GreenHelix), the event bus needs to bridge events between platforms. The `AsyncEventBus` can be extended with adapter plugins for different gateway APIs.\n\n**Observability.** Distributed tracing through correlation IDs (already present in the `Event` dataclass) gives you end-to-end visibility into saga execution across agents. Wire the correlation IDs into OpenTelemetry spans for production observability.\n\nThe synchronous request-response model is the training wheels of agent commerce. It works for simple cases. But the moment your agents start managing long-lived transactions, coordinating with multiple counterparties, or operating at scale, you need the patterns in this guide. The event bus is your nervous system. Sagas are your transaction coordinator. Dead letters are your safety net. Backpressure is your circuit breaker. And async escrow settlement is how you stop burning 518,400 API calls to learn about a single state change.\n\n","# Async Agent Commerce: Event-Driven Patterns for Autonomous Transactions\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code, require credentials, or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n\n\nThe entire GreenHelix companion library is synchronous -- request, wait, response. You call `create_escrow`, the HTTP connection blocks for 200 milliseconds, and you get back an escrow ID. You call `release_escrow`, the connection blocks again, and the funds move. This works perfectly for simple two-party transactions that settle in seconds. But real-world agent commerce is inherently asynchronous. An escrow evaluation takes 30 days. A dispute resolution takes hours. A multi-agent negotiation involves back-and-forth over minutes. A compliance check depends on a third-party regulatory API that responds in 8 seconds on a good day and 90 seconds on a bad one. Synchronous polling wastes resources and misses events. A buyer agent that polls `get_escrow_status` every 5 seconds for 30 days makes 518,400 API calls to learn about a single state change. Multiply that by a fleet of 500 agents, each managing 20 active escrows, and you are burning 5.18 billion API calls per month on polling alone -- most returning \"no change.\" This guide rebuilds agent commerce on event-driven foundations using GreenHelix's event bus, webhooks, and messaging tools. It covers the patterns that production distributed systems have relied on for decades -- saga orchestration, compensating transactions, dead letter handling, exactly-once processing, and backpressure -- adapted specifically for autonomous agent transactions. Every pattern is implemented in Python using asyncio, every example uses the GreenHelix API, and every class is designed to run in production without human intervention.\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## What You'll Learn\n- Chapter 1: Why Async Matters for Agent Commerce\n- Chapter 2: AsyncEventBus Class\n- Chapter 3: Saga Orchestrator Pattern\n- Chapter 4: Compensating Transactions\n- Chapter 5: Dead Letter Handling\n- Chapter 6: Exactly-Once Processing\n- Chapter 7: Backpressure\n- Chapter 8: Async Escrow Settlement\n- Next Steps\n- What's Next\n\n## Full Guide\n\n# Async Agent Commerce: Event-Driven Patterns for Autonomous Transactions\n\nThe entire GreenHelix companion library is synchronous -- request, wait, response. You call `create_escrow`, the HTTP connection blocks for 200 milliseconds, and you get back an escrow ID. You call `release_escrow`, the connection blocks again, and the funds move. This works perfectly for simple two-party transactions that settle in seconds. But real-world agent commerce is inherently asynchronous. An escrow evaluation takes 30 days. A dispute resolution takes hours. A multi-agent negotiation involves back-and-forth over minutes. A compliance check depends on a third-party regulatory API that responds in 8 seconds on a good day and 90 seconds on a bad one. Synchronous polling wastes resources and misses events. A buyer agent that polls `get_escrow_status` every 5 seconds for 30 days makes 518,400 API calls to learn about a single state change. Multiply that by a fleet of 500 agents, each managing 20 active escrows, and you are burning 5.18 billion API calls per month on polling alone -- most returning \"no change.\" This guide rebuilds agent commerce on event-driven foundations using GreenHelix's event bus, webhooks, and messaging tools. It covers the patterns that production distributed systems have relied on for decades -- saga orchestration, compensating transactions, dead letter handling, exactly-once processing, and backpressure -- adapted specifically for autonomous agent transactions. Every pattern is implemented in Python using asyncio, every example uses the GreenHelix API, and every class is designed to run in production without human intervention.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [Why Async Matters for Agent Commerce](#chapter-1-why-async-matters-for-agent-commerce)\n2. [AsyncEventBus Class](#chapter-2-asynceventbus-class)\n3. [Saga Orchestrator Pattern](#chapter-3-saga-orchestrator-pattern)\n4. [Compensating Transactions](#chapter-4-compensating-transactions)\n5. [Dead Letter Handling](#chapter-5-dead-letter-handling)\n6. [Exactly-Once Processing](#chapter-6-exactly-once-processing)\n7. [Backpressure](#chapter-7-backpressure)\n8. [Async Escrow Settlement](#chapter-8-async-escrow-settlement)\n\n---\n\n## Chapter 1: Why Async Matters for Agent Commerce\n\n### The Polling Tax\n\nEvery synchronous agent commerce system pays a hidden tax: the cost of asking \"has anything changed?\" repeatedly until the answer is yes. Consider the lifecycle of a single escrow-protected service transaction. The buyer creates an escrow via `create_escrow`. The seller delivers the service. The buyer evaluates delivery quality. The buyer releases the escrow via `release_escrow`. In a synchronous model, the buyer must poll for two state transitions: \"has the seller acknowledged the escrow?\" and \"has delivery been confirmed by the SLA monitor?\" Each poll is an HTTP request. Each request consumes compute on the buyer's side, network bandwidth in transit, and compute on the GreenHelix gateway.\n\nThe numbers scale badly. A single agent managing 50 active transactions, polling each at 10-second intervals, generates 432,000 API calls per day. A fleet of 200 agents generates 86.4 million. At GreenHelix's free tier rate limit of 100 calls per minute, a single agent would exhaust its entire rate budget on polling alone, leaving zero capacity for actual commerce operations. Even at the pro tier (1,000 calls per minute), polling 50 transactions at 10-second intervals consumes 300 calls per minute -- 30% of the agent's total capacity wasted on \"has anything changed? no.\"\n\n```\nSynchronous Polling Cost Model\n====================================\n\n                          FREE TIER    PRO TIER     ENTERPRISE\nRate limit (calls\u002Fmin)    100          1,000        10,000\nActive transactions        50           50           50\nPoll interval (seconds)    10           10           10\nPolls per minute           300          300          300\nBudget consumed            300%         30%          3%\nRemaining for commerce     0%           70%          97%\n\nWith 200 agents:\nTotal polls\u002Fday            86.4M        86.4M        86.4M\nAPI cost at $0.001\u002Fcall    $86,400      $86,400      $86,400\nUseful information gained  ~200         ~200         ~200\nCost per useful event      $432         $432         $432\n```\n\nThe last row is the damning one. Of 86.4 million polls per day, approximately 200 return an actual state change. The cost per useful event is $432. Event-driven architecture inverts this: instead of asking 432,000 times and getting one answer, the system notifies you once when the answer changes. The cost per useful event drops to the cost of processing one webhook callback -- effectively zero.\n\n### Real-World Async Scenarios in Agent Commerce\n\nNot every agent transaction is a simple request-response. These are the scenarios where async patterns become essential:\n\n**Multi-day escrow evaluation.** A buyer agent creates an escrow for a data pipeline service with a 30-day evaluation period. The SLA requires 99.95% uptime measured over the full 30 days. The escrow cannot be released or disputed until the evaluation window closes. Synchronous polling for 30 days is absurd. An event-driven system subscribes to `escrow.evaluation_complete` and processes the release when the event fires.\n\n**Multi-party negotiation.** Three agents negotiate a supply chain arrangement. Agent A offers raw data. Agent B offers transformation services. Agent C wants transformed data. The negotiation involves six message exchanges over 12 minutes. In a synchronous model, each agent blocks a thread waiting for the next message. In an async model, each agent subscribes to `message.received` events and processes them as they arrive, freeing resources between exchanges.\n\n**Cascading service provisioning.** Agent A buys a service from Agent B, which in turn provisions a dependency from Agent C. Agent B cannot confirm delivery to Agent A until Agent C confirms delivery to Agent B. This is a distributed transaction that spans three agents and two escrows. Synchronous orchestration requires nested blocking calls. Async orchestration uses a saga pattern that coordinates the steps through events.\n\n**Dispute resolution.** Agent A opens a dispute against Agent B via `open_dispute`. Resolution may take hours -- it could involve automated evidence evaluation, third-party arbitration, or manual review. The disputing agent should not block a thread for hours waiting for `get_dispute` to return a resolved status. An event-driven system subscribes to `dispute.resolved` and handles the outcome when it arrives.\n\n**Batch settlement.** At the end of a billing cycle, an agent needs to settle 500 transactions simultaneously. Synchronous sequential processing takes 500 x 200ms = 100 seconds. Async concurrent processing with backpressure-controlled parallelism takes 10 seconds at 50 concurrent requests.\n\n### GreenHelix Async Primitives\n\nGreenHelix provides four primitives that enable event-driven architectures:\n\n**`publish_event`** -- Publishes a structured event to the GreenHelix event bus. Events are typed, timestamped, and associated with an agent ID. Other agents can subscribe to event streams filtered by type, agent, or custom attributes.\n\n**`subscribe_events`** -- Registers a subscription to an event stream. Returns events matching the subscription criteria. Supports long-polling (block until an event arrives or timeout) and cursor-based pagination for catching up on missed events.\n\n**Webhooks** -- GreenHelix can deliver events to an HTTPS endpoint you control. When an event matching your subscription fires, GreenHelix sends an HTTP POST to your webhook URL with the event payload. This is the lowest-latency notification mechanism -- you learn about state changes in milliseconds rather than polling intervals.\n\n**`send_message` \u002F `get_messages`** -- The messaging system provides point-to-point async communication between agents. Messages are stored until retrieved, providing natural buffering for agents that process messages at different rates.\n\n```\nEvent-Driven Architecture vs Synchronous Polling\n==================================================\n\nSYNCHRONOUS                          EVENT-DRIVEN\n┌──────────┐                        ┌──────────┐\n│  Agent A  │                        │  Agent A  │\n│           │  poll poll poll poll   │           │  subscribe once\n│  while:   │──────────────────────► │  await:   │──────────┐\n│    poll() │  \"changed?\" \"no\"      │    event  │          │\n│    sleep  │  \"changed?\" \"no\"      │           │          │\n│    poll() │  \"changed?\" \"yes!\"    │  (idle)   │          │\n│    sleep  │                        │           │          │\n│    poll() │                        │  handle() │◄─────────┘\n│    ...    │                        │           │  event fires\n└──────────┘                        └──────────┘\n\nAPI calls: 432,000\u002Fday              API calls: ~200\u002Fday\nLatency: up to poll interval        Latency: milliseconds\nCPU: constant                        CPU: on-demand\n```\n\nThese four primitives are the building blocks. The rest of this guide shows how to compose them into production-grade patterns for saga orchestration, compensating transactions, dead letter handling, exactly-once processing, backpressure management, and async escrow settlement.\n\n---\n\n## Chapter 2: AsyncEventBus Class\n\n### Event Publishing and Subscription\n\nThe `AsyncEventBus` class wraps the GreenHelix event primitives in an asyncio-native interface. It manages subscriptions, delivers events to registered handlers, acknowledges processed events, and handles connection failures gracefully.\n\nThe design follows the observer pattern: handlers register interest in specific event types, and the bus dispatches matching events to the appropriate handlers. Events are typed using a dot-notation hierarchy (`escrow.created`, `escrow.released`, `dispute.opened`, `sla.breached`) that supports both exact matching and prefix matching (subscribe to `escrow.*` to receive all escrow-related events).\n\n### Event Schemas and Typing\n\nEvery event on the bus conforms to a standard envelope schema:\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Any, Optional\nfrom datetime import datetime, timezone\nimport hashlib\nimport json\n\n\n@dataclass\nclass Event:\n    \"\"\"Standard event envelope for the GreenHelix event bus.\"\"\"\n    event_type: str                   # e.g. \"escrow.created\"\n    source_agent_id: str              # Agent that produced the event\n    payload: dict                      # Event-specific data\n    event_id: str = \"\"                 # Unique event identifier\n    timestamp: str = \"\"                # ISO 8601 timestamp\n    correlation_id: str = \"\"           # Links related events across a saga\n    sequence_number: int = 0           # Ordering within a partition\n\n    def __post_init__(self):\n        if not self.timestamp:\n            self.timestamp = datetime.now(timezone.utc).isoformat()\n        if not self.event_id:\n            raw = f\"{self.event_type}:{self.source_agent_id}:{self.timestamp}\"\n            self.event_id = hashlib.sha256(raw.encode()).hexdigest()[:24]\n\n    def to_dict(self) -> dict:\n        return {\n            \"event_id\": self.event_id,\n            \"event_type\": self.event_type,\n            \"source_agent_id\": self.source_agent_id,\n            \"timestamp\": self.timestamp,\n            \"correlation_id\": self.correlation_id,\n            \"sequence_number\": self.sequence_number,\n            \"payload\": self.payload,\n        }\n\n    @classmethod\n    def from_dict(cls, data: dict) -> \"Event\":\n        return cls(\n            event_id=data.get(\"event_id\", \"\"),\n            event_type=data[\"event_type\"],\n            source_agent_id=data[\"source_agent_id\"],\n            timestamp=data.get(\"timestamp\", \"\"),\n            correlation_id=data.get(\"correlation_id\", \"\"),\n            sequence_number=data.get(\"sequence_number\", 0),\n            payload=data.get(\"payload\", {}),\n        )\n```\n\n### The Complete AsyncEventBus\n\nThe bus maintains a registry of handlers keyed by event type pattern. When an event arrives, the bus matches it against all registered patterns and dispatches to matching handlers concurrently. Acknowledgments are sent after successful processing. Failed events are routed to a dead letter handler if one is registered.\n\n```python\nimport asyncio\nimport aiohttp\nimport logging\nfrom typing import Callable, Awaitable, Dict, List, Set\nfrom collections import defaultdict\n\nlogger = logging.getLogger(__name__)\n\nEventHandler = Callable[[Event], Awaitable[None]]\n\n\nclass AsyncEventBus:\n    \"\"\"Event bus client for GreenHelix with guaranteed delivery\n    and ordered processing.\n\n    Usage:\n        bus = AsyncEventBus(api_key=\"...\", agent_id=\"...\",)\n        bus.subscribe(\"escrow.created\", handle_escrow_created)\n        bus.subscribe(\"escrow.*\", handle_any_escrow_event)\n        await bus.start()\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n                 poll_interval: float = 1.0,\n                 max_concurrent_handlers: int = 10):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.poll_interval = poll_interval\n\n        # Handler registry: pattern -> list of handlers\n        self._handlers: Dict[str, List[EventHandler]] = defaultdict(list)\n        self._dead_letter_handler: Optional[EventHandler] = None\n\n        # Processing state\n        self._cursors: Dict[str, str] = {}   # subscription -> cursor\n        self._processed_ids: Set[str] = set()\n        self._semaphore = asyncio.Semaphore(max_concurrent_handlers)\n        self._running = False\n        self._session: Optional[aiohttp.ClientSession] = None\n        self._tasks: List[asyncio.Task] = []\n\n    def subscribe(self, event_pattern: str,\n                  handler: EventHandler) -> None:\n        \"\"\"Register a handler for an event pattern.\n\n        Patterns support trailing wildcards:\n          \"escrow.created\"  -- exact match\n          \"escrow.*\"        -- matches escrow.created, escrow.released, etc.\n          \"*\"               -- matches everything\n        \"\"\"\n        self._handlers[event_pattern].append(handler)\n        logger.info(f\"Subscribed handler to '{event_pattern}'\")\n\n    def set_dead_letter_handler(self,\n                                handler: EventHandler) -> None:\n        \"\"\"Register a handler for events that fail processing.\"\"\"\n        self._dead_letter_handler = handler\n\n    async def start(self) -> None:\n        \"\"\"Start the event bus. Polls for events and dispatches\n        to handlers.\"\"\"\n        self._running = True\n        self._session = aiohttp.ClientSession(\n            headers={\n                \"Content-Type\": \"application\u002Fjson\",\n                \"Authorization\": f\"Bearer {self.api_key}\",\n            }\n        )\n\n        # Register subscriptions with GreenHelix\n        for pattern in self._handlers:\n            await self._register_subscription(pattern)\n\n        # Start the polling loop\n        self._tasks.append(\n            asyncio.create_task(self._poll_loop())\n        )\n        logger.info(\"AsyncEventBus started\")\n\n    async def stop(self) -> None:\n        \"\"\"Gracefully stop the event bus.\"\"\"\n        self._running = False\n        for task in self._tasks:\n            task.cancel()\n        if self._session:\n            await self._session.close()\n        logger.info(\"AsyncEventBus stopped\")\n\n    async def publish(self, event: Event) -> dict:\n        \"\"\"Publish an event to the GreenHelix event bus.\"\"\"\n        async with self._session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\n                \"tool\": \"publish_event\",\n                \"input\": {\n                    \"agent_id\": self.agent_id,\n                    \"event_type\": event.event_type,\n                    \"payload\": json.dumps(event.to_dict()),\n                },\n            },\n        ) as resp:\n            resp.raise_for_status()\n            result = await resp.json()\n            logger.debug(f\"Published event: {event.event_type} \"\n                         f\"[{event.event_id}]\")\n            return result\n\n    async def _register_subscription(self, pattern: str) -> None:\n        \"\"\"Register an event subscription with GreenHelix.\"\"\"\n        async with self._session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\n                \"tool\": \"subscribe_events\",\n                \"input\": {\n                    \"agent_id\": self.agent_id,\n                    \"event_type\": pattern,\n                },\n            },\n        ) as resp:\n            resp.raise_for_status()\n            result = await resp.json()\n            cursor = result.get(\"cursor\", \"\")\n            self._cursors[pattern] = cursor\n            logger.info(f\"Registered subscription: {pattern} \"\n                        f\"(cursor: {cursor})\")\n\n    async def _poll_loop(self) -> None:\n        \"\"\"Continuously poll for new events.\"\"\"\n        while self._running:\n            try:\n                for pattern, cursor in list(self._cursors.items()):\n                    events = await self._fetch_events(pattern, cursor)\n                    for event_data in events:\n                        event = Event.from_dict(event_data)\n                        if event.event_id in self._processed_ids:\n                            continue\n                        await self._dispatch(event)\n            except asyncio.CancelledError:\n                break\n            except Exception as e:\n                logger.error(f\"Poll loop error: {e}\")\n            await asyncio.sleep(self.poll_interval)\n\n    async def _fetch_events(self, pattern: str,\n                            cursor: str) -> List[dict]:\n        \"\"\"Fetch new events from the subscription.\"\"\"\n        try:\n            async with self._session.post(\n                f\"{self.base_url}\u002Fv1\",\n                json={\n                    \"tool\": \"subscribe_events\",\n                    \"input\": {\n                        \"agent_id\": self.agent_id,\n                        \"event_type\": pattern,\n                        \"cursor\": cursor,\n                    },\n                },\n                timeout=aiohttp.ClientTimeout(total=30),\n            ) as resp:\n                resp.raise_for_status()\n                result = await resp.json()\n                # Update cursor for next poll\n                if result.get(\"cursor\"):\n                    self._cursors[pattern] = result[\"cursor\"]\n                return result.get(\"events\", [])\n        except asyncio.TimeoutError:\n            logger.debug(f\"Long-poll timeout for {pattern} (normal)\")\n            return []\n        except aiohttp.ClientError as e:\n            logger.warning(f\"Fetch error for {pattern}: {e}\")\n            return []\n\n    async def _dispatch(self, event: Event) -> None:\n        \"\"\"Dispatch an event to all matching handlers.\"\"\"\n        handlers = self._find_handlers(event.event_type)\n        if not handlers:\n            logger.warning(f\"No handlers for event type: \"\n                           f\"{event.event_type}\")\n            return\n\n        for handler in handlers:\n            async with self._semaphore:\n                try:\n                    await handler(event)\n                    self._processed_ids.add(event.event_id)\n                    await self._acknowledge(event)\n                except Exception as e:\n                    logger.error(\n                        f\"Handler failed for {event.event_id}: {e}\"\n                    )\n                    if self._dead_letter_handler:\n                        try:\n                            await self._dead_letter_handler(event)\n                        except Exception as dle:\n                            logger.error(\n                                f\"Dead letter handler failed: {dle}\"\n                            )\n\n    def _find_handlers(self, event_type: str) -> List[EventHandler]:\n        \"\"\"Find all handlers that match an event type.\"\"\"\n        matched = []\n        for pattern, handlers in self._handlers.items():\n            if self._pattern_matches(pattern, event_type):\n                matched.extend(handlers)\n        return matched\n\n    @staticmethod\n    def _pattern_matches(pattern: str, event_type: str) -> bool:\n        \"\"\"Check if an event type matches a subscription pattern.\"\"\"\n        if pattern == \"*\":\n            return True\n        if pattern.endswith(\".*\"):\n            prefix = pattern[:-2]\n            return event_type.startswith(prefix + \".\")\n        return pattern == event_type\n\n    async def _acknowledge(self, event: Event) -> None:\n        \"\"\"Acknowledge successful processing of an event.\"\"\"\n        try:\n            async with self._session.post(\n                f\"{self.base_url}\u002Fv1\",\n                json={\n                    \"tool\": \"publish_event\",\n                    \"input\": {\n                        \"agent_id\": self.agent_id,\n                        \"event_type\": \"system.event_ack\",\n                        \"payload\": json.dumps({\n                            \"acknowledged_event_id\": event.event_id,\n                            \"acknowledged_at\": datetime.now(\n                                timezone.utc\n                            ).isoformat(),\n                        }),\n                    },\n                },\n            ) as resp:\n                resp.raise_for_status()\n        except Exception as e:\n            logger.warning(f\"Ack failed for {event.event_id}: {e}\")\n```\n\n### Event Ordering and Partitioning\n\nEvents within a single agent's stream are ordered by sequence number. The bus processes them in order within a partition (defined by the source agent ID). Events from different agents can be processed concurrently because they belong to different partitions and have no ordering guarantees relative to each other.\n\nThe `max_concurrent_handlers` parameter controls how many events can be processed simultaneously across all partitions. Setting this to 1 gives you strict serial processing. Setting it to 50 gives you high throughput but requires your handlers to be safe for concurrent execution. The default of 10 is a reasonable starting point for most agent workloads.\n\n```python\n# Usage: start the event bus and register handlers\n\nasync def handle_escrow_created(event: Event) -> None:\n    \"\"\"React to a new escrow being created.\"\"\"\n    escrow_id = event.payload.get(\"escrow_id\")\n    amount = event.payload.get(\"amount\")\n    logger.info(f\"Escrow created: {escrow_id} for ${amount}\")\n    # Begin monitoring the escrow lifecycle...\n\n\nasync def handle_escrow_released(event: Event) -> None:\n    \"\"\"React to escrow funds being released.\"\"\"\n    escrow_id = event.payload.get(\"escrow_id\")\n    logger.info(f\"Escrow released: {escrow_id}\")\n    # Record the settlement in the ledger...\n\n\nasync def handle_sla_breached(event: Event) -> None:\n    \"\"\"React to an SLA breach detection.\"\"\"\n    sla_id = event.payload.get(\"sla_id\")\n    metric = event.payload.get(\"metric\")\n    actual = event.payload.get(\"actual_value\")\n    threshold = event.payload.get(\"threshold\")\n    logger.warning(f\"SLA breach: {sla_id} -- {metric} \"\n                   f\"is {actual}, threshold {threshold}\")\n    # Trigger compensating transaction...\n\n\nasync def main():\n    bus = AsyncEventBus(\n        api_key=\"your-api-key\",\n        agent_id=\"agent-buyer-042\",\n        poll_interval=2.0,\n        max_concurrent_handlers=10,\n    )\n\n    bus.subscribe(\"escrow.created\", handle_escrow_created)\n    bus.subscribe(\"escrow.released\", handle_escrow_released)\n    bus.subscribe(\"sla.breached\", handle_sla_breached)\n\n    await bus.start()\n\n    # Publish an event\n    await bus.publish(Event(\n        event_type=\"order.placed\",\n        source_agent_id=\"agent-buyer-042\",\n        correlation_id=\"saga-purchase-001\",\n        payload={\n            \"seller_id\": \"agent-seller-099\",\n            \"service\": \"data-pipeline-etl\",\n            \"amount\": \"500.00\",\n        },\n    ))\n\n    # Keep running until interrupted\n    try:\n        await asyncio.Event().wait()\n    finally:\n        await bus.stop()\n\n\n# asyncio.run(main())\n```\n\n---\n\n## Chapter 3: Saga Orchestrator Pattern\n\n### What Is a Saga?\n\nA saga is a distributed transaction decomposed into a sequence of local transactions, where each step has a corresponding compensating transaction that undoes its effect if a later step fails. The term comes from Hector Garcia-Molina's 1987 paper, but the pattern has become the standard approach for managing multi-step operations in microservice architectures -- and it maps perfectly onto multi-agent commerce.\n\nConsider a purchase transaction that involves five steps: (1) verify the buyer has sufficient balance, (2) create an escrow to hold funds, (3) register the service delivery SLA, (4) notify the seller to begin delivery, (5) record the transaction in the ledger. If step 4 fails -- the seller's agent is unreachable -- you cannot simply \"rollback\" the way a database transaction does. The escrow has already been created on the GreenHelix platform. The SLA has been registered. You need to explicitly undo each completed step in reverse order: cancel the SLA, release the escrow back to the buyer, and credit the balance reservation.\n\n```\nSaga: Purchase-Verify-Escrow-Deliver-Release\n==============================================\n\nFORWARD PATH (happy path):\n  Step 1: verify_balance ──► Step 2: create_escrow ──►\n  Step 3: create_sla ──► Step 4: notify_seller ──►\n  Step 5: record_transaction\n\nCOMPENSATING PATH (step 4 fails):\n  Step 4 fails ──►\n  Compensate 3: cancel_sla ──►\n  Compensate 2: release_escrow (refund) ──►\n  Compensate 1: unreserve_balance ──►\n  Saga FAILED (all effects reversed)\n```\n\n### The SagaOrchestrator Class\n\nThe orchestrator manages the state machine for a saga. Each saga instance tracks its current step, completed steps, and the compensation stack. The orchestrator advances through steps sequentially, pushing each completed step onto the compensation stack. If any step fails, it pops the stack and executes compensations in reverse order.\n\n```python\nimport asyncio\nimport json\nimport logging\nimport time\nfrom dataclasses import dataclass, field\nfrom datetime import datetime, timezone\nfrom enum import Enum\nfrom typing import (\n    Any, Awaitable, Callable, Dict, List, Optional, Tuple,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass SagaState(Enum):\n    PENDING = \"pending\"\n    RUNNING = \"running\"\n    COMPLETED = \"completed\"\n    COMPENSATING = \"compensating\"\n    FAILED = \"failed\"\n    COMPENSATION_FAILED = \"compensation_failed\"\n\n\n@dataclass\nclass SagaStep:\n    \"\"\"A single step in a saga with its compensating action.\"\"\"\n    name: str\n    execute: Callable[[dict], Awaitable[dict]]\n    compensate: Callable[[dict], Awaitable[None]]\n    timeout_seconds: float = 30.0\n    max_retries: int = 3\n    retry_delay_seconds: float = 1.0\n\n\n@dataclass\nclass SagaInstance:\n    \"\"\"Runtime state of a saga execution.\"\"\"\n    saga_id: str\n    correlation_id: str\n    state: SagaState = SagaState.PENDING\n    current_step: int = 0\n    context: dict = field(default_factory=dict)\n    completed_steps: List[str] = field(default_factory=list)\n    compensation_stack: List[Tuple[str, dict]] = field(\n        default_factory=list\n    )\n    error: Optional[str] = None\n    started_at: Optional[str] = None\n    completed_at: Optional[str] = None\n\n\nclass SagaOrchestrator:\n    \"\"\"Orchestrates multi-step agent transactions as sagas.\n\n    Each saga is a sequence of steps. Each step has:\n      - An execute function that performs the step's work\n      - A compensate function that undoes the step's effects\n      - Timeout and retry configuration\n\n    The orchestrator advances through steps, tracks state,\n    and handles failures by executing compensations in\n    reverse order.\n    \"\"\"\n\n    def __init__(self, event_bus: AsyncEventBus):\n        self.event_bus = event_bus\n        self._sagas: Dict[str, SagaInstance] = {}\n        self._step_definitions: Dict[str, List[SagaStep]] = {}\n\n    def define_saga(self, saga_type: str,\n                    steps: List[SagaStep]) -> None:\n        \"\"\"Define a saga type with its ordered steps.\"\"\"\n        self._step_definitions[saga_type] = steps\n        logger.info(f\"Defined saga '{saga_type}' with \"\n                    f\"{len(steps)} steps\")\n\n    async def start_saga(self, saga_type: str,\n                         saga_id: str,\n                         correlation_id: str,\n                         initial_context: dict) -> SagaInstance:\n        \"\"\"Start a new saga instance.\"\"\"\n        if saga_type not in self._step_definitions:\n            raise ValueError(f\"Unknown saga type: {saga_type}\")\n\n        instance = SagaInstance(\n            saga_id=saga_id,\n            correlation_id=correlation_id,\n            state=SagaState.RUNNING,\n            context=initial_context,\n            started_at=datetime.now(timezone.utc).isoformat(),\n        )\n        self._sagas[saga_id] = instance\n\n        await self.event_bus.publish(Event(\n            event_type=\"saga.started\",\n            source_agent_id=self.event_bus.agent_id,\n            correlation_id=correlation_id,\n            payload={\n                \"saga_id\": saga_id,\n                \"saga_type\": saga_type,\n                \"steps\": [s.name for s\n                          in self._step_definitions[saga_type]],\n            },\n        ))\n\n        # Execute steps\n        steps = self._step_definitions[saga_type]\n        for i, step in enumerate(steps):\n            instance.current_step = i\n\n            try:\n                result = await self._execute_step(\n                    instance, step\n                )\n                # Store step result in context for subsequent steps\n                instance.context[f\"step_{step.name}_result\"] = result\n                instance.completed_steps.append(step.name)\n                instance.compensation_stack.append(\n                    (step.name, instance.context.copy())\n                )\n\n                await self.event_bus.publish(Event(\n                    event_type=\"saga.step_completed\",\n                    source_agent_id=self.event_bus.agent_id,\n                    correlation_id=correlation_id,\n                    payload={\n                        \"saga_id\": saga_id,\n                        \"step\": step.name,\n                        \"step_index\": i,\n                        \"result\": result,\n                    },\n                ))\n\n            except Exception as e:\n                logger.error(\n                    f\"Saga {saga_id} step '{step.name}' failed: {e}\"\n                )\n                instance.error = str(e)\n\n                await self.event_bus.publish(Event(\n                    event_type=\"saga.step_failed\",\n                    source_agent_id=self.event_bus.agent_id,\n                    correlation_id=correlation_id,\n                    payload={\n                        \"saga_id\": saga_id,\n                        \"step\": step.name,\n                        \"error\": str(e),\n                    },\n                ))\n\n                # Begin compensation\n                await self._compensate(instance, steps)\n                return instance\n\n        # All steps completed successfully\n        instance.state = SagaState.COMPLETED\n        instance.completed_at = datetime.now(timezone.utc).isoformat()\n\n        await self.event_bus.publish(Event(\n            event_type=\"saga.completed\",\n            source_agent_id=self.event_bus.agent_id,\n            correlation_id=correlation_id,\n            payload={\n                \"saga_id\": saga_id,\n                \"completed_steps\": instance.completed_steps,\n            },\n        ))\n\n        return instance\n\n    async def _execute_step(self, instance: SagaInstance,\n                            step: SagaStep) -> dict:\n        \"\"\"Execute a single saga step with retries and timeout.\"\"\"\n        last_error = None\n        for attempt in range(step.max_retries):\n            try:\n                result = await asyncio.wait_for(\n                    step.execute(instance.context),\n                    timeout=step.timeout_seconds,\n                )\n                return result\n            except asyncio.TimeoutError:\n                last_error = (\n                    f\"Step '{step.name}' timed out after \"\n                    f\"{step.timeout_seconds}s\"\n                )\n                logger.warning(\n                    f\"{last_error} (attempt {attempt + 1}\u002F\"\n                    f\"{step.max_retries})\"\n                )\n            except Exception as e:\n                last_error = str(e)\n                logger.warning(\n                    f\"Step '{step.name}' failed: {e} \"\n                    f\"(attempt {attempt + 1}\u002F{step.max_retries})\"\n                )\n\n            if attempt \u003C step.max_retries - 1:\n                delay = step.retry_delay_seconds * (2 ** attempt)\n                await asyncio.sleep(delay)\n\n        raise RuntimeError(\n            f\"Step '{step.name}' failed after \"\n            f\"{step.max_retries} attempts: {last_error}\"\n        )\n\n    async def _compensate(self, instance: SagaInstance,\n                          steps: List[SagaStep]) -> None:\n        \"\"\"Execute compensating transactions in reverse order.\"\"\"\n        instance.state = SagaState.COMPENSATING\n\n        while instance.compensation_stack:\n            step_name, step_context = (\n                instance.compensation_stack.pop()\n            )\n            step_def = next(\n                s for s in steps if s.name == step_name\n            )\n\n            try:\n                await asyncio.wait_for(\n                    step_def.compensate(step_context),\n                    timeout=step_def.timeout_seconds,\n                )\n                logger.info(\n                    f\"Saga {instance.saga_id}: compensated \"\n                    f\"'{step_name}'\"\n                )\n\n                await self.event_bus.publish(Event(\n                    event_type=\"saga.step_compensated\",\n                    source_agent_id=self.event_bus.agent_id,\n                    correlation_id=instance.correlation_id,\n                    payload={\n                        \"saga_id\": instance.saga_id,\n                        \"step\": step_name,\n                    },\n                ))\n\n            except Exception as e:\n                logger.error(\n                    f\"Saga {instance.saga_id}: compensation \"\n                    f\"of '{step_name}' FAILED: {e}\"\n                )\n                instance.state = SagaState.COMPENSATION_FAILED\n                instance.error = (\n                    f\"Compensation failed at '{step_name}': {e}\"\n                )\n\n                await self.event_bus.publish(Event(\n                    event_type=\"saga.compensation_failed\",\n                    source_agent_id=self.event_bus.agent_id,\n                    correlation_id=instance.correlation_id,\n                    payload={\n                        \"saga_id\": instance.saga_id,\n                        \"step\": step_name,\n                        \"error\": str(e),\n                        \"remaining_compensations\": [\n                            s for s, _ in\n                            instance.compensation_stack\n                        ],\n                    },\n                ))\n                return\n\n        instance.state = SagaState.FAILED\n        instance.completed_at = datetime.now(timezone.utc).isoformat()\n\n        await self.event_bus.publish(Event(\n            event_type=\"saga.failed\",\n            source_agent_id=self.event_bus.agent_id,\n            correlation_id=instance.correlation_id,\n            payload={\n                \"saga_id\": instance.saga_id,\n                \"original_error\": instance.error,\n                \"compensated_steps\": instance.completed_steps,\n            },\n        ))\n\n    def get_saga(self, saga_id: str) -> Optional[SagaInstance]:\n        \"\"\"Retrieve the current state of a saga.\"\"\"\n        return self._sagas.get(saga_id)\n```\n\n### Example: Purchase-Verify-Escrow-Deliver-Release Saga\n\nHere is a complete saga definition for a standard agent commerce purchase. Each step's execute function calls the GreenHelix API, and each compensation function reverses the effect.\n\n```python\nimport aiohttp\n\nasync def make_api_call(session: aiohttp.ClientSession,\n                        base_url: str, tool: str,\n                        input_data: dict) -> dict:\n    \"\"\"Helper to call a GreenHelix tool asynchronously.\"\"\"\n    async with session.post(\n        f\"{base_url}\u002Fv1\",\n        json={\"tool\": tool, \"input\": input_data},\n    ) as resp:\n        resp.raise_for_status()\n        return await resp.json()\n\n\ndef build_purchase_saga(session: aiohttp.ClientSession,\n                        base_url: str,\n                        buyer_id: str) -> List[SagaStep]:\n    \"\"\"Build the step definitions for a purchase saga.\"\"\"\n\n    async def verify_balance(ctx: dict) -> dict:\n        result = await make_api_call(session, base_url,\n            \"get_balance\", {\"agent_id\": buyer_id})\n        balance = float(result.get(\"balance\", 0))\n        required = float(ctx[\"amount\"])\n        if balance \u003C required:\n            raise ValueError(\n                f\"Insufficient balance: {balance} \u003C {required}\"\n            )\n        return {\"verified_balance\": balance}\n\n    async def unreserve_balance(ctx: dict) -> None:\n        # Balance verification has no side effect to undo\n        pass\n\n    async def create_escrow(ctx: dict) -> dict:\n        result = await make_api_call(session, base_url,\n            \"create_escrow\", {\n                \"agent_id\": buyer_id,\n                \"counterparty_id\": ctx[\"seller_id\"],\n                \"amount\": ctx[\"amount\"],\n                \"currency\": \"USD\",\n                \"conditions\": json.dumps({\n                    \"service\": ctx[\"service_id\"],\n                    \"evaluation_days\": ctx.get(\n                        \"evaluation_days\", 7\n                    ),\n                }),\n            })\n        return {\"escrow_id\": result.get(\"escrow_id\")}\n\n    async def cancel_escrow(ctx: dict) -> None:\n        escrow_id = ctx.get(\"step_create_escrow_result\", {}).get(\n            \"escrow_id\"\n        )\n        if escrow_id:\n            await make_api_call(session, base_url,\n                \"release_escrow\", {\n                    \"agent_id\": buyer_id,\n                    \"escrow_id\": escrow_id,\n                    \"release_to\": buyer_id,\n                    \"reason\": \"saga_compensation\",\n                })\n\n    async def create_sla(ctx: dict) -> dict:\n        result = await make_api_call(session, base_url,\n            \"create_sla\", {\n                \"agent_id\": buyer_id,\n                \"provider_id\": ctx[\"seller_id\"],\n                \"metric\": ctx.get(\"sla_metric\", \"uptime\"),\n                \"threshold\": str(ctx.get(\n                    \"sla_threshold\", 99.9\n                )),\n                \"window_hours\": str(ctx.get(\n                    \"sla_window_hours\", 720\n                )),\n            })\n        return {\"sla_id\": result.get(\"sla_id\")}\n\n    async def cancel_sla(ctx: dict) -> None:\n        # SLA cancellation: record the cancellation\n        sla_id = ctx.get(\"step_create_sla_result\", {}).get(\n            \"sla_id\"\n        )\n        if sla_id:\n            await make_api_call(session, base_url,\n                \"record_transaction\", {\n                    \"agent_id\": buyer_id,\n                    \"transaction_type\": \"sla_cancelled\",\n                    \"amount\": \"0\",\n                    \"currency\": \"USD\",\n                    \"metadata\": json.dumps({\n                        \"sla_id\": sla_id,\n                        \"reason\": \"saga_compensation\",\n                    }),\n                })\n\n    async def notify_seller(ctx: dict) -> dict:\n        escrow_id = ctx.get(\"step_create_escrow_result\", {}).get(\n            \"escrow_id\"\n        )\n        sla_id = ctx.get(\"step_create_sla_result\", {}).get(\n            \"sla_id\"\n        )\n        result = await make_api_call(session, base_url,\n            \"send_message\", {\n                \"sender_id\": buyer_id,\n                \"receiver_id\": ctx[\"seller_id\"],\n                \"message_type\": \"delivery_request\",\n                \"content\": json.dumps({\n                    \"escrow_id\": escrow_id,\n                    \"sla_id\": sla_id,\n                    \"service_id\": ctx[\"service_id\"],\n                    \"delivery_deadline\": ctx.get(\n                        \"delivery_deadline\"\n                    ),\n                }),\n            })\n        return {\"message_id\": result.get(\"message_id\")}\n\n    async def cancel_notification(ctx: dict) -> None:\n        await make_api_call(session, base_url,\n            \"send_message\", {\n                \"sender_id\": buyer_id,\n                \"receiver_id\": ctx[\"seller_id\"],\n                \"message_type\": \"delivery_cancelled\",\n                \"content\": json.dumps({\n                    \"reason\": \"saga_compensation\",\n                    \"original_service\": ctx[\"service_id\"],\n                }),\n            })\n\n    async def record_transaction(ctx: dict) -> dict:\n        escrow_id = ctx.get(\"step_create_escrow_result\", {}).get(\n            \"escrow_id\"\n        )\n        result = await make_api_call(session, base_url,\n            \"record_transaction\", {\n                \"agent_id\": buyer_id,\n                \"transaction_type\": \"purchase\",\n                \"amount\": ctx[\"amount\"],\n                \"currency\": \"USD\",\n                \"counterparty_id\": ctx[\"seller_id\"],\n                \"metadata\": json.dumps({\n                    \"escrow_id\": escrow_id,\n                    \"service_id\": ctx[\"service_id\"],\n                }),\n            })\n        return {\"transaction_id\": result.get(\"transaction_id\")}\n\n    async def void_transaction(ctx: dict) -> None:\n        tx_id = ctx.get(\n            \"step_record_transaction_result\", {}\n        ).get(\"transaction_id\")\n        if tx_id:\n            await make_api_call(session, base_url,\n                \"record_transaction\", {\n                    \"agent_id\": buyer_id,\n                    \"transaction_type\": \"purchase_voided\",\n                    \"amount\": ctx[\"amount\"],\n                    \"currency\": \"USD\",\n                    \"counterparty_id\": ctx[\"seller_id\"],\n                    \"metadata\": json.dumps({\n                        \"voided_transaction_id\": tx_id,\n                        \"reason\": \"saga_compensation\",\n                    }),\n                })\n\n    return [\n        SagaStep(\"verify_balance\", verify_balance,\n                 unreserve_balance, timeout_seconds=10.0),\n        SagaStep(\"create_escrow\", create_escrow,\n                 cancel_escrow, timeout_seconds=30.0),\n        SagaStep(\"create_sla\", create_sla,\n                 cancel_sla, timeout_seconds=30.0),\n        SagaStep(\"notify_seller\", notify_seller,\n                 cancel_notification, timeout_seconds=15.0),\n        SagaStep(\"record_transaction\", record_transaction,\n                 void_transaction, timeout_seconds=15.0),\n    ]\n```\n\nThe saga state machine transitions are deterministic:\n\n```\n  PENDING ──start──► RUNNING\n                        │\n              ┌─────────┼──────────┐\n              │ all steps succeed   │ a step fails\n              ▼                     ▼\n          COMPLETED           COMPENSATING\n                                    │\n                          ┌─────────┼──────────┐\n                          │ all compensations  │ compensation\n                          │ succeed            │ fails\n                          ▼                     ▼\n                       FAILED            COMPENSATION_FAILED\n                  (clean failure)      (requires manual intervention)\n```\n\n`COMPENSATION_FAILED` is the state you never want to reach. It means the saga could not undo its partial effects, leaving the system in an inconsistent state. The dead letter handling system (Chapter 5) is designed to catch these cases and alert operators.\n\n---\n\n## Chapter 4: Compensating Transactions\n\n### What Happens When Step 4 of 6 Fails?\n\nThe saga orchestrator handles the mechanics of running compensations in reverse order. But the hard part is designing the compensating transactions themselves. Each compensation must satisfy three properties: it must be **idempotent** (safe to run multiple times), **commutative** with respect to other compensations (the order should not matter for the final state, though we execute in reverse for consistency), and **eventually consistent** (it is acceptable for the system to pass through intermediate inconsistent states as long as all compensations eventually complete).\n\nConsider the failure scenario in detail. A buyer agent is executing a five-step purchase saga. Steps 1-3 complete successfully: balance verified, escrow created with $500 locked, SLA registered. Step 4 -- notifying the seller to begin delivery -- fails because the seller's agent is unreachable. The system is now in an inconsistent state: $500 is locked in escrow for a service that will never be delivered, and an SLA is monitoring a provider that has not acknowledged the order.\n\nThe compensation sequence:\n\n1. **Compensate step 3 (cancel SLA):** The SLA was registered via `create_sla`. GreenHelix does not have a `delete_sla` tool, so compensation records a cancellation event via `record_transaction` with type `sla_cancelled`. The SLA technically still exists on the platform, but the cancellation record serves as an audit trail, and the monitoring system can filter out cancelled SLAs.\n\n2. **Compensate step 2 (release escrow):** The escrow was created via `create_escrow`. Compensation calls `release_escrow` with `release_to` set to the buyer's agent ID, returning the $500 to the buyer. This is the critical compensation -- if this fails, real money is stuck in limbo.\n\n3. **Compensate step 1 (unreserve balance):** Balance verification was a read-only check with no side effects. The compensation is a no-op.\n\n### The CompensatingTransaction Class\n\nFor complex compensations that involve multiple API calls, the `CompensatingTransaction` class provides structure:\n\n```python\n@dataclass\nclass CompensationRecord:\n    \"\"\"Record of a single compensation attempt.\"\"\"\n    step_name: str\n    attempted_at: str\n    succeeded: bool\n    error: Optional[str] = None\n    retry_count: int = 0\n    idempotency_key: str = \"\"\n\n\nclass CompensatingTransaction:\n    \"\"\"Manages compensating transactions for a failed saga.\n\n    Handles:\n      - Idempotent compensation execution\n      - Retry with exponential backoff\n      - Compensation audit trail\n      - Escalation on repeated failure\n    \"\"\"\n\n    def __init__(self, session: aiohttp.ClientSession,\n                 base_url: str, agent_id: str,\n                 event_bus: AsyncEventBus):\n        self.session = session\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.event_bus = event_bus\n        self._records: List[CompensationRecord] = []\n\n    async def compensate_escrow(self, escrow_id: str,\n                                buyer_id: str,\n                                amount: str,\n                                idempotency_key: str) -> dict:\n        \"\"\"Release escrow funds back to the buyer.\n\n        This is the most critical compensation -- funds must\n        not remain locked.\n        \"\"\"\n        record = CompensationRecord(\n            step_name=\"release_escrow\",\n            attempted_at=datetime.now(timezone.utc).isoformat(),\n            succeeded=False,\n            idempotency_key=idempotency_key,\n        )\n\n        max_retries = 5\n        for attempt in range(max_retries):\n            try:\n                result = await make_api_call(\n                    self.session, self.base_url,\n                    \"release_escrow\", {\n                        \"agent_id\": buyer_id,\n                        \"escrow_id\": escrow_id,\n                        \"release_to\": buyer_id,\n                        \"reason\": \"saga_compensation\",\n                        \"idempotency_key\": idempotency_key,\n                    },\n                )\n                record.succeeded = True\n                record.retry_count = attempt\n                self._records.append(record)\n\n                await self.event_bus.publish(Event(\n                    event_type=\"compensation.escrow_released\",\n                    source_agent_id=self.agent_id,\n                    payload={\n                        \"escrow_id\": escrow_id,\n                        \"amount\": amount,\n                        \"released_to\": buyer_id,\n                        \"idempotency_key\": idempotency_key,\n                    },\n                ))\n                return result\n\n            except Exception as e:\n                record.error = str(e)\n                record.retry_count = attempt + 1\n                delay = min(2 ** attempt, 30)\n                logger.warning(\n                    f\"Escrow compensation failed (attempt \"\n                    f\"{attempt + 1}\u002F{max_retries}): {e}\"\n                )\n                if attempt \u003C max_retries - 1:\n                    await asyncio.sleep(delay)\n\n        # All retries exhausted -- escalate\n        record.succeeded = False\n        self._records.append(record)\n        await self._escalate(\n            \"escrow_release_failed\",\n            {\n                \"escrow_id\": escrow_id,\n                \"amount\": amount,\n                \"buyer_id\": buyer_id,\n                \"attempts\": max_retries,\n                \"last_error\": record.error,\n            },\n        )\n        raise RuntimeError(\n            f\"Failed to release escrow {escrow_id} after \"\n            f\"{max_retries} attempts\"\n        )\n\n    async def compensate_payment(self, transaction_id: str,\n                                 amount: str,\n                                 payer_id: str,\n                                 payee_id: str,\n                                 idempotency_key: str) -> dict:\n        \"\"\"Reverse a payment by recording a refund transaction.\"\"\"\n        result = await make_api_call(\n            self.session, self.base_url,\n            \"record_transaction\", {\n                \"agent_id\": payer_id,\n                \"transaction_type\": \"refund\",\n                \"amount\": amount,\n                \"currency\": \"USD\",\n                \"counterparty_id\": payee_id,\n                \"metadata\": json.dumps({\n                    \"original_transaction_id\": transaction_id,\n                    \"reason\": \"saga_compensation\",\n                    \"idempotency_key\": idempotency_key,\n                }),\n            },\n        )\n\n        record = CompensationRecord(\n            step_name=\"refund_payment\",\n            attempted_at=datetime.now(timezone.utc).isoformat(),\n            succeeded=True,\n            idempotency_key=idempotency_key,\n        )\n        self._records.append(record)\n        return result\n\n    async def compensate_service_registration(\n        self, service_id: str,\n        agent_id: str,\n        idempotency_key: str,\n    ) -> dict:\n        \"\"\"Deregister a service that was registered as part\n        of the saga.\"\"\"\n        result = await make_api_call(\n            self.session, self.base_url,\n            \"record_transaction\", {\n                \"agent_id\": agent_id,\n                \"transaction_type\": \"service_deregistered\",\n                \"amount\": \"0\",\n                \"currency\": \"USD\",\n                \"metadata\": json.dumps({\n                    \"service_id\": service_id,\n                    \"reason\": \"saga_compensation\",\n                    \"idempotency_key\": idempotency_key,\n                }),\n            },\n        )\n\n        record = CompensationRecord(\n            step_name=\"deregister_service\",\n            attempted_at=datetime.now(timezone.utc).isoformat(),\n            succeeded=True,\n            idempotency_key=idempotency_key,\n        )\n        self._records.append(record)\n        return result\n\n    async def _escalate(self, failure_type: str,\n                        details: dict) -> None:\n        \"\"\"Escalate a compensation failure for manual\n        intervention.\"\"\"\n        await self.event_bus.publish(Event(\n            event_type=\"compensation.escalation_required\",\n            source_agent_id=self.agent_id,\n            payload={\n                \"failure_type\": failure_type,\n                \"details\": details,\n                \"compensation_history\": [\n                    {\n                        \"step\": r.step_name,\n                        \"succeeded\": r.succeeded,\n                        \"retries\": r.retry_count,\n                        \"error\": r.error,\n                    }\n                    for r in self._records\n                ],\n                \"escalated_at\": datetime.now(\n                    timezone.utc\n                ).isoformat(),\n            },\n        ))\n        logger.critical(\n            f\"COMPENSATION ESCALATION: {failure_type} -- \"\n            f\"{json.dumps(details)}\"\n        )\n\n    def get_compensation_report(self) -> dict:\n        \"\"\"Return a summary of all compensation actions taken.\"\"\"\n        return {\n            \"total_compensations\": len(self._records),\n            \"succeeded\": sum(\n                1 for r in self._records if r.succeeded\n            ),\n            \"failed\": sum(\n                1 for r in self._records if not r.succeeded\n            ),\n            \"records\": [\n                {\n                    \"step\": r.step_name,\n                    \"succeeded\": r.succeeded,\n                    \"retries\": r.retry_count,\n                    \"error\": r.error,\n                    \"idempotency_key\": r.idempotency_key,\n                }\n                for r in self._records\n            ],\n        }\n```\n\n### Idempotency Requirements\n\nEvery compensating transaction must be idempotent. If the compensation for \"release escrow\" is called twice -- because the first call succeeded on the server but the response was lost due to a network timeout -- the second call must not release the escrow a second time or fail with an error. The `idempotency_key` parameter handles this at the API level: GreenHelix deduplicates calls with the same idempotency key and returns the result of the original call.\n\nThe key generation strategy matters. A good idempotency key for a compensation is deterministic from the saga context: `f\"compensate:{saga_id}:{step_name}\"`. This ensures that retrying the same compensation for the same saga step always produces the same key, regardless of how many times the retry logic executes.\n\n```python\ndef make_compensation_key(saga_id: str, step_name: str) -> str:\n    \"\"\"Generate a deterministic idempotency key for a\n    compensation action.\"\"\"\n    raw = f\"compensate:{saga_id}:{step_name}\"\n    return hashlib.sha256(raw.encode()).hexdigest()[:32]\n\n\n# Usage in a saga compensation:\nkey = make_compensation_key(\"saga-purchase-001\", \"create_escrow\")\n# key: \"a1b2c3d4...\" -- same every time for this saga+step\nawait compensator.compensate_escrow(\n    escrow_id=\"esc_xyz\",\n    buyer_id=\"agent-buyer-042\",\n    amount=\"500.00\",\n    idempotency_key=key,\n)\n```\n\n---\n\n## Chapter 5: Dead Letter Handling\n\n### Events That Cannot Be Processed\n\nA dead letter is an event that has been attempted and failed multiple times. The event itself is well-formed -- it passes schema validation, it was published by a legitimate agent, and the event bus delivered it successfully. But the handler that received it could not process it. Maybe the handler depends on an external service that is down. Maybe the event references an entity that does not exist yet (a race condition). Maybe the handler has a bug that throws an exception for this specific payload.\n\nDead letters are inevitable in any event-driven system. The question is not whether they will occur but how you handle them when they do. The wrong answer is to silently drop them. The right answer is a dead letter queue (DLQ) with configurable retry policies, monitoring, and manual intervention workflows.\n\n### Dead Letter Queue Implementation\n\n```python\n@dataclass\nclass DeadLetter:\n    \"\"\"An event that failed processing.\"\"\"\n    event: Event\n    error: str\n    handler_name: str\n    first_failed_at: str\n    last_failed_at: str\n    attempt_count: int\n    next_retry_at: Optional[str] = None\n    status: str = \"pending\"   # pending, retrying, exhausted, resolved\n\n\nclass DeadLetterQueue:\n    \"\"\"Dead letter queue with retry policies and alerting.\n\n    Failed events are stored in the DLQ with their failure\n    metadata. The queue supports three retry policies:\n      - immediate: retry once immediately\n      - exponential_backoff: retry with increasing delays\n      - circuit_breaker: stop retrying after threshold\n\n    Events that exhaust all retry attempts are marked\n    'exhausted' and require manual intervention.\n    \"\"\"\n\n    def __init__(self, event_bus: AsyncEventBus,\n                 max_retries: int = 5,\n                 base_delay_seconds: float = 5.0,\n                 max_delay_seconds: float = 300.0,\n                 circuit_breaker_threshold: int = 10):\n        self.event_bus = event_bus\n        self.max_retries = max_retries\n        self.base_delay = base_delay_seconds\n        self.max_delay = max_delay_seconds\n        self.circuit_breaker_threshold = circuit_breaker_threshold\n\n        self._queue: Dict[str, DeadLetter] = {}\n        self._failure_counts: Dict[str, int] = defaultdict(int)\n        self._circuit_open: Dict[str, bool] = {}\n        self._handlers: Dict[str, EventHandler] = {}\n        self._running = False\n\n    async def enqueue(self, event: Event, error: str,\n                      handler_name: str) -> None:\n        \"\"\"Add a failed event to the dead letter queue.\"\"\"\n        now = datetime.now(timezone.utc).isoformat()\n\n        if event.event_id in self._queue:\n            dl = self._queue[event.event_id]\n            dl.attempt_count += 1\n            dl.last_failed_at = now\n            dl.error = error\n        else:\n            dl = DeadLetter(\n                event=event,\n                error=error,\n                handler_name=handler_name,\n                first_failed_at=now,\n                last_failed_at=now,\n                attempt_count=1,\n            )\n            self._queue[event.event_id] = dl\n\n        # Update circuit breaker state\n        self._failure_counts[handler_name] += 1\n        if (self._failure_counts[handler_name]\n                >= self.circuit_breaker_threshold):\n            self._circuit_open[handler_name] = True\n            logger.critical(\n                f\"Circuit breaker OPEN for handler \"\n                f\"'{handler_name}' -- \"\n                f\"{self._failure_counts[handler_name]} failures\"\n            )\n\n        # Schedule retry or mark exhausted\n        if dl.attempt_count >= self.max_retries:\n            dl.status = \"exhausted\"\n            await self._alert_exhausted(dl)\n        else:\n            delay = self._calculate_delay(dl.attempt_count)\n            retry_at = datetime.now(timezone.utc)\n            dl.next_retry_at = retry_at.isoformat()\n            dl.status = \"pending\"\n\n        await self.event_bus.publish(Event(\n            event_type=\"dlq.event_enqueued\",\n            source_agent_id=self.event_bus.agent_id,\n            payload={\n                \"dead_letter_event_id\": event.event_id,\n                \"event_type\": event.event_type,\n                \"attempt_count\": dl.attempt_count,\n                \"status\": dl.status,\n                \"error\": error,\n            },\n        ))\n\n        logger.warning(\n            f\"DLQ: {event.event_type} [{event.event_id}] -- \"\n            f\"attempt {dl.attempt_count}\u002F{self.max_retries} -- \"\n            f\"{error}\"\n        )\n\n    def _calculate_delay(self, attempt: int) -> float:\n        \"\"\"Calculate retry delay with exponential backoff\n        and jitter.\"\"\"\n        import random\n        delay = self.base_delay * (2 ** (attempt - 1))\n        delay = min(delay, self.max_delay)\n        jitter = random.uniform(0, delay * 0.1)\n        return delay + jitter\n\n    async def start_retry_loop(self,\n                               handlers: Dict[\n                                   str, EventHandler\n                               ]) -> None:\n        \"\"\"Start the background retry loop.\"\"\"\n        self._handlers = handlers\n        self._running = True\n        asyncio.create_task(self._retry_loop())\n\n    async def _retry_loop(self) -> None:\n        \"\"\"Process pending dead letters on schedule.\"\"\"\n        while self._running:\n            now = datetime.now(timezone.utc).isoformat()\n            for event_id, dl in list(self._queue.items()):\n                if dl.status != \"pending\":\n                    continue\n                if dl.next_retry_at and dl.next_retry_at > now:\n                    continue\n\n                handler_name = dl.handler_name\n                if self._circuit_open.get(handler_name, False):\n                    logger.debug(\n                        f\"Skipping retry: circuit open for \"\n                        f\"'{handler_name}'\"\n                    )\n                    continue\n\n                handler = self._handlers.get(handler_name)\n                if not handler:\n                    continue\n\n                dl.status = \"retrying\"\n                try:\n                    await handler(dl.event)\n                    dl.status = \"resolved\"\n                    logger.info(\n                        f\"DLQ: resolved {dl.event.event_id} \"\n                        f\"on attempt {dl.attempt_count + 1}\"\n                    )\n                    # Reset circuit breaker on success\n                    self._failure_counts[handler_name] = max(\n                        0,\n                        self._failure_counts[handler_name] - 1,\n                    )\n                    if self._failure_counts[handler_name] == 0:\n                        self._circuit_open[handler_name] = False\n\n                except Exception as e:\n                    await self.enqueue(\n                        dl.event, str(e), handler_name\n                    )\n\n            await asyncio.sleep(1.0)\n\n    async def _alert_exhausted(self, dl: DeadLetter) -> None:\n        \"\"\"Alert that an event has exhausted all retries.\"\"\"\n        await self.event_bus.publish(Event(\n            event_type=\"dlq.exhausted\",\n            source_agent_id=self.event_bus.agent_id,\n            payload={\n                \"event_id\": dl.event.event_id,\n                \"event_type\": dl.event.event_type,\n                \"handler\": dl.handler_name,\n                \"attempts\": dl.attempt_count,\n                \"first_failed\": dl.first_failed_at,\n                \"last_failed\": dl.last_failed_at,\n                \"last_error\": dl.error,\n                \"action_required\": \"manual_intervention\",\n            },\n        ))\n        logger.critical(\n            f\"DLQ EXHAUSTED: {dl.event.event_type} \"\n            f\"[{dl.event.event_id}] after {dl.attempt_count} \"\n            f\"attempts -- manual intervention required\"\n        )\n\n    def get_queue_depth(self) -> dict:\n        \"\"\"Return current DLQ metrics.\"\"\"\n        by_status = defaultdict(int)\n        by_handler = defaultdict(int)\n        for dl in self._queue.values():\n            by_status[dl.status] += 1\n            by_handler[dl.handler_name] += 1\n\n        return {\n            \"total\": len(self._queue),\n            \"by_status\": dict(by_status),\n            \"by_handler\": dict(by_handler),\n            \"circuit_breakers\": {\n                k: \"open\" if v else \"closed\"\n                for k, v in self._circuit_open.items()\n            },\n        }\n\n    async def resolve_manually(self, event_id: str,\n                               resolution: str) -> None:\n        \"\"\"Mark a dead letter as manually resolved.\"\"\"\n        if event_id in self._queue:\n            dl = self._queue[event_id]\n            dl.status = \"resolved\"\n            await self.event_bus.publish(Event(\n                event_type=\"dlq.manually_resolved\",\n                source_agent_id=self.event_bus.agent_id,\n                payload={\n                    \"event_id\": event_id,\n                    \"resolution\": resolution,\n                    \"resolved_at\": datetime.now(\n                        timezone.utc\n                    ).isoformat(),\n                },\n            ))\n```\n\n### Retry Policy Summary\n\n```\nRetry Policy: Exponential Backoff with Circuit Breaker\n=======================================================\n\nAttempt   Delay        Cumulative Wait\n────────────────────────────────────────\n1         5s           5s\n2         10s          15s\n3         20s          35s\n4         40s          75s (1m 15s)\n5         80s          155s (2m 35s)\n  ──── MAX RETRIES REACHED ────\n  Status: exhausted\n  Action: manual intervention required\n\nCircuit Breaker:\n  Threshold: 10 consecutive failures per handler\n  State: OPEN (all retries skipped)\n  Recovery: automatic on successful retry\n```\n\n### Alerting on Dead Letters\n\nThe `dlq.exhausted` event is the critical signal. Subscribe to it in your monitoring system and route it to an alerting channel -- PagerDuty, Slack, email, whatever your operations team monitors. An exhausted dead letter means automated recovery has failed and a human (or a supervisory agent) must intervene. The event payload contains everything needed to diagnose the problem: the original event, the handler that failed, the number of attempts, and the last error message.\n\n---\n\n## Chapter 6: Exactly-Once Processing\n\n### The Challenge\n\nDistributed systems offer three delivery guarantees: at-most-once (fire and forget), at-least-once (retry until acknowledged), and exactly-once (process each event exactly one time). At-most-once loses events. At-least-once duplicates events. Exactly-once is what you want -- and what everyone claims is impossible.\n\nThe practical answer is: exactly-once processing is achieved by combining at-least-once delivery with idempotent handlers. The event bus guarantees that every event is delivered at least once (it retries on failure). Your handlers guarantee that processing the same event twice produces the same result as processing it once (idempotency). Together, these two properties give you exactly-once semantics from the application's perspective, even though the underlying delivery mechanism may send duplicates.\n\n### Idempotency Key Patterns\n\nEvery GreenHelix API call that creates or modifies state should include an idempotency key. The key must be deterministic from the event that triggered the call. If the same event triggers the same handler twice, the same idempotency key is generated, and GreenHelix deduplicates the second call.\n\n```python\nclass IdempotencyKeyGenerator:\n    \"\"\"Generate deterministic idempotency keys from events.\"\"\"\n\n    @staticmethod\n    def for_event(event: Event, operation: str) -> str:\n        \"\"\"Generate an idempotency key for an operation\n        triggered by an event.\"\"\"\n        raw = (\n            f\"{event.event_id}:{operation}:\"\n            f\"{event.source_agent_id}\"\n        )\n        return hashlib.sha256(raw.encode()).hexdigest()[:32]\n\n    @staticmethod\n    def for_saga_step(saga_id: str, step_name: str,\n                      attempt: int = 0) -> str:\n        \"\"\"Generate an idempotency key for a saga step.\n\n        Note: attempt is NOT included by default. This ensures\n        retries of the same step produce the same key, which is\n        the correct behavior for idempotent operations.\n        \"\"\"\n        raw = f\"saga:{saga_id}:step:{step_name}\"\n        return hashlib.sha256(raw.encode()).hexdigest()[:32]\n\n    @staticmethod\n    def for_compensation(saga_id: str,\n                         step_name: str) -> str:\n        \"\"\"Generate an idempotency key for a compensating\n        transaction.\"\"\"\n        raw = f\"compensate:{saga_id}:{step_name}\"\n        return hashlib.sha256(raw.encode()).hexdigest()[:32]\n```\n\n### Deduplication Strategies\n\nClient-side deduplication provides an additional layer of protection. The `AsyncEventBus` already tracks processed event IDs in `_processed_ids`. For handlers that need stronger guarantees, a persistent deduplication store ensures that events are not reprocessed after a process restart.\n\n```python\nclass EventDeduplicator:\n    \"\"\"Client-side event deduplication with persistent storage.\n\n    Stores processed event IDs with timestamps. Supports\n    TTL-based expiry to prevent unbounded memory growth.\n    \"\"\"\n\n    def __init__(self, ttl_seconds: int = 86400):\n        self._processed: Dict[str, float] = {}\n        self.ttl_seconds = ttl_seconds\n\n    def is_duplicate(self, event_id: str) -> bool:\n        \"\"\"Check if an event has already been processed.\"\"\"\n        self._evict_expired()\n        return event_id in self._processed\n\n    def mark_processed(self, event_id: str) -> None:\n        \"\"\"Mark an event as processed.\"\"\"\n        self._processed[event_id] = time.time()\n\n    def _evict_expired(self) -> None:\n        \"\"\"Remove entries older than TTL.\"\"\"\n        cutoff = time.time() - self.ttl_seconds\n        expired = [\n            eid for eid, ts in self._processed.items()\n            if ts \u003C cutoff\n        ]\n        for eid in expired:\n            del self._processed[eid]\n\n    @property\n    def size(self) -> int:\n        return len(self._processed)\n\n\n# Usage in a handler:\ndedup = EventDeduplicator(ttl_seconds=86400)  # 24 hour window\n\n\nasync def handle_escrow_created(event: Event) -> None:\n    if dedup.is_duplicate(event.event_id):\n        logger.info(f\"Skipping duplicate: {event.event_id}\")\n        return\n\n    # Process the event...\n    escrow_id = event.payload.get(\"escrow_id\")\n    # ... do work ...\n\n    dedup.mark_processed(event.event_id)\n```\n\n### The Outbox Pattern\n\nThe outbox pattern solves a subtle but critical problem: how do you atomically update your local state AND publish an event? If you update your local state first and then publish the event, a crash between the two operations leaves you with updated state but no event (the outside world does not know). If you publish the event first and then update local state, a crash leaves you with an event published but no local state update (you will re-publish when you restart).\n\nThe outbox pattern writes the event to a local \"outbox\" table in the same database transaction as the state update. A separate process reads the outbox and publishes events to the event bus. If publishing succeeds, the outbox entry is marked as sent. If publishing fails, the entry remains and will be retried.\n\n```python\nclass OutboxPublisher:\n    \"\"\"Implements the outbox pattern for reliable event\n    publishing.\n\n    Events are written to a local outbox (in-memory for this\n    example; use a database in production). A background task\n    reads the outbox and publishes events to the event bus.\n    Sent events are marked and eventually cleaned up.\n    \"\"\"\n\n    def __init__(self, event_bus: AsyncEventBus,\n                 flush_interval: float = 0.5):\n        self.event_bus = event_bus\n        self.flush_interval = flush_interval\n        self._outbox: List[dict] = []\n        self._lock = asyncio.Lock()\n        self._running = False\n\n    async def write(self, event: Event) -> None:\n        \"\"\"Write an event to the outbox.\n\n        Call this inside the same 'transaction' as your\n        state update. In production, this would be an INSERT\n        into an outbox table within the same DB transaction.\n        \"\"\"\n        async with self._lock:\n            self._outbox.append({\n                \"event\": event,\n                \"status\": \"pending\",\n                \"created_at\": datetime.now(\n                    timezone.utc\n                ).isoformat(),\n                \"attempts\": 0,\n            })\n\n    async def start(self) -> None:\n        \"\"\"Start the background publisher.\"\"\"\n        self._running = True\n        asyncio.create_task(self._flush_loop())\n\n    async def stop(self) -> None:\n        \"\"\"Stop the background publisher.\"\"\"\n        self._running = False\n\n    async def _flush_loop(self) -> None:\n        \"\"\"Continuously publish pending outbox events.\"\"\"\n        while self._running:\n            async with self._lock:\n                pending = [\n                    entry for entry in self._outbox\n                    if entry[\"status\"] == \"pending\"\n                ]\n\n            for entry in pending:\n                try:\n                    await self.event_bus.publish(entry[\"event\"])\n                    entry[\"status\"] = \"sent\"\n                except Exception as e:\n                    entry[\"attempts\"] += 1\n                    logger.warning(\n                        f\"Outbox publish failed: {e} \"\n                        f\"(attempt {entry['attempts']})\"\n                    )\n                    if entry[\"attempts\"] >= 10:\n                        entry[\"status\"] = \"failed\"\n                        logger.error(\n                            f\"Outbox entry exhausted: \"\n                            f\"{entry['event'].event_id}\"\n                        )\n\n            # Clean up sent entries older than 1 hour\n            async with self._lock:\n                self._outbox = [\n                    e for e in self._outbox\n                    if e[\"status\"] != \"sent\"\n                ]\n\n            await asyncio.sleep(self.flush_interval)\n\n    @property\n    def pending_count(self) -> int:\n        return sum(\n            1 for e in self._outbox\n            if e[\"status\"] == \"pending\"\n        )\n```\n\nThe interaction between deduplication, idempotency keys, and the outbox pattern creates a three-layer defense against duplicate processing:\n\n```\nExactly-Once Processing: Three-Layer Defense\n=============================================\n\nLayer 1: OUTBOX PATTERN\n  State update + event write in same transaction\n  Guarantees: event is published if and only if\n              state was updated\n\nLayer 2: IDEMPOTENCY KEYS\n  Every API call includes a deterministic key\n  Guarantees: GreenHelix deduplicates repeated calls\n\nLayer 3: CLIENT-SIDE DEDUPLICATION\n  EventDeduplicator tracks processed event IDs\n  Guarantees: handler skips already-processed events\n\nTogether: exactly-once semantics from the\n          application's perspective\n```\n\n---\n\n## Chapter 7: Backpressure\n\n### What Happens When Events Arrive Faster Than Processing?\n\nBackpressure is what happens when a producer generates events faster than a consumer can process them. In agent commerce, this occurs during batch settlement (500 escrows releasing simultaneously), during market disruptions (every agent reacts to the same price signal at once), or during recovery from an outage (a backlog of unprocessed events floods the system when connectivity is restored).\n\nWithout backpressure management, the system fails in one of two ways. Either the event queue grows without bound until memory is exhausted, or the consumer falls so far behind that events become stale and the system processes outdated information. Both outcomes are catastrophic for financial operations where every event represents real money.\n\n### Rate Limiting Strategies\n\nThe `AsyncEventBus` already provides one form of backpressure through its `max_concurrent_handlers` semaphore. But that only controls concurrency within a single consumer. For fleet-wide backpressure, you need rate limiting at the API call level.\n\n```python\nclass RateLimiter:\n    \"\"\"Token bucket rate limiter for async operations.\n\n    Controls the rate of outbound API calls to stay within\n    GreenHelix tier limits and prevent overwhelming\n    downstream services.\n    \"\"\"\n\n    def __init__(self, rate: float, burst: int):\n        \"\"\"\n        Args:\n            rate: tokens per second (sustained rate)\n            burst: maximum tokens available (burst capacity)\n        \"\"\"\n        self.rate = rate\n        self.burst = burst\n        self._tokens = float(burst)\n        self._last_refill = time.monotonic()\n        self._lock = asyncio.Lock()\n\n    async def acquire(self, tokens: int = 1) -> float:\n        \"\"\"Acquire tokens, waiting if necessary.\n\n        Returns the time waited in seconds.\n        \"\"\"\n        waited = 0.0\n        async with self._lock:\n            self._refill()\n            while self._tokens \u003C tokens:\n                deficit = tokens - self._tokens\n                wait_time = deficit \u002F self.rate\n                await asyncio.sleep(wait_time)\n                waited += wait_time\n                self._refill()\n            self._tokens -= tokens\n        return waited\n\n    def _refill(self) -> None:\n        \"\"\"Refill tokens based on elapsed time.\"\"\"\n        now = time.monotonic()\n        elapsed = now - self._last_refill\n        self._tokens = min(\n            self.burst,\n            self._tokens + elapsed * self.rate,\n        )\n        self._last_refill = now\n\n    @property\n    def available_tokens(self) -> float:\n        self._refill()\n        return self._tokens\n\n\n# Usage: rate-limit GreenHelix API calls\n\n# Pro tier: 1000 calls\u002Fminute = ~16.7 calls\u002Fsecond\nlimiter = RateLimiter(rate=15.0, burst=50)\n\n\nasync def rate_limited_api_call(session, base_url,\n                                tool, input_data):\n    \"\"\"Make a GreenHelix API call with rate limiting.\"\"\"\n    wait = await limiter.acquire()\n    if wait > 0:\n        logger.debug(f\"Rate limited: waited {wait:.2f}s\")\n    return await make_api_call(session, base_url, tool,\n                               input_data)\n```\n\n### Queue Depth Monitoring\n\nMonitoring queue depth is essential for detecting backpressure before it becomes a problem. The metric to watch is the ratio of events arriving per second to events processed per second. When the ratio exceeds 1.0 for more than a few minutes, the queue is growing and backpressure management must engage.\n\n```python\nclass BackpressureMonitor:\n    \"\"\"Monitors event processing rate and queue depth.\n\n    Emits metrics and triggers load shedding when\n    the system is overwhelmed.\n    \"\"\"\n\n    def __init__(self, event_bus: AsyncEventBus,\n                 high_watermark: int = 1000,\n                 low_watermark: int = 100,\n                 check_interval: float = 5.0):\n        self.event_bus = event_bus\n        self.high_watermark = high_watermark\n        self.low_watermark = low_watermark\n        self.check_interval = check_interval\n\n        self._queue_depth = 0\n        self._events_received = 0\n        self._events_processed = 0\n        self._shedding = False\n        self._last_check = time.monotonic()\n        self._running = False\n\n    def record_received(self) -> None:\n        self._events_received += 1\n        self._queue_depth += 1\n\n    def record_processed(self) -> None:\n        self._events_processed += 1\n        self._queue_depth = max(0, self._queue_depth - 1)\n\n    @property\n    def is_shedding(self) -> bool:\n        return self._shedding\n\n    async def start(self) -> None:\n        self._running = True\n        asyncio.create_task(self._monitor_loop())\n\n    async def _monitor_loop(self) -> None:\n        while self._running:\n            now = time.monotonic()\n            elapsed = now - self._last_check\n\n            if elapsed > 0:\n                receive_rate = self._events_received \u002F elapsed\n                process_rate = self._events_processed \u002F elapsed\n            else:\n                receive_rate = 0\n                process_rate = 0\n\n            # Engage load shedding at high watermark\n            if (self._queue_depth >= self.high_watermark\n                    and not self._shedding):\n                self._shedding = True\n                logger.warning(\n                    f\"BACKPRESSURE: load shedding ENGAGED \"\n                    f\"(depth: {self._queue_depth})\"\n                )\n                await self.event_bus.publish(Event(\n                    event_type=\"system.backpressure_engaged\",\n                    source_agent_id=self.event_bus.agent_id,\n                    payload={\n                        \"queue_depth\": self._queue_depth,\n                        \"receive_rate\": round(receive_rate, 2),\n                        \"process_rate\": round(process_rate, 2),\n                    },\n                ))\n\n            # Disengage at low watermark\n            if (self._queue_depth \u003C= self.low_watermark\n                    and self._shedding):\n                self._shedding = False\n                logger.info(\n                    f\"BACKPRESSURE: load shedding DISENGAGED \"\n                    f\"(depth: {self._queue_depth})\"\n                )\n\n            # Reset counters\n            self._events_received = 0\n            self._events_processed = 0\n            self._last_check = now\n\n            await asyncio.sleep(self.check_interval)\n\n    def get_metrics(self) -> dict:\n        return {\n            \"queue_depth\": self._queue_depth,\n            \"shedding_active\": self._shedding,\n            \"high_watermark\": self.high_watermark,\n            \"low_watermark\": self.low_watermark,\n        }\n```\n\n### Load Shedding vs Buffering\n\nWhen backpressure engages, you have two choices: buffer events (accept them all and process them later) or shed load (reject or deprioritize low-priority events to protect high-priority processing).\n\nFor agent commerce, the answer is priority-based load shedding. Financial events (escrow releases, payments, dispute deadlines) must never be shed. Informational events (analytics updates, reputation refreshes, non-urgent notifications) can be deferred or dropped. The priority is encoded in the event type.\n\n```python\nclass PrioritizedEventProcessor:\n    \"\"\"Processes events with priority-based load shedding.\n\n    During backpressure, low-priority events are deferred\n    while high-priority events (financial operations) are\n    processed immediately.\n    \"\"\"\n\n    # Priority levels: lower number = higher priority\n    PRIORITY_MAP = {\n        \"escrow.*\": 1,\n        \"payment.*\": 1,\n        \"dispute.*\": 1,\n        \"saga.*\": 2,\n        \"sla.breached\": 2,\n        \"compensation.*\": 2,\n        \"sla.*\": 3,\n        \"message.*\": 3,\n        \"analytics.*\": 4,\n        \"reputation.*\": 4,\n        \"system.*\": 5,\n    }\n\n    def __init__(self, monitor: BackpressureMonitor,\n                 shed_threshold: int = 3):\n        \"\"\"\n        Args:\n            shed_threshold: events with priority >= this\n                            value are shed during backpressure.\n        \"\"\"\n        self.monitor = monitor\n        self.shed_threshold = shed_threshold\n        self._deferred: List[Event] = []\n\n    def should_process(self, event: Event) -> bool:\n        \"\"\"Determine if an event should be processed now.\"\"\"\n        if not self.monitor.is_shedding:\n            return True\n\n        priority = self._get_priority(event.event_type)\n        if priority \u003C self.shed_threshold:\n            return True  # High priority: always process\n\n        # Low priority during backpressure: defer\n        self._deferred.append(event)\n        logger.debug(\n            f\"Deferred event {event.event_type} \"\n            f\"(priority {priority}, depth \"\n            f\"{self.monitor.get_metrics()['queue_depth']})\"\n        )\n        return False\n\n    def _get_priority(self, event_type: str) -> int:\n        \"\"\"Get priority for an event type.\"\"\"\n        for pattern, priority in self.PRIORITY_MAP.items():\n            if pattern.endswith(\".*\"):\n                prefix = pattern[:-2]\n                if event_type.startswith(prefix + \".\"):\n                    return priority\n            elif pattern == event_type:\n                return priority\n        return 5  # Default: lowest priority\n\n    def get_deferred(self) -> List[Event]:\n        \"\"\"Return and clear deferred events for processing\n        when backpressure subsides.\"\"\"\n        events = self._deferred.copy()\n        self._deferred.clear()\n        return events\n```\n\n---\n\n## Chapter 8: Async Escrow Settlement\n\n### Event-Driven Escrow Lifecycle\n\nThe escrow is the financial backbone of agent commerce. Every escrow passes through a lifecycle: created, funded, conditions met (or breached), released (or disputed). In a synchronous model, the buyer polls `get_escrow_status` until the escrow transitions. In an event-driven model, the buyer subscribes to escrow lifecycle events and reacts to state changes as they occur.\n\n```\nEscrow Lifecycle Events\n========================\n\n  create_escrow\n       │\n       ▼\n  escrow.created ──────────────────────┐\n       │                                │\n       ▼                                │\n  escrow.funded                         │\n       │                                │\n  ┌────┴────┐                           │\n  │         │                           │\n  ▼         ▼                           ▼\nescrow.   escrow.                  escrow.expired\nconditions conditions              (timeout, no\n_met      _breached                 activity)\n  │         │\n  ▼         ▼\nescrow.   dispute.opened\nreleased       │\n               ▼\n          dispute.resolved\n               │\n          ┌────┴────┐\n          ▼         ▼\n     escrow.    escrow.\n     released   forfeited\n```\n\n### Webhook Handlers for Escrow State Changes\n\nFor the lowest latency notifications, register a webhook endpoint with GreenHelix. When an escrow state changes, GreenHelix sends an HTTP POST to your endpoint.\n\n```python\nfrom aiohttp import web\nimport hmac\n\n\nclass EscrowWebhookHandler:\n    \"\"\"HTTP server that receives GreenHelix webhook\n    notifications for escrow state changes.\n\n    Validates webhook signatures, deduplicates events,\n    and dispatches to registered handlers.\n    \"\"\"\n\n    def __init__(self, webhook_secret: str,\n                 event_bus: AsyncEventBus,\n                 deduplicator: EventDeduplicator):\n        self.webhook_secret = webhook_secret\n        self.event_bus = event_bus\n        self.dedup = deduplicator\n        self._handlers: Dict[str, EventHandler] = {}\n\n    def register_handler(self, escrow_state: str,\n                         handler: EventHandler) -> None:\n        \"\"\"Register a handler for an escrow state transition.\"\"\"\n        self._handlers[escrow_state] = handler\n\n    async def handle_webhook(self,\n                             request: web.Request) -> web.Response:\n        \"\"\"Process an incoming webhook from GreenHelix.\"\"\"\n        # Step 1: Verify signature\n        body = await request.read()\n        signature = request.headers.get(\n            \"X-GreenHelix-Signature\", \"\"\n        )\n        if not self._verify_signature(body, signature):\n            return web.Response(status=401, text=\"Invalid signature\")\n\n        # Step 2: Parse event\n        try:\n            data = json.loads(body)\n            event = Event.from_dict(data)\n        except (json.JSONDecodeError, KeyError) as e:\n            return web.Response(\n                status=400, text=f\"Invalid payload: {e}\"\n            )\n\n        # Step 3: Deduplicate\n        if self.dedup.is_duplicate(event.event_id):\n            # Return 200 to prevent GreenHelix from retrying\n            return web.Response(\n                status=200, text=\"Already processed\"\n            )\n\n        # Step 4: Dispatch to handler\n        escrow_state = event.payload.get(\"state\", \"\")\n        handler = self._handlers.get(escrow_state)\n\n        if handler:\n            try:\n                await handler(event)\n                self.dedup.mark_processed(event.event_id)\n                return web.Response(status=200, text=\"OK\")\n            except Exception as e:\n                logger.error(\n                    f\"Webhook handler failed: {e}\"\n                )\n                # Return 500 so GreenHelix retries\n                return web.Response(\n                    status=500,\n                    text=\"Processing failed\",\n                )\n        else:\n            # Unknown state -- accept but log\n            logger.warning(\n                f\"No handler for escrow state: {escrow_state}\"\n            )\n            self.dedup.mark_processed(event.event_id)\n            return web.Response(status=200, text=\"No handler\")\n\n    def _verify_signature(self, body: bytes,\n                          signature: str) -> bool:\n        \"\"\"Verify the webhook signature using HMAC-SHA256.\"\"\"\n        expected = hmac.new(\n            self.webhook_secret.encode(),\n            body,\n            hashlib.sha256,\n        ).hexdigest()\n        return hmac.compare_digest(expected, signature)\n\n    def create_app(self) -> web.Application:\n        \"\"\"Create an aiohttp web application for the webhook.\"\"\"\n        app = web.Application()\n        app.router.add_post(\n            \"\u002Fwebhooks\u002Fescrow\", self.handle_webhook\n        )\n        return app\n```\n\n### Automated Evaluation and Release\n\nThe most powerful application of async escrow settlement is automated evaluation. Instead of a buyer agent manually checking SLA status and deciding whether to release, an event handler monitors SLA events and releases escrow automatically when conditions are met.\n\n```python\nclass AsyncEscrowSettlement:\n    \"\"\"Automated escrow settlement driven by events.\n\n    Subscribes to SLA, delivery, and dispute events.\n    Automatically releases or disputes escrows based on\n    observed conditions.\n    \"\"\"\n\n    def __init__(self, session: aiohttp.ClientSession,\n                 base_url: str, agent_id: str,\n                 event_bus: AsyncEventBus):\n        self.session = session\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.event_bus = event_bus\n        self.keygen = IdempotencyKeyGenerator()\n\n        # Track active escrows and their conditions\n        self._escrows: Dict[str, dict] = {}\n\n        # Register event handlers\n        event_bus.subscribe(\n            \"escrow.created\", self._on_escrow_created\n        )\n        event_bus.subscribe(\n            \"sla.evaluation_complete\",\n            self._on_sla_evaluation_complete,\n        )\n        event_bus.subscribe(\n            \"delivery.confirmed\", self._on_delivery_confirmed\n        )\n        event_bus.subscribe(\n            \"escrow.expired\", self._on_escrow_expired\n        )\n\n    async def _on_escrow_created(self, event: Event) -> None:\n        \"\"\"Track a newly created escrow.\"\"\"\n        escrow_id = event.payload.get(\"escrow_id\")\n        self._escrows[escrow_id] = {\n            \"escrow_id\": escrow_id,\n            \"amount\": event.payload.get(\"amount\"),\n            \"counterparty_id\": event.payload.get(\n                \"counterparty_id\"\n            ),\n            \"conditions\": event.payload.get(\"conditions\", {}),\n            \"sla_met\": False,\n            \"delivery_confirmed\": False,\n            \"created_at\": event.timestamp,\n            \"correlation_id\": event.correlation_id,\n        }\n        logger.info(f\"Tracking escrow: {escrow_id}\")\n\n    async def _on_sla_evaluation_complete(\n        self, event: Event\n    ) -> None:\n        \"\"\"Handle SLA evaluation completion.\"\"\"\n        sla_id = event.payload.get(\"sla_id\")\n        escrow_id = event.payload.get(\"escrow_id\")\n        compliant = event.payload.get(\"compliant\", False)\n\n        if escrow_id not in self._escrows:\n            return\n\n        escrow = self._escrows[escrow_id]\n\n        if compliant:\n            escrow[\"sla_met\"] = True\n            logger.info(\n                f\"SLA met for escrow {escrow_id} \"\n                f\"(SLA: {sla_id})\"\n            )\n            await self._check_release_conditions(escrow_id)\n        else:\n            # SLA breached -- consider disputing\n            breach_data = event.payload.get(\"breach_data\", {})\n            await self._handle_sla_breach(\n                escrow_id, sla_id, breach_data\n            )\n\n    async def _on_delivery_confirmed(\n        self, event: Event\n    ) -> None:\n        \"\"\"Handle delivery confirmation.\"\"\"\n        escrow_id = event.payload.get(\"escrow_id\")\n        if escrow_id not in self._escrows:\n            return\n\n        self._escrows[escrow_id][\"delivery_confirmed\"] = True\n        logger.info(f\"Delivery confirmed for escrow {escrow_id}\")\n        await self._check_release_conditions(escrow_id)\n\n    async def _on_escrow_expired(self, event: Event) -> None:\n        \"\"\"Handle escrow expiration without settlement.\"\"\"\n        escrow_id = event.payload.get(\"escrow_id\")\n        if escrow_id in self._escrows:\n            logger.warning(f\"Escrow expired: {escrow_id}\")\n            del self._escrows[escrow_id]\n\n    async def _check_release_conditions(\n        self, escrow_id: str\n    ) -> None:\n        \"\"\"Check if all conditions are met to release\n        the escrow.\"\"\"\n        escrow = self._escrows.get(escrow_id)\n        if not escrow:\n            return\n\n        if escrow[\"sla_met\"] and escrow[\"delivery_confirmed\"]:\n            await self._release_escrow(escrow)\n\n    async def _release_escrow(self, escrow: dict) -> None:\n        \"\"\"Release escrow funds to the counterparty.\"\"\"\n        escrow_id = escrow[\"escrow_id\"]\n        counterparty_id = escrow[\"counterparty_id\"]\n\n        idempotency_key = self.keygen.for_event(\n            Event(\n                event_type=\"settlement\",\n                source_agent_id=self.agent_id,\n                event_id=f\"release-{escrow_id}\",\n                payload={},\n            ),\n            \"release_escrow\",\n        )\n\n        try:\n            result = await make_api_call(\n                self.session, self.base_url,\n                \"release_escrow\", {\n                    \"agent_id\": self.agent_id,\n                    \"escrow_id\": escrow_id,\n                    \"release_to\": counterparty_id,\n                    \"reason\": \"conditions_met\",\n                    \"idempotency_key\": idempotency_key,\n                },\n            )\n\n            await self.event_bus.publish(Event(\n                event_type=\"settlement.escrow_released\",\n                source_agent_id=self.agent_id,\n                correlation_id=escrow.get(\"correlation_id\", \"\"),\n                payload={\n                    \"escrow_id\": escrow_id,\n                    \"amount\": escrow[\"amount\"],\n                    \"released_to\": counterparty_id,\n                },\n            ))\n\n            # Record in ledger\n            await make_api_call(\n                self.session, self.base_url,\n                \"record_transaction\", {\n                    \"agent_id\": self.agent_id,\n                    \"transaction_type\": \"escrow_settlement\",\n                    \"amount\": str(escrow[\"amount\"]),\n                    \"currency\": \"USD\",\n                    \"counterparty_id\": counterparty_id,\n                    \"metadata\": json.dumps({\n                        \"escrow_id\": escrow_id,\n                        \"settlement_type\": \"automatic\",\n                        \"sla_compliant\": True,\n                        \"delivery_confirmed\": True,\n                    }),\n                },\n            )\n\n            logger.info(\n                f\"Escrow {escrow_id} released to \"\n                f\"{counterparty_id}: ${escrow['amount']}\"\n            )\n            del self._escrows[escrow_id]\n\n        except Exception as e:\n            logger.error(\n                f\"Failed to release escrow {escrow_id}: {e}\"\n            )\n            # The DLQ will handle retries\n\n    async def _handle_sla_breach(self, escrow_id: str,\n                                 sla_id: str,\n                                 breach_data: dict) -> None:\n        \"\"\"Handle an SLA breach by opening a dispute.\"\"\"\n        escrow = self._escrows.get(escrow_id)\n        if not escrow:\n            return\n\n        counterparty_id = escrow[\"counterparty_id\"]\n\n        result = await make_api_call(\n            self.session, self.base_url,\n            \"open_dispute\", {\n                \"agent_id\": self.agent_id,\n                \"counterparty_id\": counterparty_id,\n                \"dispute_type\": \"sla_breach\",\n                \"description\": json.dumps({\n                    \"escrow_id\": escrow_id,\n                    \"sla_id\": sla_id,\n                    \"breach_data\": breach_data,\n                }),\n            },\n        )\n\n        await self.event_bus.publish(Event(\n            event_type=\"settlement.dispute_opened\",\n            source_agent_id=self.agent_id,\n            correlation_id=escrow.get(\"correlation_id\", \"\"),\n            payload={\n                \"escrow_id\": escrow_id,\n                \"dispute_id\": result.get(\"dispute_id\"),\n                \"sla_id\": sla_id,\n            },\n        ))\n\n        logger.warning(\n            f\"Dispute opened for escrow {escrow_id}: \"\n            f\"{result.get('dispute_id')}\"\n        )\n\n    def get_active_escrows(self) -> dict:\n        \"\"\"Return summary of all active escrows being tracked.\"\"\"\n        return {\n            \"total\": len(self._escrows),\n            \"escrows\": [\n                {\n                    \"escrow_id\": e[\"escrow_id\"],\n                    \"amount\": e[\"amount\"],\n                    \"sla_met\": e[\"sla_met\"],\n                    \"delivery_confirmed\": e[\"delivery_confirmed\"],\n                    \"age_seconds\": (\n                        datetime.now(timezone.utc)\n                        - datetime.fromisoformat(\n                            e[\"created_at\"].replace(\n                                \"Z\", \"+00:00\"\n                            )\n                        )\n                    ).total_seconds(),\n                }\n                for e in self._escrows.values()\n            ],\n        }\n```\n\n---\n\n## Next Steps\n\nFor deployment patterns, monitoring, and production hardening, see the\n[Agent Production Hardening Guide](https:\u002F\u002Fclawhub.ai\u002Fskills\u002Fgreenhelix-agent-production-hardening).\n\n### Deployment Architecture\n\n```\nProduction Async Agent Commerce Architecture\n==============================================\n\nINBOUND                              OUTBOUND\n┌─────────────────────┐             ┌─────────────────────┐\n│  GreenHelix Webhooks │             │  GreenHelix API      │\n│  POST \u002Fwebhooks\u002F     │             │  the GreenHelix REST API    │\n│  escrow              │             │                      │\n└─────────┬───────────┘             └──────────┬──────────┘\n          │                                     ▲\n          ▼                                     │\n┌─────────────────────┐             ┌──────────┴──────────┐\n│  Webhook Handler     │             │  Rate Limiter        │\n│  ├─ Verify signature │             │  (token bucket)      │\n│  ├─ Deduplicate      │             └──────────┬──────────┘\n│  └─ Dispatch         │                        ▲\n└─────────┬───────────┘                        │\n          │                          ┌──────────┴──────────┐\n          ▼                          │  Outbox Publisher     │\n┌──────────────────────────────┐    │  (reliable delivery)  │\n│         AsyncEventBus         │    └──────────┬──────────┘\n│  ┌────────────────────────┐  │               ▲\n│  │  Subscription Manager   │  │               │\n│  │  Event Dispatcher       │  │    ┌──────────┴──────────┐\n│  │  Acknowledgment Tracker │  │    │  Saga Orchestrator    │\n│  └────────────────────────┘  │    │  ├─ Step execution     │\n│                               │    │  ├─ Compensation       │\n│  ┌────────────────────────┐  │    │  └─ State machine      │\n│  │  Backpressure Monitor   │  │    └──────────┬──────────┘\n│  │  ├─ Queue depth         │  │               ▲\n│  │  ├─ Load shedding       │  │               │\n│  │  └─ Priority routing    │  │    ┌──────────┴──────────┐\n│  └────────────────────────┘  │    │  Async Escrow         │\n│                               │    │  Settlement           │\n│  ┌────────────────────────┐  │    │  ├─ Condition tracker  │\n│  │  Dead Letter Queue      │  │    │  ├─ Auto-release      │\n│  │  ├─ Retry policies      │  │    │  └─ Dispute trigger   │\n│  │  ├─ Circuit breaker     │  │    └─────────────────────┘\n│  │  └─ Escalation          │  │\n│  └────────────────────────┘  │\n└──────────────────────────────┘\n```\n\n### Key Metrics for Production\n\n```\nAsync Commerce Agent Metrics\n==============================\n\nEVENT BUS\n──────────────────────────────────────────────────\nEvents received\u002Fsec          target \u003C 50\nEvents processed\u002Fsec         target >= receive rate\nQueue depth                  target \u003C 100\nAcknowledgment latency       target \u003C 500ms\n\nSAGAS\n──────────────────────────────────────────────────\nActive sagas                 monitor for growth\nSaga completion rate         target > 99%\nCompensation trigger rate    target \u003C 1%\nCompensation success rate    target > 99.9%\n\nDEAD LETTER QUEUE\n──────────────────────────────────────────────────\nDLQ depth                    target = 0\nEvents exhausted\u002Fday         target = 0\nCircuit breakers open        target = 0\n\nBACKPRESSURE\n──────────────────────────────────────────────────\nLoad shedding active         target: rarely\nEvents deferred\u002Fmin          monitor trend\nDeferred event age           target \u003C 60s\n\nESCROW SETTLEMENT\n──────────────────────────────────────────────────\nActive escrows tracked       monitor for leaks\nAuto-release success rate    target > 99%\nTime to settlement           monitor p95\nDisputes opened\u002Fday          monitor trend\n```\n\n---\n\n## What's Next\n\nThis guide covered the event-driven foundations: the bus, the patterns, the failure modes. From here, the natural extensions are:\n\n**Multi-agent choreography.** This guide focused on orchestration (a central coordinator drives the saga). Choreography is the alternative: each agent reacts to events independently, with no central coordinator. Choreography scales better but is harder to debug. Combine the `AsyncEventBus` with per-agent state machines for a choreographed approach.\n\n**Event sourcing.** Instead of storing the current state of an escrow or saga, store the complete sequence of events that produced that state. Replay the events to reconstruct state at any point in time. The `OutboxPublisher` is already halfway there -- extend it with a persistent event store and projection functions.\n\n**Cross-gateway federation.** When agents operate across multiple commerce gateways (not just GreenHelix), the event bus needs to bridge events between platforms. The `AsyncEventBus` can be extended with adapter plugins for different gateway APIs.\n\n**Observability.** Distributed tracing through correlation IDs (already present in the `Event` dataclass) gives you end-to-end visibility into saga execution across agents. Wire the correlation IDs into OpenTelemetry spans for production observability.\n\nThe synchronous request-response model is the training wheels of agent commerce. It works for simple cases. But the moment your agents start managing long-lived transactions, coordinating with multiple counterparties, or operating at scale, you need the patterns in this guide. The event bus is your nervous system. Sagas are your transaction coordinator. Dead letters are your safety net. Backpressure is your circuit breaker. And async escrow settlement is how you stop burning 518,400 API calls to learn about a single state change.\n\n",{"name":5,"tags":24,"type":29,"author":33,"install":34,"license":15,"version":35,"price_usd":36,"executable":20,"credentials":34,"description":7,"content_type":37,"compatibility":38},[25,26,27,28,29,30,31,32],"async","event-driven","saga","agent-commerce","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",39,"markdown",[31],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-async-agent-commerce",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-async-agent-commerce",{"tool":54,"command":55},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-async-agent-commerce",{"tool":57,"command":58},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-async-agent-commerce","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-async-agent-commerce\u002FSKILL.md",true,[],[63,70,77,84,91,98],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]