[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77H82GRGMVBJFCFDACN4HX0":3,"skill-same:01M77H82GRGMVBJFCFDACN4HX0":69},{"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":46,"commitSha":47,"skillDirectory":48,"forksCount":49,"repositoryHtmlUrl":50,"repositoryHomepageUrl":51,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M77H82GRGMVBJFCFDACN4HX0","greenhelix-agent-commerce-migration",null,"Agent Commerce Migration Guide: Retrofit Your REST APIs for Autonomous Agent Buyers. Step-by-step migration guide for teams with existing REST APIs that need to add agent commerce capabilities. Assessment framework, x402 retrofit patterns, authentication bridging, gradual migration strategies, testing, rollback procedures, and performance comparison.","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-agent-commerce-migration\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-commerce-migration\nversion: \"1.3.1\"\ndescription: \"Agent Commerce Migration Guide: Retrofit Your REST APIs for Autonomous Agent Buyers. Step-by-step migration guide for teams with existing REST APIs that need to add agent commerce capabilities. Assessment framework, x402 retrofit patterns, authentication bridging, gradual migration strategies, testing, rollback procedures, and performance comparison.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [migration, rest-api, retrofit, x402, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 39.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY, AGENT_SIGNING_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n        - AGENT_SIGNING_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# Agent Commerce Migration Guide: Retrofit Your REST APIs for Autonomous Agent Buyers\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code 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> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nYou have a working REST API. It serves human users through a web frontend. Maybe it powers a SaaS product, a data marketplace, or a specialized computation service. The endpoints are tested, the authentication works, and your customers are happy. Now AI agents want to buy your services programmatically. They don't want to fill out a signup form, navigate a dashboard, or read your documentation the way a human does. They want to discover your capabilities through structured metadata, negotiate a price via HTTP headers, pay per call with cryptographic proof, and consume your response — all in a single request cycle. The instinct is to build a separate \"agent API\" from scratch, but that is the wrong move. You already have the hard part: working business logic behind stable endpoints. What you need is a commerce layer on top of what exists. This guide shows how to retrofit any REST API with agent commerce capabilities: x402 payment headers for per-call pricing, GreenHelix escrow integration for trustless settlement, Ed25519 identity verification for agent authentication, and structured service discovery so agents can find and evaluate your offerings without human intervention. The approach is gradual. You can migrate one endpoint at a time while existing human users continue hitting the same URLs with the same authentication they have always used. No big bang rewrite. No downtime. No breaking changes. By the end of this guide you will have a complete migration framework — assessment tools, adapter classes, middleware patterns, validation harnesses, and rollback procedures — that transforms your existing REST API into an agent-ready commerce platform without sacrificing anything that already works.\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: Migration Assessment\n- Chapter 2: LegacyApiAdapter Class\n- Chapter 3: x402 Retrofit Patterns\n- Chapter 4: Authentication Bridging\n- Chapter 5: Gradual Migration Strategies\n- Chapter 6: MigrationValidator Class\n- Chapter 7: Testing Migration\n- Chapter 8: Performance Comparison\n- What's Next\n\n## Full Guide\n\n# Agent Commerce Migration Guide: Retrofit Your REST APIs for Autonomous Agent Buyers\n\nYou have a working REST API. It serves human users through a web frontend. Maybe it powers a SaaS product, a data marketplace, or a specialized computation service. The endpoints are tested, the authentication works, and your customers are happy. Now AI agents want to buy your services programmatically. They don't want to fill out a signup form, navigate a dashboard, or read your documentation the way a human does. They want to discover your capabilities through structured metadata, negotiate a price via HTTP headers, pay per call with cryptographic proof, and consume your response — all in a single request cycle. The instinct is to build a separate \"agent API\" from scratch, but that is the wrong move. You already have the hard part: working business logic behind stable endpoints. What you need is a commerce layer on top of what exists. This guide shows how to retrofit any REST API with agent commerce capabilities: x402 payment headers for per-call pricing, GreenHelix escrow integration for trustless settlement, Ed25519 identity verification for agent authentication, and structured service discovery so agents can find and evaluate your offerings without human intervention. The approach is gradual. You can migrate one endpoint at a time while existing human users continue hitting the same URLs with the same authentication they have always used. No big bang rewrite. No downtime. No breaking changes. By the end of this guide you will have a complete migration framework — assessment tools, adapter classes, middleware patterns, validation harnesses, and rollback procedures — that transforms your existing REST API into an agent-ready commerce platform without sacrificing anything that already works.\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## Chapter 1: Migration Assessment\n\nBefore writing any migration code, you need an honest evaluation of where your API stands today and what it will take to make it agent-commerce ready. This assessment phase saves weeks of wasted effort by identifying blockers early, surfacing hidden dependencies, and prioritizing the endpoints that will generate the most agent revenue with the least migration risk.\n\n### The Four Pillars of Agent Commerce Readiness\n\nEvery REST API migration touches four areas. Your current implementation might already satisfy some of them partially, but each one needs explicit attention.\n\n**Authentication readiness.** Agents do not use browser cookies or OAuth redirect flows. They present cryptographic identity — typically an Ed25519 public key with a signed request payload. Your API needs to verify these signatures alongside whatever auth mechanism already exists. The question is not whether you can replace your current auth, but whether you can layer agent auth on top of it.\n\n**Payment readiness.** Human users pay through subscriptions, invoices, or credit cards processed asynchronously. Agent commerce is synchronous: the agent includes a payment token in the request header, your API verifies it before processing, and settlement happens atomically. If your API currently has no concept of per-call pricing, you need to add one. If it already has usage-based billing, you have a head start.\n\n**Response structure readiness.** Human-facing APIs often return loosely structured JSON with messages meant for UI rendering — status strings like \"Success!\", nested error objects with display text, pagination metadata mixed into the response body. Agents need machine-parseable responses with predictable schemas, consistent error codes, and clear separation between data and metadata. The more disciplined your current response format, the less transformation work ahead.\n\n**Discovery readiness.** Agents find services through structured manifests — A2A protocol cards, OpenAPI specifications with pricing extensions, or capability registries. If your API has no machine-readable description of what it offers and what it costs, agents cannot evaluate it. Most REST APIs have some form of documentation, but rarely in a format an agent can consume autonomously.\n\n### The Assessment Checklist\n\nRun through this checklist for every endpoint you are considering for migration. Score each item 0 (not present), 1 (partially present), or 2 (fully present):\n\n```python\nMIGRATION_ASSESSMENT = {\n    \"authentication\": [\n        \"Stateless auth supported (tokens, not sessions)\",\n        \"Auth info passed via headers (not cookies)\",\n        \"Auth can be extended without breaking existing clients\",\n        \"Rate limiting is per-identity, not per-IP\",\n    ],\n    \"payments\": [\n        \"Usage tracking exists at per-call granularity\",\n        \"Pricing model defined for individual operations\",\n        \"Billing system can handle micropayments\",\n        \"Idempotency keys supported on payment-related endpoints\",\n    ],\n    \"response_structure\": [\n        \"Consistent JSON envelope across all endpoints\",\n        \"Error responses use numeric codes, not just strings\",\n        \"Pagination uses cursors, not page numbers\",\n        \"Response schemas are documented and stable\",\n    ],\n    \"discovery\": [\n        \"OpenAPI \u002F Swagger spec exists and is current\",\n        \"Endpoint capabilities described in machine-readable format\",\n        \"Versioning strategy is explicit (URL or header)\",\n        \"Health check endpoint exists\",\n    ],\n}\n\ndef score_api(scores: dict[str, list[int]]) -> dict:\n    results = {}\n    for category, items in scores.items():\n        total = sum(items)\n        max_score = len(MIGRATION_ASSESSMENT[category]) * 2\n        results[category] = {\n            \"score\": total,\n            \"max\": max_score,\n            \"percentage\": round(total \u002F max_score * 100),\n            \"ready\": total >= max_score * 0.75,\n        }\n    results[\"overall_ready\"] = all(r[\"ready\"] for r in results.values())\n    return results\n```\n\nAn overall score above 75% means you can proceed with migration directly. Between 50% and 75%, plan for prerequisite work on the weakest pillar before starting. Below 50%, consider whether the API needs structural improvements first — migration on top of a fragile foundation creates compounding problems.\n\n### The LegacyApiAdapter Pattern Overview\n\nThe core architectural pattern for this migration is the `LegacyApiAdapter`: a wrapper class that sits between incoming agent requests and your existing endpoint handlers. It performs three functions. First, it intercepts agent-specific headers (x402 payment tokens, Ed25519 signatures, capability queries) and processes them before the request reaches your business logic. Second, it transforms your existing response format into the agent-expected envelope if needed. Third, it passes through requests from non-agent clients completely unchanged, so your existing users never notice the migration happened.\n\nThis is not a proxy in the traditional sense. It runs in the same process as your existing API, adds no network hops, and shares the same database connections and caches. Think of it as a decorator pattern applied at the HTTP layer.\n\n### Identifying High-Value Migration Targets\n\nNot every endpoint is worth migrating. Start with endpoints that satisfy three criteria:\n\n**High agent utility.** Data retrieval endpoints (search, lookup, analytics) are the most immediately useful to agents. Agents are information consumers first. An endpoint that returns structured data an agent can act on is more valuable than a CRUD endpoint for managing user profiles.\n\n**Low migration complexity.** Endpoints with simple request\u002Fresponse schemas, no file uploads, no streaming responses, and no multi-step workflows are easiest to migrate. Save the complex ones for later phases.\n\n**Clear pricing model.** You need to assign a per-call price. Endpoints where the cost of serving a request is predictable (fixed computation, bounded database queries) are easier to price than endpoints with variable resource consumption. If you cannot state a price, you are not ready to migrate that endpoint.\n\nRank your endpoints by (utility x 1\u002Fcomplexity x pricing_clarity) and migrate the top five first. This gives you a working agent commerce surface quickly, generates early revenue, and builds confidence in the migration pattern before tackling harder endpoints.\n\n---\n\n## Chapter 2: LegacyApiAdapter Class\n\nThe `LegacyApiAdapter` is the central abstraction for this entire migration. It wraps your existing endpoint handlers and adds agent commerce capabilities without modifying the underlying business logic. Every request flows through the adapter, which decides whether to apply agent commerce processing or pass the request through unchanged.\n\n### Design Principles\n\nThe adapter follows three rules. First, zero regression: any request that worked before the adapter was installed must continue to work identically. Second, opt-in activation: agent commerce features activate only when the request contains agent-specific headers. Third, fail-open for humans: if agent commerce processing fails (payment verification timeout, identity service unavailable), non-agent requests still succeed. Agent requests fail explicitly with structured error responses.\n\n### The Complete Adapter Class\n\n```python\nimport time\nimport hashlib\nimport json\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import Any, Callable, Optional\nfrom functools import wraps\n\nimport httpx\nfrom fastapi import Request, Response, HTTPException\nfrom fastapi.responses import JSONResponse\n\n\nclass CallerType(str, Enum):\n    HUMAN = \"human\"\n    AGENT = \"agent\"\n    UNKNOWN = \"unknown\"\n\n\n@dataclass\nclass PricingConfig:\n    \"\"\"Per-endpoint pricing configuration.\"\"\"\n    price_usd: float\n    currency: str = \"USD\"\n    escrow_required: bool = True\n    min_deposit: float = 0.01\n    max_deposit: float = 100.00\n    settlement_timeout_seconds: int = 300\n\n\n@dataclass\nclass MigrationConfig:\n    \"\"\"Configuration for the adapter's behavior.\"\"\"\n    greenhelix_url: str = \"https:\u002F\u002Fapi.greenhelix.net\"\n    greenhelix_api_key: str = \"\"\n    verify_payments: bool = True\n    verify_identity: bool = True\n    transform_responses: bool = True\n    pass_through_on_failure: bool = False\n    pricing: dict[str, PricingConfig] = field(default_factory=dict)\n\n\n@dataclass\nclass AgentContext:\n    \"\"\"Extracted agent information from request headers.\"\"\"\n    caller_type: CallerType\n    agent_id: Optional[str] = None\n    payment_token: Optional[str] = None\n    signature: Optional[str] = None\n    public_key: Optional[str] = None\n    requested_capabilities: list[str] = field(default_factory=list)\n\n\nclass LegacyApiAdapter:\n    \"\"\"\n    Wraps existing REST API endpoints with agent commerce capabilities.\n\n    Intercepts agent-specific headers, verifies payments and identity,\n    transforms responses, and passes through non-agent requests unchanged.\n    \"\"\"\n\n    def __init__(self, config: MigrationConfig):\n        self.config = config\n        self._http_client = httpx.AsyncClient(\n            base_url=config.greenhelix_url,\n            timeout=10.0,\n        )\n        self._payment_cache: dict[str, float] = {}\n\n    def classify_caller(self, request: Request) -> AgentContext:\n        \"\"\"Determine whether the request comes from a human or an agent.\"\"\"\n        payment_token = request.headers.get(\"x-402-payment-token\")\n        agent_id = request.headers.get(\"x-agent-id\")\n        signature = request.headers.get(\"x-agent-signature\")\n        public_key = request.headers.get(\"x-agent-public-key\")\n\n        if payment_token or agent_id:\n            return AgentContext(\n                caller_type=CallerType.AGENT,\n                agent_id=agent_id,\n                payment_token=payment_token,\n                signature=signature,\n                public_key=public_key,\n            )\n\n        user_agent = request.headers.get(\"user-agent\", \"\")\n        agent_indicators = [\"bot\", \"agent\", \"crawler\", \"a2a-client\"]\n        if any(indicator in user_agent.lower() for indicator in agent_indicators):\n            return AgentContext(caller_type=CallerType.AGENT, agent_id=agent_id)\n\n        return AgentContext(caller_type=CallerType.HUMAN)\n\n    async def verify_payment(\n        self, payment_token: str, endpoint: str, price: PricingConfig\n    ) -> dict:\n        \"\"\"Verify a payment token against GreenHelix escrow.\"\"\"\n        response = await self._http_client.post(\n            \"\u002Fv1\u002Fpayments\u002Fverify\",\n            json={\n                \"token\": payment_token,\n                \"expected_amount\": str(price.price_usd),\n                \"currency\": price.currency,\n                \"endpoint\": endpoint,\n            },\n            headers={\"Authorization\": f\"Bearer {self.config.greenhelix_api_key}\"},\n        )\n\n        if response.status_code != 200:\n            return {\"valid\": False, \"error\": response.text}\n\n        result = response.json()\n        return {\n            \"valid\": result.get(\"verified\", False),\n            \"escrow_id\": result.get(\"escrow_id\"),\n            \"amount\": result.get(\"amount\"),\n        }\n\n    async def verify_identity(self, ctx: AgentContext) -> dict:\n        \"\"\"Verify agent identity via Ed25519 signature.\"\"\"\n        if not ctx.public_key or not ctx.signature:\n            return {\"verified\": False, \"error\": \"Missing signature or public key\"}\n\n        response = await self._http_client.post(\n            \"\u002Fv1\u002Fidentity\u002Fverify\",\n            json={\n                \"agent_id\": ctx.agent_id,\n                \"public_key\": ctx.public_key,\n                \"signature\": ctx.signature,\n            },\n            headers={\"Authorization\": f\"Bearer {self.config.greenhelix_api_key}\"},\n        )\n\n        if response.status_code != 200:\n            return {\"verified\": False, \"error\": response.text}\n\n        return response.json()\n\n    def transform_response(\n        self, response_data: Any, endpoint: str, escrow_id: Optional[str] = None\n    ) -> dict:\n        \"\"\"Transform legacy response format into agent-expected envelope.\"\"\"\n        return {\n            \"data\": response_data,\n            \"meta\": {\n                \"endpoint\": endpoint,\n                \"timestamp\": time.time(),\n                \"escrow_id\": escrow_id,\n                \"schema_version\": \"1.0\",\n            },\n        }\n\n    def wrap_endpoint(self, endpoint_path: str):\n        \"\"\"\n        Decorator that wraps an existing endpoint handler with agent commerce.\n\n        Usage:\n            adapter = LegacyApiAdapter(config)\n\n            @app.get(\"\u002Fapi\u002Fdata\")\n            @adapter.wrap_endpoint(\"\u002Fapi\u002Fdata\")\n            async def get_data(request: Request):\n                return {\"results\": [...]}\n        \"\"\"\n        def decorator(func: Callable):\n            @wraps(func)\n            async def wrapper(request: Request, *args, **kwargs):\n                ctx = self.classify_caller(request)\n\n                # Pass through non-agent requests unchanged\n                if ctx.caller_type == CallerType.HUMAN:\n                    return await func(request, *args, **kwargs)\n\n                # Agent request: verify payment if pricing is configured\n                pricing = self.config.pricing.get(endpoint_path)\n                escrow_id = None\n\n                if pricing and self.config.verify_payments:\n                    if not ctx.payment_token:\n                        return JSONResponse(\n                            status_code=402,\n                            content={\n                                \"error\": \"payment_required\",\n                                \"detail\": \"This endpoint requires payment\",\n                                \"price\": str(pricing.price_usd),\n                                \"currency\": pricing.currency,\n                                \"payment_url\": (\n                                    f\"{self.config.greenhelix_url}\"\n                                    f\"\u002Fv1\u002Fpayments\u002Fcreate\"\n                                ),\n                            },\n                            headers={\n                                \"X-Price\": str(pricing.price_usd),\n                                \"X-Currency\": pricing.currency,\n                                \"X-Payment-URL\": (\n                                    f\"{self.config.greenhelix_url}\"\n                                    f\"\u002Fv1\u002Fpayments\u002Fcreate\"\n                                ),\n                            },\n                        )\n\n                    payment_result = await self.verify_payment(\n                        ctx.payment_token, endpoint_path, pricing\n                    )\n                    if not payment_result[\"valid\"]:\n                        return JSONResponse(\n                            status_code=402,\n                            content={\n                                \"error\": \"payment_invalid\",\n                                \"detail\": payment_result.get(\"error\", \"Payment verification failed\"),\n                            },\n                        )\n                    escrow_id = payment_result.get(\"escrow_id\")\n\n                # Verify agent identity if configured\n                if self.config.verify_identity and ctx.agent_id:\n                    identity_result = await self.verify_identity(ctx)\n                    if not identity_result.get(\"verified\", False):\n                        return JSONResponse(\n                            status_code=403,\n                            content={\n                                \"error\": \"identity_verification_failed\",\n                                \"detail\": identity_result.get(\"error\", \"Could not verify agent identity\"),\n                            },\n                        )\n\n                # Execute the original handler\n                result = await func(request, *args, **kwargs)\n\n                # Transform response for agents if configured\n                if self.config.transform_responses:\n                    if isinstance(result, Response):\n                        # If the handler returned a Response object, extract the body\n                        body = json.loads(result.body) if hasattr(result, 'body') else result\n                        return JSONResponse(\n                            content=self.transform_response(body, endpoint_path, escrow_id),\n                            status_code=result.status_code if hasattr(result, 'status_code') else 200,\n                        )\n                    else:\n                        return JSONResponse(\n                            content=self.transform_response(result, endpoint_path, escrow_id),\n                        )\n\n                return result\n\n            return wrapper\n        return decorator\n\n    async def close(self):\n        \"\"\"Clean up HTTP client resources.\"\"\"\n        await self._http_client.aclose()\n```\n\n### How the Adapter Routes Requests\n\nThe `classify_caller` method is the decision point. It checks for the `x-402-payment-token` and `x-agent-id` headers first — these are definitive agent indicators. If those are absent, it falls back to user-agent string inspection as a heuristic. This two-tier classification means agents that follow the x402 protocol get full commerce support, while agents that merely identify via user-agent get classified but may still need to provide payment headers for paid endpoints.\n\nThe `wrap_endpoint` decorator is designed to be non-invasive. You add it to an existing route handler with a single line. The original function signature does not change. The original return value is preserved for human callers. Only agent callers see the transformed response envelope. This means you can add the decorator to every endpoint in your API and nothing changes for existing users — they continue to get exactly the same responses they always got.\n\n### Request and Response Transformation\n\nResponse transformation deserves attention because it is where most migration bugs appear. The adapter wraps the original response in a standardized envelope with `data` and `meta` fields. The `data` field contains exactly what the original endpoint returned. The `meta` field adds context that agents need: which endpoint served the response, when it was generated, and the escrow ID if a payment was involved. This separation means agents can always find the business data in `response[\"data\"]` and the transaction metadata in `response[\"meta\"]`, regardless of how different endpoints structure their responses internally.\n\nFor endpoints that return `Response` objects directly (common in FastAPI when you need to set custom status codes or headers), the adapter extracts the body, deserializes it, wraps it, and re-serializes. This adds negligible overhead — JSON parsing of a response that was going to be serialized anyway.\n\n---\n\n## Chapter 3: x402 Retrofit Patterns\n\nThe x402 protocol uses HTTP status code 402 (Payment Required) to signal that an endpoint requires payment before it will process the request. This status code has been reserved in the HTTP specification since 1997 but was rarely used until agent commerce gave it a concrete purpose. Retrofitting x402 onto existing endpoints means adding payment negotiation to the HTTP layer without modifying business logic.\n\n### The Payment Negotiation Flow\n\nWhen an agent hits a paid endpoint without a payment token, the flow works like this:\n\n1. Agent sends `GET \u002Fapi\u002Fv1\u002Fdata` with no payment headers.\n2. Server responds with `402 Payment Required`, including price and payment URL in headers.\n3. Agent creates a payment escrow via the payment URL.\n4. Agent retries `GET \u002Fapi\u002Fv1\u002Fdata` with the `X-402-Payment-Token` header.\n5. Server verifies the token, processes the request, and returns data.\n6. Settlement happens automatically after the response is delivered.\n\nThis is a two-request flow for the agent: one to discover the price, one to pay and consume. Agents that already know the price (from cached discovery or manifest data) can skip step 1 and go straight to step 4.\n\n### Payment Header Specification\n\nThe x402 headers used in negotiation:\n\n```\n# Response headers on 402:\nX-Price: 0.05\nX-Currency: USD\nX-Payment-URL: https:\u002F\u002Fapi.greenhelix.net\u002Fv1\u002Fpayments\u002Fcreate\nX-Payment-Methods: greenhelix-escrow, x402-direct\nX-Price-Window: 300  # price valid for 300 seconds\n\n# Request headers on paid request:\nX-402-Payment-Token: ght_abc123...\nX-Agent-Id: agent-buyer-001\nX-Idempotency-Key: req_unique_id_here\n```\n\n### FastAPI Middleware Implementation\n\nThe cleanest way to add x402 support across multiple endpoints in FastAPI is through middleware combined with a pricing registry:\n\n```python\nimport time\nfrom typing import Optional\n\nfrom fastapi import FastAPI, Request, Response\nfrom fastapi.responses import JSONResponse\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\nimport httpx\n\n\n# Pricing registry: maps endpoint patterns to prices\nENDPOINT_PRICING: dict[str, dict] = {\n    \"\u002Fapi\u002Fv1\u002Fsearch\": {\n        \"price_usd\": \"0.02\",\n        \"currency\": \"USD\",\n        \"settlement_timeout\": 300,\n    },\n    \"\u002Fapi\u002Fv1\u002Fanalyze\": {\n        \"price_usd\": \"0.10\",\n        \"currency\": \"USD\",\n        \"settlement_timeout\": 600,\n    },\n    \"\u002Fapi\u002Fv1\u002Fgenerate\": {\n        \"price_usd\": \"0.25\",\n        \"currency\": \"USD\",\n        \"settlement_timeout\": 600,\n    },\n}\n\nGREENHELIX_URL = \"https:\u002F\u002Fapi.greenhelix.net\"\nGREENHELIX_API_KEY = \"\"  # Set from environment\n\n\nclass X402PaymentMiddleware(BaseHTTPMiddleware):\n    \"\"\"\n    Middleware that enforces x402 payment on configured endpoints.\n\n    Non-agent requests pass through. Agent requests to priced\n    endpoints must include a valid payment token.\n    \"\"\"\n\n    def __init__(self, app: FastAPI, greenhelix_api_key: str):\n        super().__init__(app)\n        self.api_key = greenhelix_api_key\n        self._client = httpx.AsyncClient(\n            base_url=GREENHELIX_URL, timeout=10.0\n        )\n\n    async def dispatch(self, request: Request, call_next) -> Response:\n        # Check if this endpoint has pricing\n        pricing = self._match_pricing(request.url.path)\n        if pricing is None:\n            return await call_next(request)\n\n        # Check if this is an agent request\n        payment_token = request.headers.get(\"x-402-payment-token\")\n        agent_id = request.headers.get(\"x-agent-id\")\n\n        # No agent headers — pass through to existing handler\n        if not payment_token and not agent_id:\n            return await call_next(request)\n\n        # Agent request without payment token — return 402\n        if not payment_token:\n            return self._payment_required_response(request.url.path, pricing)\n\n        # Agent request with payment token — verify it\n        verification = await self._verify_token(payment_token, request.url.path, pricing)\n        if not verification[\"valid\"]:\n            return JSONResponse(\n                status_code=402,\n                content={\n                    \"error\": \"payment_invalid\",\n                    \"detail\": verification.get(\"error\", \"Token verification failed\"),\n                },\n            )\n\n        # Payment verified — attach escrow info and proceed\n        request.state.escrow_id = verification.get(\"escrow_id\")\n        request.state.payment_verified = True\n        response = await call_next(request)\n\n        # Add settlement headers to the response\n        response.headers[\"X-Escrow-Id\"] = verification.get(\"escrow_id\", \"\")\n        response.headers[\"X-Settlement-Status\"] = \"pending\"\n\n        return response\n\n    def _match_pricing(self, path: str) -> Optional[dict]:\n        \"\"\"Match request path to pricing config, supporting wildcards.\"\"\"\n        if path in ENDPOINT_PRICING:\n            return ENDPOINT_PRICING[path]\n        # Check prefix matches for versioned endpoints\n        for pattern, pricing in ENDPOINT_PRICING.items():\n            if path.startswith(pattern):\n                return pricing\n        return None\n\n    def _payment_required_response(self, path: str, pricing: dict) -> JSONResponse:\n        \"\"\"Build a 402 response with payment negotiation headers.\"\"\"\n        return JSONResponse(\n            status_code=402,\n            content={\n                \"error\": \"payment_required\",\n                \"endpoint\": path,\n                \"price\": pricing[\"price_usd\"],\n                \"currency\": pricing[\"currency\"],\n                \"payment_url\": f\"{GREENHELIX_URL}\u002Fv1\u002Fpayments\u002Fcreate\",\n                \"price_valid_seconds\": pricing.get(\"settlement_timeout\", 300),\n            },\n            headers={\n                \"X-Price\": pricing[\"price_usd\"],\n                \"X-Currency\": pricing[\"currency\"],\n                \"X-Payment-URL\": f\"{GREENHELIX_URL}\u002Fv1\u002Fpayments\u002Fcreate\",\n                \"X-Payment-Methods\": \"greenhelix-escrow\",\n                \"X-Price-Window\": str(pricing.get(\"settlement_timeout\", 300)),\n            },\n        )\n\n    async def _verify_token(\n        self, token: str, endpoint: str, pricing: dict\n    ) -> dict:\n        \"\"\"Verify payment token with GreenHelix.\"\"\"\n        try:\n            response = await self._client.post(\n                \"\u002Fv1\u002Fpayments\u002Fverify\",\n                json={\n                    \"token\": token,\n                    \"expected_amount\": pricing[\"price_usd\"],\n                    \"currency\": pricing[\"currency\"],\n                    \"endpoint\": endpoint,\n                },\n                headers={\"Authorization\": f\"Bearer {self.api_key}\"},\n            )\n            if response.status_code == 200:\n                return response.json()\n            return {\"valid\": False, \"error\": f\"Verification returned {response.status_code}\"}\n        except httpx.TimeoutException:\n            return {\"valid\": False, \"error\": \"Payment verification timed out\"}\n\n\n# Application setup\napp = FastAPI()\napp.add_middleware(X402PaymentMiddleware, greenhelix_api_key=GREENHELIX_API_KEY)\n```\n\n### Flask Middleware Equivalent\n\nFor Flask applications, the same pattern uses `before_request` and `after_request` hooks:\n\n```python\nimport time\nfrom flask import Flask, request, jsonify, g\nimport httpx\n\napp = Flask(__name__)\n\nENDPOINT_PRICING = {\n    \"\u002Fapi\u002Fv1\u002Fsearch\": {\"price_usd\": \"0.02\", \"currency\": \"USD\"},\n    \"\u002Fapi\u002Fv1\u002Fanalyze\": {\"price_usd\": \"0.10\", \"currency\": \"USD\"},\n}\n\nGREENHELIX_URL = \"https:\u002F\u002Fapi.greenhelix.net\"\nGREENHELIX_API_KEY = \"\"\n\n\n@app.before_request\ndef check_agent_payment():\n    \"\"\"Intercept agent requests and enforce payment.\"\"\"\n    pricing = ENDPOINT_PRICING.get(request.path)\n    if pricing is None:\n        return None  # No pricing — pass through\n\n    payment_token = request.headers.get(\"X-402-Payment-Token\")\n    agent_id = request.headers.get(\"X-Agent-Id\")\n\n    if not payment_token and not agent_id:\n        return None  # Not an agent — pass through\n\n    if not payment_token:\n        response = jsonify({\n            \"error\": \"payment_required\",\n            \"price\": pricing[\"price_usd\"],\n            \"currency\": pricing[\"currency\"],\n            \"payment_url\": f\"{GREENHELIX_URL}\u002Fv1\u002Fpayments\u002Fcreate\",\n        })\n        response.status_code = 402\n        response.headers[\"X-Price\"] = pricing[\"price_usd\"]\n        response.headers[\"X-Currency\"] = pricing[\"currency\"]\n        return response\n\n    # Verify payment synchronously (use async client in production)\n    with httpx.Client(base_url=GREENHELIX_URL, timeout=10.0) as client:\n        result = client.post(\n            \"\u002Fv1\u002Fpayments\u002Fverify\",\n            json={\n                \"token\": payment_token,\n                \"expected_amount\": pricing[\"price_usd\"],\n                \"endpoint\": request.path,\n            },\n            headers={\"Authorization\": f\"Bearer {GREENHELIX_API_KEY}\"},\n        )\n\n    if result.status_code != 200 or not result.json().get(\"verified\"):\n        return jsonify({\"error\": \"payment_invalid\"}), 402\n\n    g.escrow_id = result.json().get(\"escrow_id\")\n    g.payment_verified = True\n    return None\n\n\n@app.after_request\ndef add_settlement_headers(response):\n    \"\"\"Add escrow headers to responses for verified agent requests.\"\"\"\n    if hasattr(g, \"payment_verified\") and g.payment_verified:\n        response.headers[\"X-Escrow-Id\"] = getattr(g, \"escrow_id\", \"\")\n        response.headers[\"X-Settlement-Status\"] = \"pending\"\n    return response\n```\n\n### Django Middleware Equivalent\n\nDjango uses a class-based middleware approach:\n\n```python\nimport json\nimport httpx\nfrom django.http import JsonResponse\n\nENDPOINT_PRICING = {\n    \"\u002Fapi\u002Fv1\u002Fsearch\u002F\": {\"price_usd\": \"0.02\", \"currency\": \"USD\"},\n    \"\u002Fapi\u002Fv1\u002Fanalyze\u002F\": {\"price_usd\": \"0.10\", \"currency\": \"USD\"},\n}\n\nGREENHELIX_URL = \"https:\u002F\u002Fapi.greenhelix.net\"\nGREENHELIX_API_KEY = \"\"\n\n\nclass X402PaymentMiddleware:\n    def __init__(self, get_response):\n        self.get_response = get_response\n\n    def __call__(self, request):\n        pricing = ENDPOINT_PRICING.get(request.path)\n\n        if pricing is None:\n            return self.get_response(request)\n\n        payment_token = request.META.get(\"HTTP_X_402_PAYMENT_TOKEN\")\n        agent_id = request.META.get(\"HTTP_X_AGENT_ID\")\n\n        if not payment_token and not agent_id:\n            return self.get_response(request)\n\n        if not payment_token:\n            response = JsonResponse(\n                {\n                    \"error\": \"payment_required\",\n                    \"price\": pricing[\"price_usd\"],\n                    \"currency\": pricing[\"currency\"],\n                },\n                status=402,\n            )\n            response[\"X-Price\"] = pricing[\"price_usd\"]\n            response[\"X-Currency\"] = pricing[\"currency\"]\n            return response\n\n        # Verify payment token\n        with httpx.Client(base_url=GREENHELIX_URL, timeout=10.0) as client:\n            result = client.post(\n                \"\u002Fv1\u002Fpayments\u002Fverify\",\n                json={\n                    \"token\": payment_token,\n                    \"expected_amount\": pricing[\"price_usd\"],\n                    \"endpoint\": request.path,\n                },\n                headers={\"Authorization\": f\"Bearer {GREENHELIX_API_KEY}\"},\n            )\n\n        if result.status_code != 200:\n            return JsonResponse({\"error\": \"payment_invalid\"}, status=402)\n\n        data = result.json()\n        if not data.get(\"verified\"):\n            return JsonResponse({\"error\": \"payment_invalid\"}, status=402)\n\n        request.escrow_id = data.get(\"escrow_id\")\n        request.payment_verified = True\n\n        response = self.get_response(request)\n        response[\"X-Escrow-Id\"] = getattr(request, \"escrow_id\", \"\")\n        response[\"X-Settlement-Status\"] = \"pending\"\n        return response\n```\n\n### Token Verification Caching\n\nPayment verification adds a network round-trip to every agent request. For high-throughput endpoints, this is unacceptable. Implement a short-lived verification cache:\n\n```python\nimport hashlib\nimport time\nfrom typing import Optional\n\n\nclass PaymentVerificationCache:\n    \"\"\"Short-lived cache for payment verification results.\"\"\"\n\n    def __init__(self, ttl_seconds: int = 30):\n        self.ttl = ttl_seconds\n        self._cache: dict[str, tuple[float, dict]] = {}\n\n    def _key(self, token: str, endpoint: str) -> str:\n        return hashlib.sha256(f\"{token}:{endpoint}\".encode()).hexdigest()\n\n    def get(self, token: str, endpoint: str) -> Optional[dict]:\n        key = self._key(token, endpoint)\n        entry = self._cache.get(key)\n        if entry is None:\n            return None\n        timestamp, result = entry\n        if time.time() - timestamp > self.ttl:\n            del self._cache[key]\n            return None\n        return result\n\n    def set(self, token: str, endpoint: str, result: dict) -> None:\n        key = self._key(token, endpoint)\n        self._cache[key] = (time.time(), result)\n\n    def evict_expired(self) -> int:\n        \"\"\"Remove all expired entries. Returns count of evicted entries.\"\"\"\n        now = time.time()\n        expired = [k for k, (ts, _) in self._cache.items() if now - ts > self.ttl]\n        for k in expired:\n            del self._cache[k]\n        return len(expired)\n```\n\nThe cache TTL should be short — 30 seconds is usually sufficient. A payment token verified 30 seconds ago is still valid for the same endpoint. But do not cache across endpoints: a token valid for `\u002Fsearch` is not necessarily valid for `\u002Fanalyze` at a different price point.\n\n---\n\n## Chapter 4: Authentication Bridging\n\nMost REST APIs already have authentication. The migration challenge is not replacing that auth but running agent authentication alongside it. Agents authenticate differently from humans — they use cryptographic key pairs instead of passwords, sign requests instead of presenting session tokens, and identify themselves by public key hash instead of username. Authentication bridging lets both systems coexist.\n\n### The Dual-Auth Architecture\n\nThe bridging architecture has three layers:\n\n**Layer 1: Header inspection.** Every request is classified as human-auth, agent-auth, or unauthenticated based on which headers are present. Human requests carry `Authorization: Bearer \u003Cjwt>` or `X-API-Key`. Agent requests carry `X-Agent-Id`, `X-Agent-Public-Key`, and `X-Agent-Signature`.\n\n**Layer 2: Verification.** Human auth goes through your existing verification pipeline (JWT decode, API key lookup, OAuth token introspection). Agent auth goes through Ed25519 signature verification against the claimed public key, followed by identity resolution against GreenHelix.\n\n**Layer 3: Identity normalization.** Both paths produce a unified identity object that downstream handlers consume. The handler does not know or care whether the caller is human or agent — it gets the same interface.\n\n```python\nimport time\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom typing import Optional\n\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey\nfrom cryptography.hazmat.primitives.serialization import Encoding, PublicFormat\nfrom cryptography.exceptions import InvalidSignature\nimport base64\n\n\nclass AuthMethod(str, Enum):\n    JWT = \"jwt\"\n    API_KEY = \"api_key\"\n    AGENT_SIGNATURE = \"agent_signature\"\n    NONE = \"none\"\n\n\n@dataclass\nclass UnifiedIdentity:\n    \"\"\"Normalized identity produced by either auth path.\"\"\"\n    identity_id: str\n    display_name: str\n    auth_method: AuthMethod\n    is_agent: bool\n    permissions: list[str]\n    tier: str = \"free\"\n    metadata: dict = None\n\n    def __post_init__(self):\n        if self.metadata is None:\n            self.metadata = {}\n\n    def has_permission(self, permission: str) -> bool:\n        return permission in self.permissions or \"*\" in self.permissions\n\n\nclass AuthBridge:\n    \"\"\"\n    Bridges existing human auth with agent Ed25519 auth.\n    Produces a UnifiedIdentity regardless of auth method.\n    \"\"\"\n\n    def __init__(\n        self,\n        jwt_secret: str,\n        api_key_lookup: callable,\n        greenhelix_client: object,\n    ):\n        self.jwt_secret = jwt_secret\n        self.api_key_lookup = api_key_lookup\n        self.greenhelix = greenhelix_client\n\n    async def authenticate(self, request) -> UnifiedIdentity:\n        \"\"\"\n        Authenticate the request using whichever method is present.\n        Raises HTTPException on failure.\n        \"\"\"\n        # Check for agent auth first (more specific headers)\n        agent_id = request.headers.get(\"x-agent-id\")\n        agent_sig = request.headers.get(\"x-agent-signature\")\n        agent_pubkey = request.headers.get(\"x-agent-public-key\")\n\n        if agent_id and agent_sig and agent_pubkey:\n            return await self._authenticate_agent(\n                agent_id, agent_sig, agent_pubkey, request\n            )\n\n        # Check for JWT\n        auth_header = request.headers.get(\"authorization\", \"\")\n        if auth_header.startswith(\"Bearer \"):\n            token = auth_header[7:]\n            return self._authenticate_jwt(token)\n\n        # Check for API key\n        api_key = request.headers.get(\"x-api-key\")\n        if api_key:\n            return self._authenticate_api_key(api_key)\n\n        # No auth provided\n        return UnifiedIdentity(\n            identity_id=\"anonymous\",\n            display_name=\"Anonymous\",\n            auth_method=AuthMethod.NONE,\n            is_agent=False,\n            permissions=[\"read:public\"],\n            tier=\"free\",\n        )\n\n    async def _authenticate_agent(\n        self,\n        agent_id: str,\n        signature_b64: str,\n        public_key_b64: str,\n        request,\n    ) -> UnifiedIdentity:\n        \"\"\"Verify agent Ed25519 signature and resolve identity.\"\"\"\n        # Step 1: Reconstruct the signed payload\n        # The agent signs: METHOD + PATH + TIMESTAMP + BODY_HASH\n        timestamp = request.headers.get(\"x-agent-timestamp\", \"\")\n        body = await request.body()\n        body_hash = hashlib.sha256(body).hexdigest() if body else \"\"\n\n        signed_payload = (\n            f\"{request.method}:{request.url.path}:{timestamp}:{body_hash}\"\n        )\n\n        # Step 2: Verify the Ed25519 signature\n        try:\n            public_key_bytes = base64.b64decode(public_key_b64)\n            signature_bytes = base64.b64decode(signature_b64)\n\n            public_key = Ed25519PublicKey.from_public_key_der(public_key_bytes)\n            public_key.verify(signature_bytes, signed_payload.encode(\"utf-8\"))\n        except (InvalidSignature, ValueError, Exception) as exc:\n            raise HTTPException(\n                status_code=401,\n                detail={\n                    \"error\": \"signature_invalid\",\n                    \"message\": \"Ed25519 signature verification failed\",\n                },\n            )\n\n        # Step 3: Check timestamp freshness (prevent replay attacks)\n        try:\n            req_time = float(timestamp)\n            if abs(time.time() - req_time) > 300:  # 5-minute window\n                raise HTTPException(\n                    status_code=401,\n                    detail={\n                        \"error\": \"timestamp_expired\",\n                        \"message\": \"Request timestamp outside acceptable window\",\n                    },\n                )\n        except (ValueError, TypeError):\n            raise HTTPException(\n                status_code=401,\n                detail={\"error\": \"timestamp_invalid\", \"message\": \"Invalid timestamp format\"},\n            )\n\n        # Step 4: Resolve agent identity from GreenHelix\n        agent_info = await self.greenhelix.resolve_agent(agent_id, public_key_b64)\n\n        return UnifiedIdentity(\n            identity_id=agent_id,\n            display_name=agent_info.get(\"display_name\", agent_id),\n            auth_method=AuthMethod.AGENT_SIGNATURE,\n            is_agent=True,\n            permissions=agent_info.get(\"permissions\", [\"read:public\", \"execute:paid\"]),\n            tier=agent_info.get(\"tier\", \"standard\"),\n            metadata={\n                \"public_key\": public_key_b64,\n                \"reputation_score\": agent_info.get(\"reputation_score\", 0),\n                \"total_transactions\": agent_info.get(\"total_transactions\", 0),\n            },\n        )\n\n    def _authenticate_jwt(self, token: str) -> UnifiedIdentity:\n        \"\"\"Verify JWT and extract identity (existing auth path).\"\"\"\n        import jwt as pyjwt\n\n        try:\n            payload = pyjwt.decode(token, self.jwt_secret, algorithms=[\"HS256\"])\n        except pyjwt.ExpiredSignatureError:\n            raise HTTPException(status_code=401, detail={\"error\": \"token_expired\"})\n        except pyjwt.InvalidTokenError:\n            raise HTTPException(status_code=401, detail={\"error\": \"token_invalid\"})\n\n        return UnifiedIdentity(\n            identity_id=payload[\"sub\"],\n            display_name=payload.get(\"name\", \"\"),\n            auth_method=AuthMethod.JWT,\n            is_agent=False,\n            permissions=payload.get(\"permissions\", [\"read:public\"]),\n            tier=payload.get(\"tier\", \"free\"),\n        )\n\n    def _authenticate_api_key(self, api_key: str) -> UnifiedIdentity:\n        \"\"\"Verify API key and extract identity (existing auth path).\"\"\"\n        key_data = self.api_key_lookup(api_key)\n        if key_data is None:\n            raise HTTPException(status_code=401, detail={\"error\": \"api_key_invalid\"})\n\n        return UnifiedIdentity(\n            identity_id=key_data[\"user_id\"],\n            display_name=key_data.get(\"name\", \"\"),\n            auth_method=AuthMethod.API_KEY,\n            is_agent=False,\n            permissions=key_data.get(\"permissions\", [\"read:public\"]),\n            tier=key_data.get(\"tier\", \"free\"),\n        )\n```\n\n### Using the AuthBridge in FastAPI\n\nIntegrate the bridge as a dependency that replaces your existing auth dependency:\n\n```python\nfrom fastapi import Depends, FastAPI, Request\n\napp = FastAPI()\n\n# Initialize the bridge once at startup\nauth_bridge = AuthBridge(\n    jwt_secret=\"your-jwt-secret\",\n    api_key_lookup=lambda key: db.lookup_api_key(key),\n    greenhelix_client=greenhelix_client,\n)\n\n\nasync def get_identity(request: Request) -> UnifiedIdentity:\n    \"\"\"FastAPI dependency that authenticates via the bridge.\"\"\"\n    return await auth_bridge.authenticate(request)\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fdata\")\nasync def get_data(identity: UnifiedIdentity = Depends(get_identity)):\n    # identity.is_agent tells you the caller type\n    # identity.permissions controls access\n    # identity.tier determines rate limits\n    if not identity.has_permission(\"read:data\"):\n        raise HTTPException(status_code=403, detail=\"Insufficient permissions\")\n\n    return {\"results\": [...], \"caller\": identity.identity_id}\n```\n\n### Session Management for Agents\n\nHuman sessions rely on cookies and server-side state. Agent sessions are stateless by design — each request is independently authenticated. But some APIs have multi-step workflows (start a job, poll for status, download results) that require session continuity. For agents, implement session continuity through idempotency keys and request correlation:\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nimport time\nimport uuid\n\n\n@dataclass\nclass AgentSession:\n    \"\"\"Lightweight session for multi-step agent workflows.\"\"\"\n    session_id: str\n    agent_id: str\n    created_at: float\n    last_activity: float\n    workflow_state: dict = field(default_factory=dict)\n    ttl_seconds: int = 3600\n\n\nclass AgentSessionStore:\n    \"\"\"In-memory session store for agent workflows.\"\"\"\n\n    def __init__(self):\n        self._sessions: dict[str, AgentSession] = {}\n\n    def create(self, agent_id: str) -> AgentSession:\n        session = AgentSession(\n            session_id=str(uuid.uuid4()),\n            agent_id=agent_id,\n            created_at=time.time(),\n            last_activity=time.time(),\n        )\n        self._sessions[session.session_id] = session\n        return session\n\n    def get(self, session_id: str, agent_id: str) -> Optional[AgentSession]:\n        session = self._sessions.get(session_id)\n        if session is None:\n            return None\n        if session.agent_id != agent_id:\n            return None  # Session belongs to a different agent\n        if time.time() - session.last_activity > session.ttl_seconds:\n            del self._sessions[session_id]\n            return None\n        session.last_activity = time.time()\n        return session\n\n    def update_state(self, session_id: str, key: str, value: object) -> None:\n        session = self._sessions.get(session_id)\n        if session:\n            session.workflow_state[key] = value\n            session.last_activity = time.time()\n\n    def cleanup_expired(self) -> int:\n        now = time.time()\n        expired = [\n            sid for sid, s in self._sessions.items()\n            if now - s.last_activity > s.ttl_seconds\n        ]\n        for sid in expired:\n            del self._sessions[sid]\n        return len(expired)\n```\n\nAgents include `X-Session-Id` on follow-up requests. The session ID is returned in the response to the first request in a workflow. This is optional — agents that perform only single-call operations never need sessions.\n\n---\n\n## Chapter 5: Gradual Migration Strategies\n\nBig-bang migrations fail. You do not flip a switch and convert your entire API to agent commerce overnight. Instead, you migrate one endpoint at a time, verify it works, and move to the next. This chapter covers the practical strategies for incremental migration without disrupting existing traffic.\n\n### Endpoint-by-Endpoint Migration\n\nThe migration order matters. Start with read-only endpoints (GET requests), then move to write endpoints (POST\u002FPUT), and finish with complex workflows (multi-step operations). Each endpoint goes through four stages:\n\n```python\nfrom enum import Enum\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n\nclass MigrationStage(str, Enum):\n    LEGACY = \"legacy\"           # No agent support\n    DISCOVERY = \"discovery\"     # Returns 402 with pricing, but doesn't process payments\n    PAYMENT = \"payment\"         # Accepts and verifies payments\n    FULL = \"full\"               # Full agent commerce: payment + identity + response transform\n\n\n@dataclass\nclass EndpointMigrationState:\n    path: str\n    stage: MigrationStage\n    migrated_at: Optional[float] = None\n    migration_notes: str = \"\"\n\n\nclass MigrationRegistry:\n    \"\"\"Tracks which endpoints are at which migration stage.\"\"\"\n\n    def __init__(self):\n        self._endpoints: dict[str, EndpointMigrationState] = {}\n\n    def register(self, path: str, stage: MigrationStage, notes: str = \"\") -> None:\n        self._endpoints[path] = EndpointMigrationState(\n            path=path,\n            stage=stage,\n            migrated_at=time.time() if stage != MigrationStage.LEGACY else None,\n            migration_notes=notes,\n        )\n\n    def get_stage(self, path: str) -> MigrationStage:\n        state = self._endpoints.get(path)\n        return state.stage if state else MigrationStage.LEGACY\n\n    def advance(self, path: str) -> MigrationStage:\n        \"\"\"Move an endpoint to the next migration stage.\"\"\"\n        current = self.get_stage(path)\n        stages = list(MigrationStage)\n        current_index = stages.index(current)\n        if current_index \u003C len(stages) - 1:\n            new_stage = stages[current_index + 1]\n            self.register(path, new_stage)\n            return new_stage\n        return current\n\n    def summary(self) -> dict[str, int]:\n        counts = {stage.value: 0 for stage in MigrationStage}\n        for state in self._endpoints.values():\n            counts[state.stage.value] += 1\n        return counts\n\n\n# Usage\nregistry = MigrationRegistry()\nregistry.register(\"\u002Fapi\u002Fv1\u002Fsearch\", MigrationStage.FULL)\nregistry.register(\"\u002Fapi\u002Fv1\u002Fanalyze\", MigrationStage.PAYMENT)\nregistry.register(\"\u002Fapi\u002Fv1\u002Fusers\", MigrationStage.LEGACY)\n\nprint(registry.summary())\n# {'legacy': 1, 'discovery': 0, 'payment': 1, 'full': 1}\n```\n\nThe discovery stage is critical and often skipped. At this stage, the endpoint returns 402 with correct pricing headers when an agent hits it, but does not actually process payments. This lets agents discover your pricing and capabilities without you needing to handle real money yet. Run in discovery mode for at least a week to see what agents query your API, what prices they encounter, and how they react.\n\n### Feature Flags for Agent Commerce\n\nFeature flags let you enable and disable agent commerce per endpoint, per agent, or globally without deploying new code:\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nimport json\nimport os\n\n\n@dataclass\nclass AgentCommerceFlags:\n    \"\"\"Feature flags controlling agent commerce behavior.\"\"\"\n    global_enabled: bool = True\n    payment_required: bool = True\n    identity_verification: bool = True\n    response_transformation: bool = True\n    allowed_agent_ids: list[str] = field(default_factory=list)  # Empty = allow all\n    blocked_agent_ids: list[str] = field(default_factory=list)\n    endpoint_overrides: dict[str, dict] = field(default_factory=dict)\n\n    @classmethod\n    def from_env(cls) -> \"AgentCommerceFlags\":\n        \"\"\"Load flags from environment variables or config file.\"\"\"\n        config_path = os.getenv(\"AGENT_COMMERCE_CONFIG\", \"agent_commerce_flags.json\")\n        if os.path.exists(config_path):\n            with open(config_path) as f:\n                data = json.load(f)\n            return cls(**data)\n        return cls(\n            global_enabled=os.getenv(\"AGENT_COMMERCE_ENABLED\", \"true\").lower() == \"true\",\n            payment_required=os.getenv(\"AGENT_PAYMENT_REQUIRED\", \"true\").lower() == \"true\",\n        )\n\n    def is_enabled_for(self, endpoint: str, agent_id: Optional[str] = None) -> bool:\n        \"\"\"Check if agent commerce is enabled for a specific endpoint and agent.\"\"\"\n        if not self.global_enabled:\n            return False\n\n        if agent_id and agent_id in self.blocked_agent_ids:\n            return False\n\n        if self.allowed_agent_ids and agent_id not in self.allowed_agent_ids:\n            return False\n\n        override = self.endpoint_overrides.get(endpoint, {})\n        return override.get(\"enabled\", True)\n\n    def get_price_override(self, endpoint: str) -> Optional[str]:\n        \"\"\"Get endpoint-specific price override, if any.\"\"\"\n        override = self.endpoint_overrides.get(endpoint, {})\n        return override.get(\"price_usd\")\n```\n\n### Traffic Routing with Reverse Proxy\n\nFor APIs running behind nginx or a similar reverse proxy, you can route agent traffic to a separate upstream that has the commerce middleware enabled, while human traffic hits the original upstream unchanged:\n\n```nginx\n# nginx.conf — agent traffic routing\n\nupstream legacy_api {\n    server 127.0.0.1:8000;\n}\n\nupstream agent_commerce_api {\n    server 127.0.0.1:8001;\n}\n\nmap $http_x_agent_id $is_agent {\n    default 0;\n    \"~.+\" 1;\n}\n\nmap $http_x_402_payment_token $has_payment {\n    default 0;\n    \"~.+\" 1;\n}\n\nserver {\n    listen 443 ssl;\n    server_name api.example.com;\n\n    location \u002Fapi\u002Fv1\u002F {\n        # Route to agent commerce API if agent headers are present\n        if ($is_agent) {\n            proxy_pass http:\u002F\u002Fagent_commerce_api;\n            break;\n        }\n        if ($has_payment) {\n            proxy_pass http:\u002F\u002Fagent_commerce_api;\n            break;\n        }\n\n        # Default: route to legacy API\n        proxy_pass http:\u002F\u002Flegacy_api;\n    }\n}\n```\n\nThis approach lets you run the agent commerce version of your API as a separate process. The legacy API process remains completely untouched. If anything goes wrong with agent commerce, you adjust the nginx config to route all traffic back to the legacy upstream. Zero-downtime rollback.\n\n### A\u002FB Testing Human vs Agent Traffic\n\nTrack metrics separately for human and agent callers to detect regressions:\n\n```python\nimport time\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\n\n\n@dataclass\nclass TrafficMetrics:\n    request_count: int = 0\n    error_count: int = 0\n    total_latency_ms: float = 0.0\n    p95_latencies: list[float] = field(default_factory=list)\n\n    @property\n    def avg_latency_ms(self) -> float:\n        if self.request_count == 0:\n            return 0.0\n        return self.total_latency_ms \u002F self.request_count\n\n    @property\n    def error_rate(self) -> float:\n        if self.request_count == 0:\n            return 0.0\n        return self.error_count \u002F self.request_count\n\n\nclass MigrationMetricsCollector:\n    \"\"\"Collects metrics split by caller type for migration monitoring.\"\"\"\n\n    def __init__(self):\n        self._metrics: dict[str, dict[str, TrafficMetrics]] = defaultdict(\n            lambda: {\"human\": TrafficMetrics(), \"agent\": TrafficMetrics()}\n        )\n\n    def record(\n        self,\n        endpoint: str,\n        caller_type: str,\n        latency_ms: float,\n        is_error: bool = False,\n    ) -> None:\n        metrics = self._metrics[endpoint][caller_type]\n        metrics.request_count += 1\n        metrics.total_latency_ms += latency_ms\n        metrics.p95_latencies.append(latency_ms)\n        if is_error:\n            metrics.error_count += 1\n\n        # Keep only last 1000 latencies for p95 calculation\n        if len(metrics.p95_latencies) > 1000:\n            metrics.p95_latencies = metrics.p95_latencies[-1000:]\n\n    def compare(self, endpoint: str) -> dict:\n        \"\"\"Compare human vs agent metrics for an endpoint.\"\"\"\n        human = self._metrics[endpoint][\"human\"]\n        agent = self._metrics[endpoint][\"agent\"]\n        return {\n            \"endpoint\": endpoint,\n            \"human\": {\n                \"requests\": human.request_count,\n                \"avg_latency_ms\": round(human.avg_latency_ms, 2),\n                \"error_rate\": round(human.error_rate, 4),\n            },\n            \"agent\": {\n                \"requests\": agent.request_count,\n                \"avg_latency_ms\": round(agent.avg_latency_ms, 2),\n                \"error_rate\": round(agent.error_rate, 4),\n            },\n            \"latency_delta_ms\": round(agent.avg_latency_ms - human.avg_latency_ms, 2),\n        }\n```\n\nThe `latency_delta_ms` is the key metric during migration. If agent requests are significantly slower than human requests at the same endpoint, the commerce middleware is adding too much overhead. The target is under 50ms of additional latency for the payment verification and response transformation layer.\n\n---\n\n## Chapter 6: MigrationValidator Class\n\nMigration validation answers one question: does the migrated endpoint behave identically to the original for all non-commerce concerns? The business logic should produce the same output, the response schemas should be compatible, and performance should not degrade beyond acceptable bounds. The `MigrationValidator` automates these checks.\n\n### The Validator Architecture\n\nThe validator works by sending the same request to both the legacy endpoint and the migrated endpoint, then comparing the responses. For endpoints that have already replaced the legacy version (same URL, new middleware), it compares captured legacy response snapshots against live migrated responses.\n\n```python\nimport json\nimport time\nimport hashlib\nfrom dataclasses import dataclass, field\nfrom typing import Any, Optional\nfrom enum import Enum\n\nimport httpx\n\n\nclass ValidationResult(str, Enum):\n    PASS = \"pass\"\n    FAIL = \"fail\"\n    WARN = \"warn\"\n\n\n@dataclass\nclass ValidationReport:\n    endpoint: str\n    result: ValidationResult\n    checks: list[dict] = field(default_factory=list)\n    duration_ms: float = 0.0\n    timestamp: float = field(default_factory=time.time)\n\n    def add_check(self, name: str, result: ValidationResult, detail: str = \"\") -> None:\n        self.checks.append({\n            \"name\": name,\n            \"result\": result.value,\n            \"detail\": detail,\n        })\n        # Overall result is the worst individual result\n        if result == ValidationResult.FAIL:\n            self.result = ValidationResult.FAIL\n        elif result == ValidationResult.WARN and self.result != ValidationResult.FAIL:\n            self.result = ValidationResult.WARN\n\n    @property\n    def passed(self) -> bool:\n        return self.result != ValidationResult.FAIL\n\n    def summary(self) -> str:\n        total = len(self.checks)\n        passed = sum(1 for c in self.checks if c[\"result\"] == \"pass\")\n        return f\"{self.endpoint}: {passed}\u002F{total} checks passed ({self.result.value})\"\n\n\n@dataclass\nclass ResponseSnapshot:\n    \"\"\"Captured response for comparison.\"\"\"\n    status_code: int\n    headers: dict[str, str]\n    body: Any\n    latency_ms: float\n    captured_at: float = field(default_factory=time.time)\n\n    def body_hash(self) -> str:\n        return hashlib.sha256(json.dumps(self.body, sort_keys=True).encode()).hexdigest()\n\n\nclass MigrationValidator:\n    \"\"\"\n    Validates that migrated endpoints preserve original behavior.\n\n    Compares response schemas, status codes, data content, and\n    performance between legacy and migrated versions.\n    \"\"\"\n\n    def __init__(\n        self,\n        legacy_base_url: str,\n        migrated_base_url: str,\n        tolerance_ms: float = 100.0,\n        schema_strict: bool = False,\n    ):\n        self.legacy_url = legacy_base_url.rstrip(\"\u002F\")\n        self.migrated_url = migrated_base_url.rstrip(\"\u002F\")\n        self.tolerance_ms = tolerance_ms\n        self.schema_strict = schema_strict\n        self._client = httpx.AsyncClient(timeout=30.0)\n        self._snapshots: dict[str, list[ResponseSnapshot]] = {}\n\n    async def capture_legacy_snapshot(\n        self, endpoint: str, method: str = \"GET\", body: Any = None, headers: dict = None,\n    ) -> ResponseSnapshot:\n        \"\"\"Capture a response from the legacy endpoint for later comparison.\"\"\"\n        request_headers = headers or {}\n        start = time.time()\n\n        if method.upper() == \"GET\":\n            response = await self._client.get(\n                f\"{self.legacy_url}{endpoint}\", headers=request_headers\n            )\n        else:\n            response = await self._client.request(\n                method, f\"{self.legacy_url}{endpoint}\",\n                json=body, headers=request_headers,\n            )\n\n        latency_ms = (time.time() - start) * 1000\n\n        snapshot = ResponseSnapshot(\n            status_code=response.status_code,\n            headers=dict(response.headers),\n            body=response.json() if response.headers.get(\"content-type\", \"\").startswith(\"application\u002Fjson\") else response.text,\n            latency_ms=latency_ms,\n        )\n\n        if endpoint not in self._snapshots:\n            self._snapshots[endpoint] = []\n        self._snapshots[endpoint].append(snapshot)\n\n        return snapshot\n\n    async def validate_endpoint(\n        self,\n        endpoint: str,\n        method: str = \"GET\",\n        body: Any = None,\n        human_headers: dict = None,\n        agent_headers: dict = None,\n    ) -> ValidationReport:\n        \"\"\"Run full validation suite on a migrated endpoint.\"\"\"\n        report = ValidationReport(endpoint=endpoint, result=ValidationResult.PASS)\n        start = time.time()\n\n        # Test 1: Human request produces same response as legacy\n        human_headers = human_headers or {}\n        try:\n            legacy_resp = await self._request(self.legacy_url, endpoint, method, body, human_headers)\n            migrated_resp = await self._request(self.migrated_url, endpoint, method, body, human_headers)\n\n            self._check_status_code(report, legacy_resp, migrated_resp)\n            self._check_schema_compatibility(report, legacy_resp, migrated_resp)\n            self._check_data_equivalence(report, legacy_resp, migrated_resp)\n        except httpx.RequestError as exc:\n            report.add_check(\"connectivity\", ValidationResult.FAIL, str(exc))\n            report.duration_ms = (time.time() - start) * 1000\n            return report\n\n        # Test 2: Agent request without payment returns 402\n        if agent_headers:\n            agent_no_payment = {k: v for k, v in agent_headers.items() if k.lower() != \"x-402-payment-token\"}\n            try:\n                agent_resp = await self._request(\n                    self.migrated_url, endpoint, method, body, agent_no_payment\n                )\n                if agent_resp.status_code == 402:\n                    report.add_check(\"402_response\", ValidationResult.PASS, \"Returns 402 for unpaid agent requests\")\n                    self._check_402_headers(report, agent_resp)\n                else:\n                    report.add_check(\n                        \"402_response\", ValidationResult.WARN,\n                        f\"Expected 402, got {agent_resp.status_code}\",\n                    )\n            except httpx.RequestError as exc:\n                report.add_check(\"agent_request\", ValidationResult.FAIL, str(exc))\n\n        # Test 3: Performance regression check\n        await self._check_performance(report, endpoint, method, body, human_headers)\n\n        report.duration_ms = (time.time() - start) * 1000\n        return report\n\n    async def _request(\n        self, base_url: str, endpoint: str, method: str, body: Any, headers: dict,\n    ) -> httpx.Response:\n        if method.upper() == \"GET\":\n            return await self._client.get(f\"{base_url}{endpoint}\", headers=headers)\n        return await self._client.request(\n            method, f\"{base_url}{endpoint}\", json=body, headers=headers\n        )\n\n    def _check_status_code(\n        self, report: ValidationReport, legacy: httpx.Response, migrated: httpx.Response,\n    ) -> None:\n        if legacy.status_code == migrated.status_code:\n            report.add_check(\"status_code\", ValidationResult.PASS)\n        else:\n            report.add_check(\n                \"status_code\", ValidationResult.FAIL,\n                f\"Legacy returned {legacy.status_code}, migrated returned {migrated.status_code}\",\n            )\n\n    def _check_schema_compatibility(\n        self, report: ValidationReport, legacy: httpx.Response, migrated: httpx.Response,\n    ) -> None:\n        \"\"\"Compare response structure (keys at each level).\"\"\"\n        try:\n            legacy_body = legacy.json()\n            migrated_body = migrated.json()\n        except (json.JSONDecodeError, ValueError):\n            report.add_check(\"schema\", ValidationResult.WARN, \"Could not parse response as JSON\")\n            return\n\n        legacy_keys = self._extract_keys(legacy_body)\n        migrated_keys = self._extract_keys(migrated_body)\n\n        missing = legacy_keys - migrated_keys\n        added = migrated_keys - legacy_keys\n\n        if not missing and not added:\n            report.add_check(\"schema\", ValidationResult.PASS)\n        elif missing:\n            report.add_check(\n                \"schema\", ValidationResult.FAIL,\n                f\"Missing keys in migrated response: {missing}\",\n            )\n        elif added and self.schema_strict:\n            report.add_check(\n                \"schema\", ValidationResult.FAIL,\n                f\"Unexpected keys in migrated response: {added}\",\n            )\n        else:\n            report.add_check(\n                \"schema\", ValidationResult.WARN,\n                f\"New keys in migrated response: {added}\",\n            )\n\n    def _check_data_equivalence(\n        self, report: ValidationReport, legacy: httpx.Response, migrated: httpx.Response,\n    ) -> None:\n        \"\"\"Check that the actual data values match.\"\"\"\n        try:\n            legacy_body = legacy.json()\n            migrated_body = migrated.json()\n        except (json.JSONDecodeError, ValueError):\n            return\n\n        # If migrated response wraps data in an envelope, unwrap it\n        if isinstance(migrated_body, dict) and \"data\" in migrated_body and \"meta\" in migrated_body:\n            migrated_body = migrated_body[\"data\"]\n\n        legacy_hash = hashlib.sha256(json.dumps(legacy_body, sort_keys=True).encode()).hexdigest()\n        migrated_hash = hashlib.sha256(json.dumps(migrated_body, sort_keys=True).encode()).hexdigest()\n\n        if legacy_hash == migrated_hash:\n            report.add_check(\"data_equivalence\", ValidationResult.PASS)\n        else:\n            report.add_check(\n                \"data_equivalence\", ValidationResult.WARN,\n                \"Response data differs (may be expected for dynamic fields like timestamps)\",\n            )\n\n    def _check_402_headers(self, report: ValidationReport, response: httpx.Response) -> None:\n        \"\"\"Verify that 402 responses include required negotiation headers.\"\"\"\n        required_headers = [\"x-price\", \"x-currency\", \"x-payment-url\"]\n        missing = [h for h in required_headers if h not in response.headers]\n\n        if not missing:\n            report.add_check(\"402_headers\", ValidationResult.PASS)\n        else:\n            report.add_check(\n                \"402_headers\", ValidationResult.FAIL,\n                f\"Missing 402 headers: {missing}\",\n            )\n\n    async def _check_performance(\n        self, report: ValidationReport, endpoint: str, method: str, body: Any, headers: dict,\n    ) -> None:\n        \"\"\"Check that migration hasn't introduced unacceptable latency.\"\"\"\n        # Run 5 requests against each and compare average\n        legacy_latencies = []\n        migrated_latencies = []\n\n        for _ in range(5):\n            start = time.time()\n            await self._request(self.legacy_url, endpoint, method, body, headers)\n            legacy_latencies.append((time.time() - start) * 1000)\n\n            start = time.time()\n            await self._request(self.migrated_url, endpoint, method, body, headers)\n            migrated_latencies.append((time.time() - start) * 1000)\n\n        avg_legacy = sum(legacy_latencies) \u002F len(legacy_latencies)\n        avg_migrated = sum(migrated_latencies) \u002F len(migrated_latencies)\n        delta = avg_migrated - avg_legacy\n\n        if delta \u003C= self.tolerance_ms:\n            report.add_check(\n                \"performance\", ValidationResult.PASS,\n                f\"Latency delta: {delta:.1f}ms (within {self.tolerance_ms}ms tolerance)\",\n            )\n        elif delta \u003C= self.tolerance_ms * 2:\n            report.add_check(\n                \"performance\", ValidationResult.WARN,\n                f\"Latency delta: {delta:.1f}ms (approaching tolerance of {self.tolerance_ms}ms)\",\n            )\n        else:\n            report.add_check(\n                \"performance\", ValidationResult.FAIL,\n                f\"Latency delta: {delta:.1f}ms (exceeds tolerance of {self.tolerance_ms}ms)\",\n            )\n\n    def _extract_keys(self, obj: Any, prefix: str = \"\") -> set[str]:\n        \"\"\"Recursively extract all key paths from a JSON object.\"\"\"\n        keys = set()\n        if isinstance(obj, dict):\n            for k, v in obj.items():\n                full_key = f\"{prefix}.{k}\" if prefix else k\n                keys.add(full_key)\n                keys.update(self._extract_keys(v, full_key))\n        elif isinstance(obj, list) and obj:\n            keys.update(self._extract_keys(obj[0], f\"{prefix}[]\"))\n        return keys\n\n    async def close(self):\n        await self._client.aclose()\n```\n\n### Running Validation\n\nRun the validator as part of your CI pipeline or as a standalone validation script:\n\n```python\nimport asyncio\n\n\nasync def validate_migration():\n    validator = MigrationValidator(\n        legacy_base_url=\"http:\u002F\u002Flocalhost:8000\",\n        migrated_base_url=\"http:\u002F\u002Flocalhost:8001\",\n        tolerance_ms=50.0,\n    )\n\n    endpoints_to_validate = [\n        {\n            \"endpoint\": \"\u002Fapi\u002Fv1\u002Fsearch\",\n            \"method\": \"GET\",\n            \"human_headers\": {\"Authorization\": \"Bearer test-jwt-token\"},\n            \"agent_headers\": {\"X-Agent-Id\": \"test-agent-001\"},\n        },\n        {\n            \"endpoint\": \"\u002Fapi\u002Fv1\u002Fanalyze\",\n            \"method\": \"POST\",\n            \"body\": {\"text\": \"sample input for validation\"},\n            \"human_headers\": {\"Authorization\": \"Bearer test-jwt-token\"},\n            \"agent_headers\": {\"X-Agent-Id\": \"test-agent-001\"},\n        },\n    ]\n\n    reports = []\n    for ep in endpoints_to_validate:\n        report = await validator.validate_endpoint(**ep)\n        reports.append(report)\n        print(report.summary())\n        for check in report.checks:\n            status = \"OK\" if check[\"result\"] == \"pass\" else check[\"result\"].upper()\n            detail = f\" - {check['detail']}\" if check[\"detail\"] else \"\"\n            print(f\"  [{status}] {check['name']}{detail}\")\n\n    await validator.close()\n\n    # Fail CI if any endpoint fails validation\n    all_passed = all(r.passed for r in reports)\n    if not all_passed:\n        print(\"\\nMigration validation FAILED\")\n        exit(1)\n    else:\n        print(\"\\nAll migration validations passed\")\n\n\nasyncio.run(validate_migration())\n```\n\n### Contract Testing Between Old and New\n\nBeyond schema comparison, contract tests verify specific response invariants that your API consumers depend on. Define these contracts explicitly:\n\n```python\n@dataclass\nclass ResponseContract:\n    \"\"\"Defines expected properties of a response that must not change during migration.\"\"\"\n    endpoint: str\n    status_code: int\n    required_fields: list[str]\n    field_types: dict[str, type]\n    value_constraints: dict[str, callable]  # field -> validator function\n\n    def validate(self, response_body: dict) -> list[str]:\n        \"\"\"Returns list of contract violations.\"\"\"\n        violations = []\n\n        for field_path in self.required_fields:\n            if not self._has_field(response_body, field_path):\n                violations.append(f\"Missing required field: {field_path}\")\n\n        for field_path, expected_type in self.field_types.items():\n            value = self._get_field(response_body, field_path)\n            if value is not None and not isinstance(value, expected_type):\n                violations.append(\n                    f\"Type mismatch for {field_path}: expected {expected_type.__name__}, \"\n                    f\"got {type(value).__name__}\"\n                )\n\n        for field_path, validator in self.value_constraints.items():\n            value = self._get_field(response_body, field_path)\n            if value is not None and not validator(value):\n                violations.append(f\"Value constraint failed for {field_path}: {value}\")\n\n        return violations\n\n    def _has_field(self, obj: dict, path: str) -> bool:\n        parts = path.split(\".\")\n        current = obj\n        for part in parts:\n            if isinstance(current, dict) and part in current:\n                current = current[part]\n            else:\n                return False\n        return True\n\n    def _get_field(self, obj: dict, path: str) -> Any:\n        parts = path.split(\".\")\n        current = obj\n        for part in parts:\n            if isinstance(current, dict) and part in current:\n                current = current[part]\n            else:\n                return None\n        return current\n\n\n# Example contract definition\nsearch_contract = ResponseContract(\n    endpoint=\"\u002Fapi\u002Fv1\u002Fsearch\",\n    status_code=200,\n    required_fields=[\"results\", \"total_count\"],\n    field_types={\n        \"results\": list,\n        \"total_count\": int,\n    },\n    value_constraints={\n        \"total_count\": lambda v: v >= 0,\n    },\n)\n```\n\n---\n\n## Chapter 7: Testing Migration\n\nTesting a migration is not the same as testing new code. You are not verifying that something works — you are verifying that it works the same way it did before, plus new capabilities. The testing strategy has three phases: pre-migration baseline capture, parallel validation during migration, and post-migration regression testing.\n\n### Phase 1: Baseline Capture\n\nBefore touching any code, capture baseline responses for every endpoint you plan to migrate. These baselines become the ground truth for comparison:\n\n```python\nimport json\nimport time\nimport os\nfrom dataclasses import dataclass, asdict\nfrom typing import Any\n\nimport httpx\n\n\n@dataclass\nclass BaselineCapture:\n    endpoint: str\n    method: str\n    request_body: Any\n    response_status: int\n    response_body: Any\n    response_headers: dict[str, str]\n    latency_ms: float\n    captured_at: float\n\n\nclass BaselineRecorder:\n    \"\"\"Records baseline API responses for migration comparison.\"\"\"\n\n    def __init__(self, base_url: str, output_dir: str = \".\u002Fmigration_baselines\"):\n        self.base_url = base_url.rstrip(\"\u002F\")\n        self.output_dir = output_dir\n        os.makedirs(output_dir, exist_ok=True)\n\n    async def capture(\n        self, endpoint: str, method: str = \"GET\", body: Any = None,\n        headers: dict = None, iterations: int = 10,\n    ) -> list[BaselineCapture]:\n        \"\"\"Capture multiple baseline responses for statistical comparison.\"\"\"\n        captures = []\n        async with httpx.AsyncClient(timeout=30.0) as client:\n            for _ in range(iterations):\n                start = time.time()\n                if method.upper() == \"GET\":\n                    resp = await client.get(\n                        f\"{self.base_url}{endpoint}\", headers=headers or {}\n                    )\n                else:\n                    resp = await client.request(\n                        method, f\"{self.base_url}{endpoint}\",\n                        json=body, headers=headers or {},\n                    )\n                latency = (time.time() - start) * 1000\n\n                try:\n                    resp_body = resp.json()\n                except ValueError:\n                    resp_body = resp.text\n\n                capture = BaselineCapture(\n                    endpoint=endpoint,\n                    method=method,\n                    request_body=body,\n                    response_status=resp.status_code,\n                    response_body=resp_body,\n                    response_headers=dict(resp.headers),\n                    latency_ms=latency,\n                    captured_at=time.time(),\n                )\n                captures.append(capture)\n\n        # Save to disk\n        filename = endpoint.replace(\"\u002F\", \"_\").strip(\"_\") + \".json\"\n        filepath = os.path.join(self.output_dir, filename)\n        with open(filepath, \"w\") as f:\n            json.dump([asdict(c) for c in captures], f, indent=2, default=str)\n\n        return captures\n```\n\nRun the baseline recorder against every endpoint in your migration list. Store the output in version control. These files serve as regression evidence — if something breaks during migration, you have concrete proof of what the correct behavior was.\n\n### Phase 2: Shadow Traffic Validation\n\nShadow traffic sends a copy of every real production request to the migrated endpoint and compares responses without affecting the actual client. The client gets the legacy response, but the migrated response is captured and compared asynchronously:\n\n```python\nimport asyncio\nimport time\nimport json\nimport logging\nfrom typing import Any\n\nimport httpx\n\nlogger = logging.getLogger(\"shadow_traffic\")\n\n\nclass ShadowTrafficValidator:\n    \"\"\"\n    Replays production traffic against migrated endpoints.\n    Compares responses without affecting production clients.\n    \"\"\"\n\n    def __init__(\n        self,\n        migrated_base_url: str,\n        mismatch_log: str = \".\u002Fshadow_mismatches.jsonl\",\n    ):\n        self.migrated_url = migrated_base_url.rstrip(\"\u002F\")\n        self.mismatch_log = mismatch_log\n        self._client = httpx.AsyncClient(timeout=10.0)\n        self._stats = {\"total\": 0, \"matched\": 0, \"mismatched\": 0, \"errors\": 0}\n\n    async def shadow_request(\n        self,\n        endpoint: str,\n        method: str,\n        body: Any,\n        headers: dict,\n        legacy_status: int,\n        legacy_body: Any,\n    ) -> None:\n        \"\"\"Send shadow request and compare with legacy response.\"\"\"\n        self._stats[\"total\"] += 1\n\n        # Remove auth headers that might not work against the migrated version\n        shadow_headers = {\n            k: v for k, v in headers.items()\n            if k.lower() not in (\"cookie\", \"x-csrf-token\")\n        }\n\n        try:\n            start = time.time()\n            if method.upper() == \"GET\":\n                resp = await self._client.get(\n                    f\"{self.migrated_url}{endpoint}\", headers=shadow_headers\n                )\n            else:\n                resp = await self._client.request(\n                    method, f\"{self.migrated_url}{endpoint}\",\n                    json=body, headers=shadow_headers,\n                )\n            latency = (time.time() - start) * 1000\n\n            # Compare status codes\n            if resp.status_code != legacy_status:\n                self._log_mismatch(endpoint, \"status_code\", legacy_status, resp.status_code)\n                self._stats[\"mismatched\"] += 1\n                return\n\n            # Compare response bodies (ignoring dynamic fields)\n            try:\n                migrated_body = resp.json()\n                if not self._bodies_equivalent(legacy_body, migrated_body):\n                    self._log_mismatch(endpoint, \"body\", legacy_body, migrated_body)\n                    self._stats[\"mismatched\"] += 1\n                    return\n            except (json.JSONDecodeError, ValueError):\n                pass\n\n            self._stats[\"matched\"] += 1\n\n        except Exception as exc:\n            self._stats[\"errors\"] += 1\n            logger.error(f\"Shadow request failed for {endpoint}: {exc}\")\n\n    def _bodies_equivalent(self, legacy: Any, migrated: Any) -> bool:\n        \"\"\"Compare bodies, ignoring known dynamic fields.\"\"\"\n        dynamic_fields = {\"timestamp\", \"request_id\", \"trace_id\", \"generated_at\"}\n\n        if isinstance(legacy, dict) and isinstance(migrated, dict):\n            # If migrated wraps in envelope, unwrap\n            if \"data\" in migrated and \"meta\" in migrated:\n                migrated = migrated[\"data\"]\n\n            for key in set(legacy.keys()) | set(migrated.keys()):\n                if key in dynamic_fields:\n                    continue\n                if key not in legacy or key not in migrated:\n                    return False\n                if not self._bodies_equivalent(legacy[key], migrated[key]):\n                    return False\n            return True\n\n        if isinstance(legacy, list) and isinstance(migrated, list):\n            if len(legacy) != len(migrated):\n                return False\n            return all(\n                self._bodies_equivalent(a, b) for a, b in zip(legacy, migrated)\n            )\n\n        return legacy == migrated\n\n    def _log_mismatch(\n        self, endpoint: str, field: str, expected: Any, actual: Any,\n    ) -> None:\n        entry = {\n            \"timestamp\": time.time(),\n            \"endpoint\": endpoint,\n            \"field\": field,\n            \"expected\": str(expected)[:500],\n            \"actual\": str(actual)[:500],\n        }\n        with open(self.mismatch_log, \"a\") as f:\n            f.write(json.dumps(entry) + \"\\n\")\n\n    @property\n    def match_rate(self) -> float:\n        if self._stats[\"total\"] == 0:\n            return 0.0\n        return self._stats[\"matched\"] \u002F self._stats[\"total\"]\n\n    async def close(self):\n        await self._client.aclose()\n```\n\nIntegrate shadow validation into your production middleware. After the legacy handler returns a response to the client, fire off the shadow request asynchronously:\n\n```python\nimport asyncio\nfrom fastapi import Request, Response\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\nshadow_validator = ShadowTrafficValidator(migrated_base_url=\"http:\u002F\u002Flocalhost:8001\")\n\n\nclass ShadowTrafficMiddleware(BaseHTTPMiddleware):\n    async def dispatch(self, request: Request, call_next) -> Response:\n        # Process request normally\n        body = await request.body()\n        response = await call_next(request)\n\n        # Fire shadow request in background (don't block the response)\n        try:\n            resp_body = json.loads(response.body) if hasattr(response, \"body\") else None\n        except (json.JSONDecodeError, ValueError):\n            resp_body = None\n\n        asyncio.create_task(\n            shadow_validator.shadow_request(\n                endpoint=request.url.path,\n                method=request.method,\n                body=json.loads(body) if body else None,\n                headers=dict(request.headers),\n                legacy_status=response.status_code,\n                legacy_body=resp_body,\n            )\n        )\n\n        return response\n```\n\n### Rollback Procedures\n\nEvery migration needs a rollback plan. Document rollback steps for each migration stage:\n\n**Stage 1 rollback (Discovery).** Remove the `wrap_endpoint` decorator or disable the middleware via feature flag. No data to clean up — discovery mode does not create escrows or process payments.\n\n**Stage 2 rollback (Payment).** Disable payment verification in the feature flags. Any in-flight escrows will expire and refund automatically after the settlement timeout. Communicate the maintenance window to agent consumers via your A2A protocol card status field.\n\n**Stage 3 rollback (Full).** Revert to the pre-migration code deployment. If using the reverse proxy routing approach, switch the nginx config to route all traffic to the legacy upstream. Agent sessions in progress will fail — this is acceptable because agent sessions are designed to be retryable.\n\n### Monitoring During Migration\n\nSet up alerts for these conditions during each migration phase:\n\n```python\nMIGRATION_ALERTS = {\n    \"error_rate_spike\": {\n        \"condition\": \"error_rate > baseline_error_rate * 1.5\",\n        \"action\": \"Pause migration, investigate\",\n        \"severity\": \"high\",\n    },\n    \"latency_regression\": {\n        \"condition\": \"p95_latency > baseline_p95 + 100ms\",\n        \"action\": \"Check payment verification service health\",\n        \"severity\": \"medium\",\n    },\n    \"402_misconfiguration\": {\n        \"condition\": \"402_responses_for_human_callers > 0\",\n        \"action\": \"Immediate rollback — caller classification is broken\",\n        \"severity\": \"critical\",\n    },\n    \"shadow_mismatch_rate\": {\n        \"condition\": \"shadow_match_rate \u003C 0.95\",\n        \"action\": \"Stop migration, review mismatches\",\n        \"severity\": \"high\",\n    },\n    \"payment_verification_timeout\": {\n        \"condition\": \"payment_verification_p95 > 5000ms\",\n        \"action\": \"Enable verification cache, check GreenHelix status\",\n        \"severity\": \"medium\",\n    },\n}\n```\n\nThe most critical alert is `402_misconfiguration`. If human callers ever receive a 402 response, the caller classification logic is broken and the migration must be rolled back immediately. This is the one failure mode that directly impacts existing users.\n\n---\n\n## Chapter 8: Performance Comparison\n\nAdding a commerce layer to your API adds latency. The question is how much and whether it matters. This chapter provides the benchmarking framework to measure the exact overhead and the optimization strategies to minimize it.\n\n### Benchmarking Framework\n\n```python\nimport asyncio\nimport time\nimport statistics\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nimport httpx\n\n\n@dataclass\nclass BenchmarkResult:\n    endpoint: str\n    variant: str  # \"legacy\" or \"migrated\"\n    requests: int\n    avg_latency_ms: float\n    p50_latency_ms: float\n    p95_latency_ms: float\n    p99_latency_ms: float\n    min_latency_ms: float\n    max_latency_ms: float\n    error_count: int\n    throughput_rps: float\n\n\nclass MigrationBenchmark:\n    \"\"\"Benchmarks legacy vs migrated endpoint performance.\"\"\"\n\n    def __init__(\n        self,\n        legacy_url: str,\n        migrated_url: str,\n        concurrency: int = 10,\n        duration_seconds: int = 30,\n    ):\n        self.legacy_url = legacy_url.rstrip(\"\u002F\")\n        self.migrated_url = migrated_url.rstrip(\"\u002F\")\n        self.concurrency = concurrency\n        self.duration = duration_seconds\n\n    async def run(\n        self,\n        endpoint: str,\n        method: str = \"GET\",\n        body: object = None,\n        headers: dict = None,\n    ) -> dict[str, BenchmarkResult]:\n        \"\"\"Run benchmark against both legacy and migrated endpoints.\"\"\"\n        legacy_result = await self._benchmark_variant(\n            self.legacy_url, endpoint, method, body, headers or {}, \"legacy\"\n        )\n        migrated_result = await self._benchmark_variant(\n            self.migrated_url, endpoint, method, body, headers or {}, \"migrated\"\n        )\n\n        return {\n            \"legacy\": legacy_result,\n            \"migrated\": migrated_result,\n            \"overhead_ms\": migrated_result.avg_latency_ms - legacy_result.avg_latency_ms,\n            \"overhead_pct\": (\n                (migrated_result.avg_latency_ms - legacy_result.avg_latency_ms)\n                \u002F legacy_result.avg_latency_ms * 100\n                if legacy_result.avg_latency_ms > 0 else 0\n            ),\n            \"throughput_delta_rps\": (\n                migrated_result.throughput_rps - legacy_result.throughput_rps\n            ),\n        }\n\n    async def _benchmark_variant(\n        self,\n        base_url: str,\n        endpoint: str,\n        method: str,\n        body: object,\n        headers: dict,\n        variant: str,\n    ) -> BenchmarkResult:\n        latencies: list[float] = []\n        errors = 0\n        start_time = time.time()\n\n        async def worker():\n            nonlocal errors\n            async with httpx.AsyncClient(timeout=30.0) as client:\n                while time.time() - start_time \u003C self.duration:\n                    req_start = time.time()\n                    try:\n                        if method.upper() == \"GET\":\n                            resp = await client.get(\n                                f\"{base_url}{endpoint}\", headers=headers\n                            )\n                        else:\n                            resp = await client.request(\n                                method, f\"{base_url}{endpoint}\",\n                                json=body, headers=headers,\n                            )\n                        latency = (time.time() - req_start) * 1000\n                        latencies.append(latency)\n                        if resp.status_code >= 500:\n                            errors += 1\n                    except Exception:\n                        errors += 1\n\n        workers = [asyncio.create_task(worker()) for _ in range(self.concurrency)]\n        await asyncio.gather(*workers)\n\n        total_time = time.time() - start_time\n\n        if not latencies:\n            return BenchmarkResult(\n                endpoint=endpoint, variant=variant, requests=0,\n                avg_latency_ms=0, p50_latency_ms=0, p95_latency_ms=0,\n                p99_latency_ms=0, min_latency_ms=0, max_latency_ms=0,\n                error_count=errors, throughput_rps=0,\n            )\n\n        sorted_latencies = sorted(latencies)\n        p50_idx = int(len(sorted_latencies) * 0.50)\n        p95_idx = int(len(sorted_latencies) * 0.95)\n        p99_idx = int(len(sorted_latencies) * 0.99)\n\n        return BenchmarkResult(\n            endpoint=endpoint,\n            variant=variant,\n            requests=len(latencies),\n            avg_latency_ms=round(statistics.mean(latencies), 2),\n            p50_latency_ms=round(sorted_latencies[p50_idx], 2),\n            p95_latency_ms=round(sorted_latencies[p95_idx], 2),\n            p99_latency_ms=round(sorted_latencies[min(p99_idx, len(sorted_latencies) - 1)], 2),\n            min_latency_ms=round(sorted_latencies[0], 2),\n            max_latency_ms=round(sorted_latencies[-1], 2),\n            error_count=errors,\n            throughput_rps=round(len(latencies) \u002F total_time, 2),\n        )\n```\n\n### Understanding the Latency Breakdown\n\nThe commerce layer adds latency at four points:\n\n1. **Caller classification** (\u003C 1ms): Header inspection and string matching. Negligible.\n\n2. **Payment verification** (10-100ms): Network call to GreenHelix to verify the payment token. This is the dominant cost. With the verification cache enabled, repeat requests from the same agent with the same token skip this call entirely, reducing it to \u003C 1ms.\n\n3. **Identity verification** (5-50ms): Ed25519 signature verification is a local CPU operation (\u003C 1ms), but resolving the agent identity against GreenHelix adds a network call. Cache agent identity lookups for 5 minutes to amortize this cost.\n\n4. **Response transformation** (\u003C 1ms): JSON wrapping is a memory operation. Even for large responses (1MB+), the transformation adds under 1ms.\n\nThe total expected overhead for a cache-miss agent request is 15-150ms, dominated by payment and identity verification network calls. With warm caches, the overhead drops to 1-3ms.\n\n### Optimization Strategies\n\n**Connection pooling.** The `httpx.AsyncClient` used for GreenHelix communication should be a long-lived singleton with connection pooling enabled. Creating a new HTTP client per request adds 50-100ms of connection setup overhead:\n\n```python\n# Bad: new client per request\nasync def verify_payment(token):\n    async with httpx.AsyncClient() as client:  # Connection setup every time\n        return await client.post(...)\n\n# Good: shared client with connection pool\n_greenhelix_client = httpx.AsyncClient(\n    base_url=\"https:\u002F\u002Fapi.greenhelix.net\",\n    timeout=10.0,\n    limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),\n)\n\nasync def verify_payment(token):\n    return await _greenhelix_client.post(...)  # Reuses connections\n```\n\n**Batch verification.** If your API serves requests in bursts (common with agent orchestration patterns where one agent dispatches multiple sub-tasks), batch multiple payment verifications into a single GreenHelix API call:\n\n```python\nasync def verify_payments_batch(tokens: list[dict]) -> list[dict]:\n    \"\"\"Verify multiple payment tokens in one API call.\"\"\"\n    response = await _greenhelix_client.post(\n        \"\u002Fv1\u002Fpayments\u002Fverify-batch\",\n        json={\"tokens\": tokens},\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n    )\n    return response.json()[\"results\"]\n```\n\n**Preemptive caching.** Agents that frequently call the same endpoint can be given a bulk payment token that covers N future requests. The verification cache stores the token with a remaining-uses counter instead of a simple boolean:\n\n```python\n@dataclass\nclass BulkTokenEntry:\n    token: str\n    remaining_uses: int\n    endpoint: str\n    verified_at: float\n    ttl_seconds: int = 3600\n\n    @property\n    def is_valid(self) -> bool:\n        return self.remaining_uses > 0 and time.time() - self.verified_at \u003C self.ttl_seconds\n\n    def consume(self) -> bool:\n        if not self.is_valid:\n            return False\n        self.remaining_uses -= 1\n        return True\n```\n\n**Async settlement.** Payment settlement (releasing escrow funds to the seller) does not need to happen before the response is sent. Verify the token synchronously, send the response, then settle asynchronously. This removes settlement latency from the request path entirely:\n\n```python\nasync def handle_agent_request(request: Request):\n    # Verify payment (synchronous, blocks response)\n    payment = await verify_payment(request.headers[\"x-402-payment-token\"])\n\n    # Process business logic\n    result = await business_logic(request)\n\n    # Settle payment (asynchronous, does not block response)\n    asyncio.create_task(settle_payment(payment[\"escrow_id\"]))\n\n    return result\n```\n\n### Throughput Considerations\n\nAgent traffic patterns differ from human traffic. Humans send requests with natural pauses (reading, clicking, thinking). Agents send bursts of requests as fast as the API can respond. Your API might handle 100 requests per second from human users comfortably but struggle at 1000 requests per second from agents, even though the per-request processing time is the same. The bottleneck shifts from business logic to the commerce layer — specifically, the connection pool to GreenHelix for payment verification.\n\nSize your connection pool based on expected agent throughput. A pool of 20 keepalive connections to GreenHelix can handle approximately 200 verification requests per second (assuming 100ms average verification time). For higher throughput, increase the pool or enable the verification cache aggressively.\n\nMonitor these throughput metrics during migration:\n\n- Requests per second by caller type (human vs agent)\n- GreenHelix verification latency (p50, p95, p99)\n- Connection pool utilization (active vs idle connections)\n- Cache hit rate for payment verification\n- Queue depth if you implement request queuing\n\n---\n\n## What's Next\n\nYou now have a complete framework for migrating any REST API to support agent commerce. The `LegacyApiAdapter` wraps your existing endpoints without modifying business logic. The x402 middleware handles payment negotiation at the HTTP layer. The `AuthBridge` runs agent Ed25519 authentication alongside your existing auth system. The `MigrationValidator` automates regression testing throughout the migration. And the benchmarking framework quantifies the exact performance cost of each component.\n\nThe migration order should be:\n\n1. Run the assessment checklist on your API.\n2. Deploy the `LegacyApiAdapter` in discovery mode (402 responses, no payment processing) on your highest-value read endpoints.\n3. Monitor agent traffic patterns for one to two weeks.\n4. Enable payment processing on the endpoints where agents are actually sending requests.\n5. Roll out identity verification.\n6. Migrate the remaining endpoints based on observed demand.\n7. Run the `MigrationValidator` continuously in CI.\n\nThe GreenHelix platform documentation at [https:\u002F\u002Fdocs.greenhelix.net](https:\u002F\u002Fdocs.greenhelix.net) covers escrow API details, A2A protocol card registration, and agent identity management. The x402 specification at [https:\u002F\u002Fwww.x402.org](https:\u002F\u002Fwww.x402.org) defines the full payment header protocol.\n\nStart with one endpoint. Prove it works. Then migrate the rest.\n\n","# Agent Commerce Migration Guide: Retrofit Your REST APIs for Autonomous Agent Buyers\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code 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> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nYou have a working REST API. It serves human users through a web frontend. Maybe it powers a SaaS product, a data marketplace, or a specialized computation service. The endpoints are tested, the authentication works, and your customers are happy. Now AI agents want to buy your services programmatically. They don't want to fill out a signup form, navigate a dashboard, or read your documentation the way a human does. They want to discover your capabilities through structured metadata, negotiate a price via HTTP headers, pay per call with cryptographic proof, and consume your response — all in a single request cycle. The instinct is to build a separate \"agent API\" from scratch, but that is the wrong move. You already have the hard part: working business logic behind stable endpoints. What you need is a commerce layer on top of what exists. This guide shows how to retrofit any REST API with agent commerce capabilities: x402 payment headers for per-call pricing, GreenHelix escrow integration for trustless settlement, Ed25519 identity verification for agent authentication, and structured service discovery so agents can find and evaluate your offerings without human intervention. The approach is gradual. You can migrate one endpoint at a time while existing human users continue hitting the same URLs with the same authentication they have always used. No big bang rewrite. No downtime. No breaking changes. By the end of this guide you will have a complete migration framework — assessment tools, adapter classes, middleware patterns, validation harnesses, and rollback procedures — that transforms your existing REST API into an agent-ready commerce platform without sacrificing anything that already works.\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: Migration Assessment\n- Chapter 2: LegacyApiAdapter Class\n- Chapter 3: x402 Retrofit Patterns\n- Chapter 4: Authentication Bridging\n- Chapter 5: Gradual Migration Strategies\n- Chapter 6: MigrationValidator Class\n- Chapter 7: Testing Migration\n- Chapter 8: Performance Comparison\n- What's Next\n\n## Full Guide\n\n# Agent Commerce Migration Guide: Retrofit Your REST APIs for Autonomous Agent Buyers\n\nYou have a working REST API. It serves human users through a web frontend. Maybe it powers a SaaS product, a data marketplace, or a specialized computation service. The endpoints are tested, the authentication works, and your customers are happy. Now AI agents want to buy your services programmatically. They don't want to fill out a signup form, navigate a dashboard, or read your documentation the way a human does. They want to discover your capabilities through structured metadata, negotiate a price via HTTP headers, pay per call with cryptographic proof, and consume your response — all in a single request cycle. The instinct is to build a separate \"agent API\" from scratch, but that is the wrong move. You already have the hard part: working business logic behind stable endpoints. What you need is a commerce layer on top of what exists. This guide shows how to retrofit any REST API with agent commerce capabilities: x402 payment headers for per-call pricing, GreenHelix escrow integration for trustless settlement, Ed25519 identity verification for agent authentication, and structured service discovery so agents can find and evaluate your offerings without human intervention. The approach is gradual. You can migrate one endpoint at a time while existing human users continue hitting the same URLs with the same authentication they have always used. No big bang rewrite. No downtime. No breaking changes. By the end of this guide you will have a complete migration framework — assessment tools, adapter classes, middleware patterns, validation harnesses, and rollback procedures — that transforms your existing REST API into an agent-ready commerce platform without sacrificing anything that already works.\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## Chapter 1: Migration Assessment\n\nBefore writing any migration code, you need an honest evaluation of where your API stands today and what it will take to make it agent-commerce ready. This assessment phase saves weeks of wasted effort by identifying blockers early, surfacing hidden dependencies, and prioritizing the endpoints that will generate the most agent revenue with the least migration risk.\n\n### The Four Pillars of Agent Commerce Readiness\n\nEvery REST API migration touches four areas. Your current implementation might already satisfy some of them partially, but each one needs explicit attention.\n\n**Authentication readiness.** Agents do not use browser cookies or OAuth redirect flows. They present cryptographic identity — typically an Ed25519 public key with a signed request payload. Your API needs to verify these signatures alongside whatever auth mechanism already exists. The question is not whether you can replace your current auth, but whether you can layer agent auth on top of it.\n\n**Payment readiness.** Human users pay through subscriptions, invoices, or credit cards processed asynchronously. Agent commerce is synchronous: the agent includes a payment token in the request header, your API verifies it before processing, and settlement happens atomically. If your API currently has no concept of per-call pricing, you need to add one. If it already has usage-based billing, you have a head start.\n\n**Response structure readiness.** Human-facing APIs often return loosely structured JSON with messages meant for UI rendering — status strings like \"Success!\", nested error objects with display text, pagination metadata mixed into the response body. Agents need machine-parseable responses with predictable schemas, consistent error codes, and clear separation between data and metadata. The more disciplined your current response format, the less transformation work ahead.\n\n**Discovery readiness.** Agents find services through structured manifests — A2A protocol cards, OpenAPI specifications with pricing extensions, or capability registries. If your API has no machine-readable description of what it offers and what it costs, agents cannot evaluate it. Most REST APIs have some form of documentation, but rarely in a format an agent can consume autonomously.\n\n### The Assessment Checklist\n\nRun through this checklist for every endpoint you are considering for migration. Score each item 0 (not present), 1 (partially present), or 2 (fully present):\n\n```python\nMIGRATION_ASSESSMENT = {\n    \"authentication\": [\n        \"Stateless auth supported (tokens, not sessions)\",\n        \"Auth info passed via headers (not cookies)\",\n        \"Auth can be extended without breaking existing clients\",\n        \"Rate limiting is per-identity, not per-IP\",\n    ],\n    \"payments\": [\n        \"Usage tracking exists at per-call granularity\",\n        \"Pricing model defined for individual operations\",\n        \"Billing system can handle micropayments\",\n        \"Idempotency keys supported on payment-related endpoints\",\n    ],\n    \"response_structure\": [\n        \"Consistent JSON envelope across all endpoints\",\n        \"Error responses use numeric codes, not just strings\",\n        \"Pagination uses cursors, not page numbers\",\n        \"Response schemas are documented and stable\",\n    ],\n    \"discovery\": [\n        \"OpenAPI \u002F Swagger spec exists and is current\",\n        \"Endpoint capabilities described in machine-readable format\",\n        \"Versioning strategy is explicit (URL or header)\",\n        \"Health check endpoint exists\",\n    ],\n}\n\ndef score_api(scores: dict[str, list[int]]) -> dict:\n    results = {}\n    for category, items in scores.items():\n        total = sum(items)\n        max_score = len(MIGRATION_ASSESSMENT[category]) * 2\n        results[category] = {\n            \"score\": total,\n            \"max\": max_score,\n            \"percentage\": round(total \u002F max_score * 100),\n            \"ready\": total >= max_score * 0.75,\n        }\n    results[\"overall_ready\"] = all(r[\"ready\"] for r in results.values())\n    return results\n```\n\nAn overall score above 75% means you can proceed with migration directly. Between 50% and 75%, plan for prerequisite work on the weakest pillar before starting. Below 50%, consider whether the API needs structural improvements first — migration on top of a fragile foundation creates compounding problems.\n\n### The LegacyApiAdapter Pattern Overview\n\nThe core architectural pattern for this migration is the `LegacyApiAdapter`: a wrapper class that sits between incoming agent requests and your existing endpoint handlers. It performs three functions. First, it intercepts agent-specific headers (x402 payment tokens, Ed25519 signatures, capability queries) and processes them before the request reaches your business logic. Second, it transforms your existing response format into the agent-expected envelope if needed. Third, it passes through requests from non-agent clients completely unchanged, so your existing users never notice the migration happened.\n\nThis is not a proxy in the traditional sense. It runs in the same process as your existing API, adds no network hops, and shares the same database connections and caches. Think of it as a decorator pattern applied at the HTTP layer.\n\n### Identifying High-Value Migration Targets\n\nNot every endpoint is worth migrating. Start with endpoints that satisfy three criteria:\n\n**High agent utility.** Data retrieval endpoints (search, lookup, analytics) are the most immediately useful to agents. Agents are information consumers first. An endpoint that returns structured data an agent can act on is more valuable than a CRUD endpoint for managing user profiles.\n\n**Low migration complexity.** Endpoints with simple request\u002Fresponse schemas, no file uploads, no streaming responses, and no multi-step workflows are easiest to migrate. Save the complex ones for later phases.\n\n**Clear pricing model.** You need to assign a per-call price. Endpoints where the cost of serving a request is predictable (fixed computation, bounded database queries) are easier to price than endpoints with variable resource consumption. If you cannot state a price, you are not ready to migrate that endpoint.\n\nRank your endpoints by (utility x 1\u002Fcomplexity x pricing_clarity) and migrate the top five first. This gives you a working agent commerce surface quickly, generates early revenue, and builds confidence in the migration pattern before tackling harder endpoints.\n\n---\n\n## Chapter 2: LegacyApiAdapter Class\n\nThe `LegacyApiAdapter` is the central abstraction for this entire migration. It wraps your existing endpoint handlers and adds agent commerce capabilities without modifying the underlying business logic. Every request flows through the adapter, which decides whether to apply agent commerce processing or pass the request through unchanged.\n\n### Design Principles\n\nThe adapter follows three rules. First, zero regression: any request that worked before the adapter was installed must continue to work identically. Second, opt-in activation: agent commerce features activate only when the request contains agent-specific headers. Third, fail-open for humans: if agent commerce processing fails (payment verification timeout, identity service unavailable), non-agent requests still succeed. Agent requests fail explicitly with structured error responses.\n\n### The Complete Adapter Class\n\n```python\nimport time\nimport hashlib\nimport json\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import Any, Callable, Optional\nfrom functools import wraps\n\nimport httpx\nfrom fastapi import Request, Response, HTTPException\nfrom fastapi.responses import JSONResponse\n\n\nclass CallerType(str, Enum):\n    HUMAN = \"human\"\n    AGENT = \"agent\"\n    UNKNOWN = \"unknown\"\n\n\n@dataclass\nclass PricingConfig:\n    \"\"\"Per-endpoint pricing configuration.\"\"\"\n    price_usd: float\n    currency: str = \"USD\"\n    escrow_required: bool = True\n    min_deposit: float = 0.01\n    max_deposit: float = 100.00\n    settlement_timeout_seconds: int = 300\n\n\n@dataclass\nclass MigrationConfig:\n    \"\"\"Configuration for the adapter's behavior.\"\"\"\n    greenhelix_url: str = \"https:\u002F\u002Fapi.greenhelix.net\"\n    greenhelix_api_key: str = \"\"\n    verify_payments: bool = True\n    verify_identity: bool = True\n    transform_responses: bool = True\n    pass_through_on_failure: bool = False\n    pricing: dict[str, PricingConfig] = field(default_factory=dict)\n\n\n@dataclass\nclass AgentContext:\n    \"\"\"Extracted agent information from request headers.\"\"\"\n    caller_type: CallerType\n    agent_id: Optional[str] = None\n    payment_token: Optional[str] = None\n    signature: Optional[str] = None\n    public_key: Optional[str] = None\n    requested_capabilities: list[str] = field(default_factory=list)\n\n\nclass LegacyApiAdapter:\n    \"\"\"\n    Wraps existing REST API endpoints with agent commerce capabilities.\n\n    Intercepts agent-specific headers, verifies payments and identity,\n    transforms responses, and passes through non-agent requests unchanged.\n    \"\"\"\n\n    def __init__(self, config: MigrationConfig):\n        self.config = config\n        self._http_client = httpx.AsyncClient(\n            base_url=config.greenhelix_url,\n            timeout=10.0,\n        )\n        self._payment_cache: dict[str, float] = {}\n\n    def classify_caller(self, request: Request) -> AgentContext:\n        \"\"\"Determine whether the request comes from a human or an agent.\"\"\"\n        payment_token = request.headers.get(\"x-402-payment-token\")\n        agent_id = request.headers.get(\"x-agent-id\")\n        signature = request.headers.get(\"x-agent-signature\")\n        public_key = request.headers.get(\"x-agent-public-key\")\n\n        if payment_token or agent_id:\n            return AgentContext(\n                caller_type=CallerType.AGENT,\n                agent_id=agent_id,\n                payment_token=payment_token,\n                signature=signature,\n                public_key=public_key,\n            )\n\n        user_agent = request.headers.get(\"user-agent\", \"\")\n        agent_indicators = [\"bot\", \"agent\", \"crawler\", \"a2a-client\"]\n        if any(indicator in user_agent.lower() for indicator in agent_indicators):\n            return AgentContext(caller_type=CallerType.AGENT, agent_id=agent_id)\n\n        return AgentContext(caller_type=CallerType.HUMAN)\n\n    async def verify_payment(\n        self, payment_token: str, endpoint: str, price: PricingConfig\n    ) -> dict:\n        \"\"\"Verify a payment token against GreenHelix escrow.\"\"\"\n        response = await self._http_client.post(\n            \"\u002Fv1\u002Fpayments\u002Fverify\",\n            json={\n                \"token\": payment_token,\n                \"expected_amount\": str(price.price_usd),\n                \"currency\": price.currency,\n                \"endpoint\": endpoint,\n            },\n            headers={\"Authorization\": f\"Bearer {self.config.greenhelix_api_key}\"},\n        )\n\n        if response.status_code != 200:\n            return {\"valid\": False, \"error\": response.text}\n\n        result = response.json()\n        return {\n            \"valid\": result.get(\"verified\", False),\n            \"escrow_id\": result.get(\"escrow_id\"),\n            \"amount\": result.get(\"amount\"),\n        }\n\n    async def verify_identity(self, ctx: AgentContext) -> dict:\n        \"\"\"Verify agent identity via Ed25519 signature.\"\"\"\n        if not ctx.public_key or not ctx.signature:\n            return {\"verified\": False, \"error\": \"Missing signature or public key\"}\n\n        response = await self._http_client.post(\n            \"\u002Fv1\u002Fidentity\u002Fverify\",\n            json={\n                \"agent_id\": ctx.agent_id,\n                \"public_key\": ctx.public_key,\n                \"signature\": ctx.signature,\n            },\n            headers={\"Authorization\": f\"Bearer {self.config.greenhelix_api_key}\"},\n        )\n\n        if response.status_code != 200:\n            return {\"verified\": False, \"error\": response.text}\n\n        return response.json()\n\n    def transform_response(\n        self, response_data: Any, endpoint: str, escrow_id: Optional[str] = None\n    ) -> dict:\n        \"\"\"Transform legacy response format into agent-expected envelope.\"\"\"\n        return {\n            \"data\": response_data,\n            \"meta\": {\n                \"endpoint\": endpoint,\n                \"timestamp\": time.time(),\n                \"escrow_id\": escrow_id,\n                \"schema_version\": \"1.0\",\n            },\n        }\n\n    def wrap_endpoint(self, endpoint_path: str):\n        \"\"\"\n        Decorator that wraps an existing endpoint handler with agent commerce.\n\n        Usage:\n            adapter = LegacyApiAdapter(config)\n\n            @app.get(\"\u002Fapi\u002Fdata\")\n            @adapter.wrap_endpoint(\"\u002Fapi\u002Fdata\")\n            async def get_data(request: Request):\n                return {\"results\": [...]}\n        \"\"\"\n        def decorator(func: Callable):\n            @wraps(func)\n            async def wrapper(request: Request, *args, **kwargs):\n                ctx = self.classify_caller(request)\n\n                # Pass through non-agent requests unchanged\n                if ctx.caller_type == CallerType.HUMAN:\n                    return await func(request, *args, **kwargs)\n\n                # Agent request: verify payment if pricing is configured\n                pricing = self.config.pricing.get(endpoint_path)\n                escrow_id = None\n\n                if pricing and self.config.verify_payments:\n                    if not ctx.payment_token:\n                        return JSONResponse(\n                            status_code=402,\n                            content={\n                                \"error\": \"payment_required\",\n                                \"detail\": \"This endpoint requires payment\",\n                                \"price\": str(pricing.price_usd),\n                                \"currency\": pricing.currency,\n                                \"payment_url\": (\n                                    f\"{self.config.greenhelix_url}\"\n                                    f\"\u002Fv1\u002Fpayments\u002Fcreate\"\n                                ),\n                            },\n                            headers={\n                                \"X-Price\": str(pricing.price_usd),\n                                \"X-Currency\": pricing.currency,\n                                \"X-Payment-URL\": (\n                                    f\"{self.config.greenhelix_url}\"\n                                    f\"\u002Fv1\u002Fpayments\u002Fcreate\"\n                                ),\n                            },\n                        )\n\n                    payment_result = await self.verify_payment(\n                        ctx.payment_token, endpoint_path, pricing\n                    )\n                    if not payment_result[\"valid\"]:\n                        return JSONResponse(\n                            status_code=402,\n                            content={\n                                \"error\": \"payment_invalid\",\n                                \"detail\": payment_result.get(\"error\", \"Payment verification failed\"),\n                            },\n                        )\n                    escrow_id = payment_result.get(\"escrow_id\")\n\n                # Verify agent identity if configured\n                if self.config.verify_identity and ctx.agent_id:\n                    identity_result = await self.verify_identity(ctx)\n                    if not identity_result.get(\"verified\", False):\n                        return JSONResponse(\n                            status_code=403,\n                            content={\n                                \"error\": \"identity_verification_failed\",\n                                \"detail\": identity_result.get(\"error\", \"Could not verify agent identity\"),\n                            },\n                        )\n\n                # Execute the original handler\n                result = await func(request, *args, **kwargs)\n\n                # Transform response for agents if configured\n                if self.config.transform_responses:\n                    if isinstance(result, Response):\n                        # If the handler returned a Response object, extract the body\n                        body = json.loads(result.body) if hasattr(result, 'body') else result\n                        return JSONResponse(\n                            content=self.transform_response(body, endpoint_path, escrow_id),\n                            status_code=result.status_code if hasattr(result, 'status_code') else 200,\n                        )\n                    else:\n                        return JSONResponse(\n                            content=self.transform_response(result, endpoint_path, escrow_id),\n                        )\n\n                return result\n\n            return wrapper\n        return decorator\n\n    async def close(self):\n        \"\"\"Clean up HTTP client resources.\"\"\"\n        await self._http_client.aclose()\n```\n\n### How the Adapter Routes Requests\n\nThe `classify_caller` method is the decision point. It checks for the `x-402-payment-token` and `x-agent-id` headers first — these are definitive agent indicators. If those are absent, it falls back to user-agent string inspection as a heuristic. This two-tier classification means agents that follow the x402 protocol get full commerce support, while agents that merely identify via user-agent get classified but may still need to provide payment headers for paid endpoints.\n\nThe `wrap_endpoint` decorator is designed to be non-invasive. You add it to an existing route handler with a single line. The original function signature does not change. The original return value is preserved for human callers. Only agent callers see the transformed response envelope. This means you can add the decorator to every endpoint in your API and nothing changes for existing users — they continue to get exactly the same responses they always got.\n\n### Request and Response Transformation\n\nResponse transformation deserves attention because it is where most migration bugs appear. The adapter wraps the original response in a standardized envelope with `data` and `meta` fields. The `data` field contains exactly what the original endpoint returned. The `meta` field adds context that agents need: which endpoint served the response, when it was generated, and the escrow ID if a payment was involved. This separation means agents can always find the business data in `response[\"data\"]` and the transaction metadata in `response[\"meta\"]`, regardless of how different endpoints structure their responses internally.\n\nFor endpoints that return `Response` objects directly (common in FastAPI when you need to set custom status codes or headers), the adapter extracts the body, deserializes it, wraps it, and re-serializes. This adds negligible overhead — JSON parsing of a response that was going to be serialized anyway.\n\n---\n\n## Chapter 3: x402 Retrofit Patterns\n\nThe x402 protocol uses HTTP status code 402 (Payment Required) to signal that an endpoint requires payment before it will process the request. This status code has been reserved in the HTTP specification since 1997 but was rarely used until agent commerce gave it a concrete purpose. Retrofitting x402 onto existing endpoints means adding payment negotiation to the HTTP layer without modifying business logic.\n\n### The Payment Negotiation Flow\n\nWhen an agent hits a paid endpoint without a payment token, the flow works like this:\n\n1. Agent sends `GET \u002Fapi\u002Fv1\u002Fdata` with no payment headers.\n2. Server responds with `402 Payment Required`, including price and payment URL in headers.\n3. Agent creates a payment escrow via the payment URL.\n4. Agent retries `GET \u002Fapi\u002Fv1\u002Fdata` with the `X-402-Payment-Token` header.\n5. Server verifies the token, processes the request, and returns data.\n6. Settlement happens automatically after the response is delivered.\n\nThis is a two-request flow for the agent: one to discover the price, one to pay and consume. Agents that already know the price (from cached discovery or manifest data) can skip step 1 and go straight to step 4.\n\n### Payment Header Specification\n\nThe x402 headers used in negotiation:\n\n```\n# Response headers on 402:\nX-Price: 0.05\nX-Currency: USD\nX-Payment-URL: https:\u002F\u002Fapi.greenhelix.net\u002Fv1\u002Fpayments\u002Fcreate\nX-Payment-Methods: greenhelix-escrow, x402-direct\nX-Price-Window: 300  # price valid for 300 seconds\n\n# Request headers on paid request:\nX-402-Payment-Token: ght_abc123...\nX-Agent-Id: agent-buyer-001\nX-Idempotency-Key: req_unique_id_here\n```\n\n### FastAPI Middleware Implementation\n\nThe cleanest way to add x402 support across multiple endpoints in FastAPI is through middleware combined with a pricing registry:\n\n```python\nimport time\nfrom typing import Optional\n\nfrom fastapi import FastAPI, Request, Response\nfrom fastapi.responses import JSONResponse\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\nimport httpx\n\n\n# Pricing registry: maps endpoint patterns to prices\nENDPOINT_PRICING: dict[str, dict] = {\n    \"\u002Fapi\u002Fv1\u002Fsearch\": {\n        \"price_usd\": \"0.02\",\n        \"currency\": \"USD\",\n        \"settlement_timeout\": 300,\n    },\n    \"\u002Fapi\u002Fv1\u002Fanalyze\": {\n        \"price_usd\": \"0.10\",\n        \"currency\": \"USD\",\n        \"settlement_timeout\": 600,\n    },\n    \"\u002Fapi\u002Fv1\u002Fgenerate\": {\n        \"price_usd\": \"0.25\",\n        \"currency\": \"USD\",\n        \"settlement_timeout\": 600,\n    },\n}\n\nGREENHELIX_URL = \"https:\u002F\u002Fapi.greenhelix.net\"\nGREENHELIX_API_KEY = \"\"  # Set from environment\n\n\nclass X402PaymentMiddleware(BaseHTTPMiddleware):\n    \"\"\"\n    Middleware that enforces x402 payment on configured endpoints.\n\n    Non-agent requests pass through. Agent requests to priced\n    endpoints must include a valid payment token.\n    \"\"\"\n\n    def __init__(self, app: FastAPI, greenhelix_api_key: str):\n        super().__init__(app)\n        self.api_key = greenhelix_api_key\n        self._client = httpx.AsyncClient(\n            base_url=GREENHELIX_URL, timeout=10.0\n        )\n\n    async def dispatch(self, request: Request, call_next) -> Response:\n        # Check if this endpoint has pricing\n        pricing = self._match_pricing(request.url.path)\n        if pricing is None:\n            return await call_next(request)\n\n        # Check if this is an agent request\n        payment_token = request.headers.get(\"x-402-payment-token\")\n        agent_id = request.headers.get(\"x-agent-id\")\n\n        # No agent headers — pass through to existing handler\n        if not payment_token and not agent_id:\n            return await call_next(request)\n\n        # Agent request without payment token — return 402\n        if not payment_token:\n            return self._payment_required_response(request.url.path, pricing)\n\n        # Agent request with payment token — verify it\n        verification = await self._verify_token(payment_token, request.url.path, pricing)\n        if not verification[\"valid\"]:\n            return JSONResponse(\n                status_code=402,\n                content={\n                    \"error\": \"payment_invalid\",\n                    \"detail\": verification.get(\"error\", \"Token verification failed\"),\n                },\n            )\n\n        # Payment verified — attach escrow info and proceed\n        request.state.escrow_id = verification.get(\"escrow_id\")\n        request.state.payment_verified = True\n        response = await call_next(request)\n\n        # Add settlement headers to the response\n        response.headers[\"X-Escrow-Id\"] = verification.get(\"escrow_id\", \"\")\n        response.headers[\"X-Settlement-Status\"] = \"pending\"\n\n        return response\n\n    def _match_pricing(self, path: str) -> Optional[dict]:\n        \"\"\"Match request path to pricing config, supporting wildcards.\"\"\"\n        if path in ENDPOINT_PRICING:\n            return ENDPOINT_PRICING[path]\n        # Check prefix matches for versioned endpoints\n        for pattern, pricing in ENDPOINT_PRICING.items():\n            if path.startswith(pattern):\n                return pricing\n        return None\n\n    def _payment_required_response(self, path: str, pricing: dict) -> JSONResponse:\n        \"\"\"Build a 402 response with payment negotiation headers.\"\"\"\n        return JSONResponse(\n            status_code=402,\n            content={\n                \"error\": \"payment_required\",\n                \"endpoint\": path,\n                \"price\": pricing[\"price_usd\"],\n                \"currency\": pricing[\"currency\"],\n                \"payment_url\": f\"{GREENHELIX_URL}\u002Fv1\u002Fpayments\u002Fcreate\",\n                \"price_valid_seconds\": pricing.get(\"settlement_timeout\", 300),\n            },\n            headers={\n                \"X-Price\": pricing[\"price_usd\"],\n                \"X-Currency\": pricing[\"currency\"],\n                \"X-Payment-URL\": f\"{GREENHELIX_URL}\u002Fv1\u002Fpayments\u002Fcreate\",\n                \"X-Payment-Methods\": \"greenhelix-escrow\",\n                \"X-Price-Window\": str(pricing.get(\"settlement_timeout\", 300)),\n            },\n        )\n\n    async def _verify_token(\n        self, token: str, endpoint: str, pricing: dict\n    ) -> dict:\n        \"\"\"Verify payment token with GreenHelix.\"\"\"\n        try:\n            response = await self._client.post(\n                \"\u002Fv1\u002Fpayments\u002Fverify\",\n                json={\n                    \"token\": token,\n                    \"expected_amount\": pricing[\"price_usd\"],\n                    \"currency\": pricing[\"currency\"],\n                    \"endpoint\": endpoint,\n                },\n                headers={\"Authorization\": f\"Bearer {self.api_key}\"},\n            )\n            if response.status_code == 200:\n                return response.json()\n            return {\"valid\": False, \"error\": f\"Verification returned {response.status_code}\"}\n        except httpx.TimeoutException:\n            return {\"valid\": False, \"error\": \"Payment verification timed out\"}\n\n\n# Application setup\napp = FastAPI()\napp.add_middleware(X402PaymentMiddleware, greenhelix_api_key=GREENHELIX_API_KEY)\n```\n\n### Flask Middleware Equivalent\n\nFor Flask applications, the same pattern uses `before_request` and `after_request` hooks:\n\n```python\nimport time\nfrom flask import Flask, request, jsonify, g\nimport httpx\n\napp = Flask(__name__)\n\nENDPOINT_PRICING = {\n    \"\u002Fapi\u002Fv1\u002Fsearch\": {\"price_usd\": \"0.02\", \"currency\": \"USD\"},\n    \"\u002Fapi\u002Fv1\u002Fanalyze\": {\"price_usd\": \"0.10\", \"currency\": \"USD\"},\n}\n\nGREENHELIX_URL = \"https:\u002F\u002Fapi.greenhelix.net\"\nGREENHELIX_API_KEY = \"\"\n\n\n@app.before_request\ndef check_agent_payment():\n    \"\"\"Intercept agent requests and enforce payment.\"\"\"\n    pricing = ENDPOINT_PRICING.get(request.path)\n    if pricing is None:\n        return None  # No pricing — pass through\n\n    payment_token = request.headers.get(\"X-402-Payment-Token\")\n    agent_id = request.headers.get(\"X-Agent-Id\")\n\n    if not payment_token and not agent_id:\n        return None  # Not an agent — pass through\n\n    if not payment_token:\n        response = jsonify({\n            \"error\": \"payment_required\",\n            \"price\": pricing[\"price_usd\"],\n            \"currency\": pricing[\"currency\"],\n            \"payment_url\": f\"{GREENHELIX_URL}\u002Fv1\u002Fpayments\u002Fcreate\",\n        })\n        response.status_code = 402\n        response.headers[\"X-Price\"] = pricing[\"price_usd\"]\n        response.headers[\"X-Currency\"] = pricing[\"currency\"]\n        return response\n\n    # Verify payment synchronously (use async client in production)\n    with httpx.Client(base_url=GREENHELIX_URL, timeout=10.0) as client:\n        result = client.post(\n            \"\u002Fv1\u002Fpayments\u002Fverify\",\n            json={\n                \"token\": payment_token,\n                \"expected_amount\": pricing[\"price_usd\"],\n                \"endpoint\": request.path,\n            },\n            headers={\"Authorization\": f\"Bearer {GREENHELIX_API_KEY}\"},\n        )\n\n    if result.status_code != 200 or not result.json().get(\"verified\"):\n        return jsonify({\"error\": \"payment_invalid\"}), 402\n\n    g.escrow_id = result.json().get(\"escrow_id\")\n    g.payment_verified = True\n    return None\n\n\n@app.after_request\ndef add_settlement_headers(response):\n    \"\"\"Add escrow headers to responses for verified agent requests.\"\"\"\n    if hasattr(g, \"payment_verified\") and g.payment_verified:\n        response.headers[\"X-Escrow-Id\"] = getattr(g, \"escrow_id\", \"\")\n        response.headers[\"X-Settlement-Status\"] = \"pending\"\n    return response\n```\n\n### Django Middleware Equivalent\n\nDjango uses a class-based middleware approach:\n\n```python\nimport json\nimport httpx\nfrom django.http import JsonResponse\n\nENDPOINT_PRICING = {\n    \"\u002Fapi\u002Fv1\u002Fsearch\u002F\": {\"price_usd\": \"0.02\", \"currency\": \"USD\"},\n    \"\u002Fapi\u002Fv1\u002Fanalyze\u002F\": {\"price_usd\": \"0.10\", \"currency\": \"USD\"},\n}\n\nGREENHELIX_URL = \"https:\u002F\u002Fapi.greenhelix.net\"\nGREENHELIX_API_KEY = \"\"\n\n\nclass X402PaymentMiddleware:\n    def __init__(self, get_response):\n        self.get_response = get_response\n\n    def __call__(self, request):\n        pricing = ENDPOINT_PRICING.get(request.path)\n\n        if pricing is None:\n            return self.get_response(request)\n\n        payment_token = request.META.get(\"HTTP_X_402_PAYMENT_TOKEN\")\n        agent_id = request.META.get(\"HTTP_X_AGENT_ID\")\n\n        if not payment_token and not agent_id:\n            return self.get_response(request)\n\n        if not payment_token:\n            response = JsonResponse(\n                {\n                    \"error\": \"payment_required\",\n                    \"price\": pricing[\"price_usd\"],\n                    \"currency\": pricing[\"currency\"],\n                },\n                status=402,\n            )\n            response[\"X-Price\"] = pricing[\"price_usd\"]\n            response[\"X-Currency\"] = pricing[\"currency\"]\n            return response\n\n        # Verify payment token\n        with httpx.Client(base_url=GREENHELIX_URL, timeout=10.0) as client:\n            result = client.post(\n                \"\u002Fv1\u002Fpayments\u002Fverify\",\n                json={\n                    \"token\": payment_token,\n                    \"expected_amount\": pricing[\"price_usd\"],\n                    \"endpoint\": request.path,\n                },\n                headers={\"Authorization\": f\"Bearer {GREENHELIX_API_KEY}\"},\n            )\n\n        if result.status_code != 200:\n            return JsonResponse({\"error\": \"payment_invalid\"}, status=402)\n\n        data = result.json()\n        if not data.get(\"verified\"):\n            return JsonResponse({\"error\": \"payment_invalid\"}, status=402)\n\n        request.escrow_id = data.get(\"escrow_id\")\n        request.payment_verified = True\n\n        response = self.get_response(request)\n        response[\"X-Escrow-Id\"] = getattr(request, \"escrow_id\", \"\")\n        response[\"X-Settlement-Status\"] = \"pending\"\n        return response\n```\n\n### Token Verification Caching\n\nPayment verification adds a network round-trip to every agent request. For high-throughput endpoints, this is unacceptable. Implement a short-lived verification cache:\n\n```python\nimport hashlib\nimport time\nfrom typing import Optional\n\n\nclass PaymentVerificationCache:\n    \"\"\"Short-lived cache for payment verification results.\"\"\"\n\n    def __init__(self, ttl_seconds: int = 30):\n        self.ttl = ttl_seconds\n        self._cache: dict[str, tuple[float, dict]] = {}\n\n    def _key(self, token: str, endpoint: str) -> str:\n        return hashlib.sha256(f\"{token}:{endpoint}\".encode()).hexdigest()\n\n    def get(self, token: str, endpoint: str) -> Optional[dict]:\n        key = self._key(token, endpoint)\n        entry = self._cache.get(key)\n        if entry is None:\n            return None\n        timestamp, result = entry\n        if time.time() - timestamp > self.ttl:\n            del self._cache[key]\n            return None\n        return result\n\n    def set(self, token: str, endpoint: str, result: dict) -> None:\n        key = self._key(token, endpoint)\n        self._cache[key] = (time.time(), result)\n\n    def evict_expired(self) -> int:\n        \"\"\"Remove all expired entries. Returns count of evicted entries.\"\"\"\n        now = time.time()\n        expired = [k for k, (ts, _) in self._cache.items() if now - ts > self.ttl]\n        for k in expired:\n            del self._cache[k]\n        return len(expired)\n```\n\nThe cache TTL should be short — 30 seconds is usually sufficient. A payment token verified 30 seconds ago is still valid for the same endpoint. But do not cache across endpoints: a token valid for `\u002Fsearch` is not necessarily valid for `\u002Fanalyze` at a different price point.\n\n---\n\n## Chapter 4: Authentication Bridging\n\nMost REST APIs already have authentication. The migration challenge is not replacing that auth but running agent authentication alongside it. Agents authenticate differently from humans — they use cryptographic key pairs instead of passwords, sign requests instead of presenting session tokens, and identify themselves by public key hash instead of username. Authentication bridging lets both systems coexist.\n\n### The Dual-Auth Architecture\n\nThe bridging architecture has three layers:\n\n**Layer 1: Header inspection.** Every request is classified as human-auth, agent-auth, or unauthenticated based on which headers are present. Human requests carry `Authorization: Bearer \u003Cjwt>` or `X-API-Key`. Agent requests carry `X-Agent-Id`, `X-Agent-Public-Key`, and `X-Agent-Signature`.\n\n**Layer 2: Verification.** Human auth goes through your existing verification pipeline (JWT decode, API key lookup, OAuth token introspection). Agent auth goes through Ed25519 signature verification against the claimed public key, followed by identity resolution against GreenHelix.\n\n**Layer 3: Identity normalization.** Both paths produce a unified identity object that downstream handlers consume. The handler does not know or care whether the caller is human or agent — it gets the same interface.\n\n```python\nimport time\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom typing import Optional\n\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey\nfrom cryptography.hazmat.primitives.serialization import Encoding, PublicFormat\nfrom cryptography.exceptions import InvalidSignature\nimport base64\n\n\nclass AuthMethod(str, Enum):\n    JWT = \"jwt\"\n    API_KEY = \"api_key\"\n    AGENT_SIGNATURE = \"agent_signature\"\n    NONE = \"none\"\n\n\n@dataclass\nclass UnifiedIdentity:\n    \"\"\"Normalized identity produced by either auth path.\"\"\"\n    identity_id: str\n    display_name: str\n    auth_method: AuthMethod\n    is_agent: bool\n    permissions: list[str]\n    tier: str = \"free\"\n    metadata: dict = None\n\n    def __post_init__(self):\n        if self.metadata is None:\n            self.metadata = {}\n\n    def has_permission(self, permission: str) -> bool:\n        return permission in self.permissions or \"*\" in self.permissions\n\n\nclass AuthBridge:\n    \"\"\"\n    Bridges existing human auth with agent Ed25519 auth.\n    Produces a UnifiedIdentity regardless of auth method.\n    \"\"\"\n\n    def __init__(\n        self,\n        jwt_secret: str,\n        api_key_lookup: callable,\n        greenhelix_client: object,\n    ):\n        self.jwt_secret = jwt_secret\n        self.api_key_lookup = api_key_lookup\n        self.greenhelix = greenhelix_client\n\n    async def authenticate(self, request) -> UnifiedIdentity:\n        \"\"\"\n        Authenticate the request using whichever method is present.\n        Raises HTTPException on failure.\n        \"\"\"\n        # Check for agent auth first (more specific headers)\n        agent_id = request.headers.get(\"x-agent-id\")\n        agent_sig = request.headers.get(\"x-agent-signature\")\n        agent_pubkey = request.headers.get(\"x-agent-public-key\")\n\n        if agent_id and agent_sig and agent_pubkey:\n            return await self._authenticate_agent(\n                agent_id, agent_sig, agent_pubkey, request\n            )\n\n        # Check for JWT\n        auth_header = request.headers.get(\"authorization\", \"\")\n        if auth_header.startswith(\"Bearer \"):\n            token = auth_header[7:]\n            return self._authenticate_jwt(token)\n\n        # Check for API key\n        api_key = request.headers.get(\"x-api-key\")\n        if api_key:\n            return self._authenticate_api_key(api_key)\n\n        # No auth provided\n        return UnifiedIdentity(\n            identity_id=\"anonymous\",\n            display_name=\"Anonymous\",\n            auth_method=AuthMethod.NONE,\n            is_agent=False,\n            permissions=[\"read:public\"],\n            tier=\"free\",\n        )\n\n    async def _authenticate_agent(\n        self,\n        agent_id: str,\n        signature_b64: str,\n        public_key_b64: str,\n        request,\n    ) -> UnifiedIdentity:\n        \"\"\"Verify agent Ed25519 signature and resolve identity.\"\"\"\n        # Step 1: Reconstruct the signed payload\n        # The agent signs: METHOD + PATH + TIMESTAMP + BODY_HASH\n        timestamp = request.headers.get(\"x-agent-timestamp\", \"\")\n        body = await request.body()\n        body_hash = hashlib.sha256(body).hexdigest() if body else \"\"\n\n        signed_payload = (\n            f\"{request.method}:{request.url.path}:{timestamp}:{body_hash}\"\n        )\n\n        # Step 2: Verify the Ed25519 signature\n        try:\n            public_key_bytes = base64.b64decode(public_key_b64)\n            signature_bytes = base64.b64decode(signature_b64)\n\n            public_key = Ed25519PublicKey.from_public_key_der(public_key_bytes)\n            public_key.verify(signature_bytes, signed_payload.encode(\"utf-8\"))\n        except (InvalidSignature, ValueError, Exception) as exc:\n            raise HTTPException(\n                status_code=401,\n                detail={\n                    \"error\": \"signature_invalid\",\n                    \"message\": \"Ed25519 signature verification failed\",\n                },\n            )\n\n        # Step 3: Check timestamp freshness (prevent replay attacks)\n        try:\n            req_time = float(timestamp)\n            if abs(time.time() - req_time) > 300:  # 5-minute window\n                raise HTTPException(\n                    status_code=401,\n                    detail={\n                        \"error\": \"timestamp_expired\",\n                        \"message\": \"Request timestamp outside acceptable window\",\n                    },\n                )\n        except (ValueError, TypeError):\n            raise HTTPException(\n                status_code=401,\n                detail={\"error\": \"timestamp_invalid\", \"message\": \"Invalid timestamp format\"},\n            )\n\n        # Step 4: Resolve agent identity from GreenHelix\n        agent_info = await self.greenhelix.resolve_agent(agent_id, public_key_b64)\n\n        return UnifiedIdentity(\n            identity_id=agent_id,\n            display_name=agent_info.get(\"display_name\", agent_id),\n            auth_method=AuthMethod.AGENT_SIGNATURE,\n            is_agent=True,\n            permissions=agent_info.get(\"permissions\", [\"read:public\", \"execute:paid\"]),\n            tier=agent_info.get(\"tier\", \"standard\"),\n            metadata={\n                \"public_key\": public_key_b64,\n                \"reputation_score\": agent_info.get(\"reputation_score\", 0),\n                \"total_transactions\": agent_info.get(\"total_transactions\", 0),\n            },\n        )\n\n    def _authenticate_jwt(self, token: str) -> UnifiedIdentity:\n        \"\"\"Verify JWT and extract identity (existing auth path).\"\"\"\n        import jwt as pyjwt\n\n        try:\n            payload = pyjwt.decode(token, self.jwt_secret, algorithms=[\"HS256\"])\n        except pyjwt.ExpiredSignatureError:\n            raise HTTPException(status_code=401, detail={\"error\": \"token_expired\"})\n        except pyjwt.InvalidTokenError:\n            raise HTTPException(status_code=401, detail={\"error\": \"token_invalid\"})\n\n        return UnifiedIdentity(\n            identity_id=payload[\"sub\"],\n            display_name=payload.get(\"name\", \"\"),\n            auth_method=AuthMethod.JWT,\n            is_agent=False,\n            permissions=payload.get(\"permissions\", [\"read:public\"]),\n            tier=payload.get(\"tier\", \"free\"),\n        )\n\n    def _authenticate_api_key(self, api_key: str) -> UnifiedIdentity:\n        \"\"\"Verify API key and extract identity (existing auth path).\"\"\"\n        key_data = self.api_key_lookup(api_key)\n        if key_data is None:\n            raise HTTPException(status_code=401, detail={\"error\": \"api_key_invalid\"})\n\n        return UnifiedIdentity(\n            identity_id=key_data[\"user_id\"],\n            display_name=key_data.get(\"name\", \"\"),\n            auth_method=AuthMethod.API_KEY,\n            is_agent=False,\n            permissions=key_data.get(\"permissions\", [\"read:public\"]),\n            tier=key_data.get(\"tier\", \"free\"),\n        )\n```\n\n### Using the AuthBridge in FastAPI\n\nIntegrate the bridge as a dependency that replaces your existing auth dependency:\n\n```python\nfrom fastapi import Depends, FastAPI, Request\n\napp = FastAPI()\n\n# Initialize the bridge once at startup\nauth_bridge = AuthBridge(\n    jwt_secret=\"your-jwt-secret\",\n    api_key_lookup=lambda key: db.lookup_api_key(key),\n    greenhelix_client=greenhelix_client,\n)\n\n\nasync def get_identity(request: Request) -> UnifiedIdentity:\n    \"\"\"FastAPI dependency that authenticates via the bridge.\"\"\"\n    return await auth_bridge.authenticate(request)\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fdata\")\nasync def get_data(identity: UnifiedIdentity = Depends(get_identity)):\n    # identity.is_agent tells you the caller type\n    # identity.permissions controls access\n    # identity.tier determines rate limits\n    if not identity.has_permission(\"read:data\"):\n        raise HTTPException(status_code=403, detail=\"Insufficient permissions\")\n\n    return {\"results\": [...], \"caller\": identity.identity_id}\n```\n\n### Session Management for Agents\n\nHuman sessions rely on cookies and server-side state. Agent sessions are stateless by design — each request is independently authenticated. But some APIs have multi-step workflows (start a job, poll for status, download results) that require session continuity. For agents, implement session continuity through idempotency keys and request correlation:\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nimport time\nimport uuid\n\n\n@dataclass\nclass AgentSession:\n    \"\"\"Lightweight session for multi-step agent workflows.\"\"\"\n    session_id: str\n    agent_id: str\n    created_at: float\n    last_activity: float\n    workflow_state: dict = field(default_factory=dict)\n    ttl_seconds: int = 3600\n\n\nclass AgentSessionStore:\n    \"\"\"In-memory session store for agent workflows.\"\"\"\n\n    def __init__(self):\n        self._sessions: dict[str, AgentSession] = {}\n\n    def create(self, agent_id: str) -> AgentSession:\n        session = AgentSession(\n            session_id=str(uuid.uuid4()),\n            agent_id=agent_id,\n            created_at=time.time(),\n            last_activity=time.time(),\n        )\n        self._sessions[session.session_id] = session\n        return session\n\n    def get(self, session_id: str, agent_id: str) -> Optional[AgentSession]:\n        session = self._sessions.get(session_id)\n        if session is None:\n            return None\n        if session.agent_id != agent_id:\n            return None  # Session belongs to a different agent\n        if time.time() - session.last_activity > session.ttl_seconds:\n            del self._sessions[session_id]\n            return None\n        session.last_activity = time.time()\n        return session\n\n    def update_state(self, session_id: str, key: str, value: object) -> None:\n        session = self._sessions.get(session_id)\n        if session:\n            session.workflow_state[key] = value\n            session.last_activity = time.time()\n\n    def cleanup_expired(self) -> int:\n        now = time.time()\n        expired = [\n            sid for sid, s in self._sessions.items()\n            if now - s.last_activity > s.ttl_seconds\n        ]\n        for sid in expired:\n            del self._sessions[sid]\n        return len(expired)\n```\n\nAgents include `X-Session-Id` on follow-up requests. The session ID is returned in the response to the first request in a workflow. This is optional — agents that perform only single-call operations never need sessions.\n\n---\n\n## Chapter 5: Gradual Migration Strategies\n\nBig-bang migrations fail. You do not flip a switch and convert your entire API to agent commerce overnight. Instead, you migrate one endpoint at a time, verify it works, and move to the next. This chapter covers the practical strategies for incremental migration without disrupting existing traffic.\n\n### Endpoint-by-Endpoint Migration\n\nThe migration order matters. Start with read-only endpoints (GET requests), then move to write endpoints (POST\u002FPUT), and finish with complex workflows (multi-step operations). Each endpoint goes through four stages:\n\n```python\nfrom enum import Enum\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n\nclass MigrationStage(str, Enum):\n    LEGACY = \"legacy\"           # No agent support\n    DISCOVERY = \"discovery\"     # Returns 402 with pricing, but doesn't process payments\n    PAYMENT = \"payment\"         # Accepts and verifies payments\n    FULL = \"full\"               # Full agent commerce: payment + identity + response transform\n\n\n@dataclass\nclass EndpointMigrationState:\n    path: str\n    stage: MigrationStage\n    migrated_at: Optional[float] = None\n    migration_notes: str = \"\"\n\n\nclass MigrationRegistry:\n    \"\"\"Tracks which endpoints are at which migration stage.\"\"\"\n\n    def __init__(self):\n        self._endpoints: dict[str, EndpointMigrationState] = {}\n\n    def register(self, path: str, stage: MigrationStage, notes: str = \"\") -> None:\n        self._endpoints[path] = EndpointMigrationState(\n            path=path,\n            stage=stage,\n            migrated_at=time.time() if stage != MigrationStage.LEGACY else None,\n            migration_notes=notes,\n        )\n\n    def get_stage(self, path: str) -> MigrationStage:\n        state = self._endpoints.get(path)\n        return state.stage if state else MigrationStage.LEGACY\n\n    def advance(self, path: str) -> MigrationStage:\n        \"\"\"Move an endpoint to the next migration stage.\"\"\"\n        current = self.get_stage(path)\n        stages = list(MigrationStage)\n        current_index = stages.index(current)\n        if current_index \u003C len(stages) - 1:\n            new_stage = stages[current_index + 1]\n            self.register(path, new_stage)\n            return new_stage\n        return current\n\n    def summary(self) -> dict[str, int]:\n        counts = {stage.value: 0 for stage in MigrationStage}\n        for state in self._endpoints.values():\n            counts[state.stage.value] += 1\n        return counts\n\n\n# Usage\nregistry = MigrationRegistry()\nregistry.register(\"\u002Fapi\u002Fv1\u002Fsearch\", MigrationStage.FULL)\nregistry.register(\"\u002Fapi\u002Fv1\u002Fanalyze\", MigrationStage.PAYMENT)\nregistry.register(\"\u002Fapi\u002Fv1\u002Fusers\", MigrationStage.LEGACY)\n\nprint(registry.summary())\n# {'legacy': 1, 'discovery': 0, 'payment': 1, 'full': 1}\n```\n\nThe discovery stage is critical and often skipped. At this stage, the endpoint returns 402 with correct pricing headers when an agent hits it, but does not actually process payments. This lets agents discover your pricing and capabilities without you needing to handle real money yet. Run in discovery mode for at least a week to see what agents query your API, what prices they encounter, and how they react.\n\n### Feature Flags for Agent Commerce\n\nFeature flags let you enable and disable agent commerce per endpoint, per agent, or globally without deploying new code:\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nimport json\nimport os\n\n\n@dataclass\nclass AgentCommerceFlags:\n    \"\"\"Feature flags controlling agent commerce behavior.\"\"\"\n    global_enabled: bool = True\n    payment_required: bool = True\n    identity_verification: bool = True\n    response_transformation: bool = True\n    allowed_agent_ids: list[str] = field(default_factory=list)  # Empty = allow all\n    blocked_agent_ids: list[str] = field(default_factory=list)\n    endpoint_overrides: dict[str, dict] = field(default_factory=dict)\n\n    @classmethod\n    def from_env(cls) -> \"AgentCommerceFlags\":\n        \"\"\"Load flags from environment variables or config file.\"\"\"\n        config_path = os.getenv(\"AGENT_COMMERCE_CONFIG\", \"agent_commerce_flags.json\")\n        if os.path.exists(config_path):\n            with open(config_path) as f:\n                data = json.load(f)\n            return cls(**data)\n        return cls(\n            global_enabled=os.getenv(\"AGENT_COMMERCE_ENABLED\", \"true\").lower() == \"true\",\n            payment_required=os.getenv(\"AGENT_PAYMENT_REQUIRED\", \"true\").lower() == \"true\",\n        )\n\n    def is_enabled_for(self, endpoint: str, agent_id: Optional[str] = None) -> bool:\n        \"\"\"Check if agent commerce is enabled for a specific endpoint and agent.\"\"\"\n        if not self.global_enabled:\n            return False\n\n        if agent_id and agent_id in self.blocked_agent_ids:\n            return False\n\n        if self.allowed_agent_ids and agent_id not in self.allowed_agent_ids:\n            return False\n\n        override = self.endpoint_overrides.get(endpoint, {})\n        return override.get(\"enabled\", True)\n\n    def get_price_override(self, endpoint: str) -> Optional[str]:\n        \"\"\"Get endpoint-specific price override, if any.\"\"\"\n        override = self.endpoint_overrides.get(endpoint, {})\n        return override.get(\"price_usd\")\n```\n\n### Traffic Routing with Reverse Proxy\n\nFor APIs running behind nginx or a similar reverse proxy, you can route agent traffic to a separate upstream that has the commerce middleware enabled, while human traffic hits the original upstream unchanged:\n\n```nginx\n# nginx.conf — agent traffic routing\n\nupstream legacy_api {\n    server 127.0.0.1:8000;\n}\n\nupstream agent_commerce_api {\n    server 127.0.0.1:8001;\n}\n\nmap $http_x_agent_id $is_agent {\n    default 0;\n    \"~.+\" 1;\n}\n\nmap $http_x_402_payment_token $has_payment {\n    default 0;\n    \"~.+\" 1;\n}\n\nserver {\n    listen 443 ssl;\n    server_name api.example.com;\n\n    location \u002Fapi\u002Fv1\u002F {\n        # Route to agent commerce API if agent headers are present\n        if ($is_agent) {\n            proxy_pass http:\u002F\u002Fagent_commerce_api;\n            break;\n        }\n        if ($has_payment) {\n            proxy_pass http:\u002F\u002Fagent_commerce_api;\n            break;\n        }\n\n        # Default: route to legacy API\n        proxy_pass http:\u002F\u002Flegacy_api;\n    }\n}\n```\n\nThis approach lets you run the agent commerce version of your API as a separate process. The legacy API process remains completely untouched. If anything goes wrong with agent commerce, you adjust the nginx config to route all traffic back to the legacy upstream. Zero-downtime rollback.\n\n### A\u002FB Testing Human vs Agent Traffic\n\nTrack metrics separately for human and agent callers to detect regressions:\n\n```python\nimport time\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\n\n\n@dataclass\nclass TrafficMetrics:\n    request_count: int = 0\n    error_count: int = 0\n    total_latency_ms: float = 0.0\n    p95_latencies: list[float] = field(default_factory=list)\n\n    @property\n    def avg_latency_ms(self) -> float:\n        if self.request_count == 0:\n            return 0.0\n        return self.total_latency_ms \u002F self.request_count\n\n    @property\n    def error_rate(self) -> float:\n        if self.request_count == 0:\n            return 0.0\n        return self.error_count \u002F self.request_count\n\n\nclass MigrationMetricsCollector:\n    \"\"\"Collects metrics split by caller type for migration monitoring.\"\"\"\n\n    def __init__(self):\n        self._metrics: dict[str, dict[str, TrafficMetrics]] = defaultdict(\n            lambda: {\"human\": TrafficMetrics(), \"agent\": TrafficMetrics()}\n        )\n\n    def record(\n        self,\n        endpoint: str,\n        caller_type: str,\n        latency_ms: float,\n        is_error: bool = False,\n    ) -> None:\n        metrics = self._metrics[endpoint][caller_type]\n        metrics.request_count += 1\n        metrics.total_latency_ms += latency_ms\n        metrics.p95_latencies.append(latency_ms)\n        if is_error:\n            metrics.error_count += 1\n\n        # Keep only last 1000 latencies for p95 calculation\n        if len(metrics.p95_latencies) > 1000:\n            metrics.p95_latencies = metrics.p95_latencies[-1000:]\n\n    def compare(self, endpoint: str) -> dict:\n        \"\"\"Compare human vs agent metrics for an endpoint.\"\"\"\n        human = self._metrics[endpoint][\"human\"]\n        agent = self._metrics[endpoint][\"agent\"]\n        return {\n            \"endpoint\": endpoint,\n            \"human\": {\n                \"requests\": human.request_count,\n                \"avg_latency_ms\": round(human.avg_latency_ms, 2),\n                \"error_rate\": round(human.error_rate, 4),\n            },\n            \"agent\": {\n                \"requests\": agent.request_count,\n                \"avg_latency_ms\": round(agent.avg_latency_ms, 2),\n                \"error_rate\": round(agent.error_rate, 4),\n            },\n            \"latency_delta_ms\": round(agent.avg_latency_ms - human.avg_latency_ms, 2),\n        }\n```\n\nThe `latency_delta_ms` is the key metric during migration. If agent requests are significantly slower than human requests at the same endpoint, the commerce middleware is adding too much overhead. The target is under 50ms of additional latency for the payment verification and response transformation layer.\n\n---\n\n## Chapter 6: MigrationValidator Class\n\nMigration validation answers one question: does the migrated endpoint behave identically to the original for all non-commerce concerns? The business logic should produce the same output, the response schemas should be compatible, and performance should not degrade beyond acceptable bounds. The `MigrationValidator` automates these checks.\n\n### The Validator Architecture\n\nThe validator works by sending the same request to both the legacy endpoint and the migrated endpoint, then comparing the responses. For endpoints that have already replaced the legacy version (same URL, new middleware), it compares captured legacy response snapshots against live migrated responses.\n\n```python\nimport json\nimport time\nimport hashlib\nfrom dataclasses import dataclass, field\nfrom typing import Any, Optional\nfrom enum import Enum\n\nimport httpx\n\n\nclass ValidationResult(str, Enum):\n    PASS = \"pass\"\n    FAIL = \"fail\"\n    WARN = \"warn\"\n\n\n@dataclass\nclass ValidationReport:\n    endpoint: str\n    result: ValidationResult\n    checks: list[dict] = field(default_factory=list)\n    duration_ms: float = 0.0\n    timestamp: float = field(default_factory=time.time)\n\n    def add_check(self, name: str, result: ValidationResult, detail: str = \"\") -> None:\n        self.checks.append({\n            \"name\": name,\n            \"result\": result.value,\n            \"detail\": detail,\n        })\n        # Overall result is the worst individual result\n        if result == ValidationResult.FAIL:\n            self.result = ValidationResult.FAIL\n        elif result == ValidationResult.WARN and self.result != ValidationResult.FAIL:\n            self.result = ValidationResult.WARN\n\n    @property\n    def passed(self) -> bool:\n        return self.result != ValidationResult.FAIL\n\n    def summary(self) -> str:\n        total = len(self.checks)\n        passed = sum(1 for c in self.checks if c[\"result\"] == \"pass\")\n        return f\"{self.endpoint}: {passed}\u002F{total} checks passed ({self.result.value})\"\n\n\n@dataclass\nclass ResponseSnapshot:\n    \"\"\"Captured response for comparison.\"\"\"\n    status_code: int\n    headers: dict[str, str]\n    body: Any\n    latency_ms: float\n    captured_at: float = field(default_factory=time.time)\n\n    def body_hash(self) -> str:\n        return hashlib.sha256(json.dumps(self.body, sort_keys=True).encode()).hexdigest()\n\n\nclass MigrationValidator:\n    \"\"\"\n    Validates that migrated endpoints preserve original behavior.\n\n    Compares response schemas, status codes, data content, and\n    performance between legacy and migrated versions.\n    \"\"\"\n\n    def __init__(\n        self,\n        legacy_base_url: str,\n        migrated_base_url: str,\n        tolerance_ms: float = 100.0,\n        schema_strict: bool = False,\n    ):\n        self.legacy_url = legacy_base_url.rstrip(\"\u002F\")\n        self.migrated_url = migrated_base_url.rstrip(\"\u002F\")\n        self.tolerance_ms = tolerance_ms\n        self.schema_strict = schema_strict\n        self._client = httpx.AsyncClient(timeout=30.0)\n        self._snapshots: dict[str, list[ResponseSnapshot]] = {}\n\n    async def capture_legacy_snapshot(\n        self, endpoint: str, method: str = \"GET\", body: Any = None, headers: dict = None,\n    ) -> ResponseSnapshot:\n        \"\"\"Capture a response from the legacy endpoint for later comparison.\"\"\"\n        request_headers = headers or {}\n        start = time.time()\n\n        if method.upper() == \"GET\":\n            response = await self._client.get(\n                f\"{self.legacy_url}{endpoint}\", headers=request_headers\n            )\n        else:\n            response = await self._client.request(\n                method, f\"{self.legacy_url}{endpoint}\",\n                json=body, headers=request_headers,\n            )\n\n        latency_ms = (time.time() - start) * 1000\n\n        snapshot = ResponseSnapshot(\n            status_code=response.status_code,\n            headers=dict(response.headers),\n            body=response.json() if response.headers.get(\"content-type\", \"\").startswith(\"application\u002Fjson\") else response.text,\n            latency_ms=latency_ms,\n        )\n\n        if endpoint not in self._snapshots:\n            self._snapshots[endpoint] = []\n        self._snapshots[endpoint].append(snapshot)\n\n        return snapshot\n\n    async def validate_endpoint(\n        self,\n        endpoint: str,\n        method: str = \"GET\",\n        body: Any = None,\n        human_headers: dict = None,\n        agent_headers: dict = None,\n    ) -> ValidationReport:\n        \"\"\"Run full validation suite on a migrated endpoint.\"\"\"\n        report = ValidationReport(endpoint=endpoint, result=ValidationResult.PASS)\n        start = time.time()\n\n        # Test 1: Human request produces same response as legacy\n        human_headers = human_headers or {}\n        try:\n            legacy_resp = await self._request(self.legacy_url, endpoint, method, body, human_headers)\n            migrated_resp = await self._request(self.migrated_url, endpoint, method, body, human_headers)\n\n            self._check_status_code(report, legacy_resp, migrated_resp)\n            self._check_schema_compatibility(report, legacy_resp, migrated_resp)\n            self._check_data_equivalence(report, legacy_resp, migrated_resp)\n        except httpx.RequestError as exc:\n            report.add_check(\"connectivity\", ValidationResult.FAIL, str(exc))\n            report.duration_ms = (time.time() - start) * 1000\n            return report\n\n        # Test 2: Agent request without payment returns 402\n        if agent_headers:\n            agent_no_payment = {k: v for k, v in agent_headers.items() if k.lower() != \"x-402-payment-token\"}\n            try:\n                agent_resp = await self._request(\n                    self.migrated_url, endpoint, method, body, agent_no_payment\n                )\n                if agent_resp.status_code == 402:\n                    report.add_check(\"402_response\", ValidationResult.PASS, \"Returns 402 for unpaid agent requests\")\n                    self._check_402_headers(report, agent_resp)\n                else:\n                    report.add_check(\n                        \"402_response\", ValidationResult.WARN,\n                        f\"Expected 402, got {agent_resp.status_code}\",\n                    )\n            except httpx.RequestError as exc:\n                report.add_check(\"agent_request\", ValidationResult.FAIL, str(exc))\n\n        # Test 3: Performance regression check\n        await self._check_performance(report, endpoint, method, body, human_headers)\n\n        report.duration_ms = (time.time() - start) * 1000\n        return report\n\n    async def _request(\n        self, base_url: str, endpoint: str, method: str, body: Any, headers: dict,\n    ) -> httpx.Response:\n        if method.upper() == \"GET\":\n            return await self._client.get(f\"{base_url}{endpoint}\", headers=headers)\n        return await self._client.request(\n            method, f\"{base_url}{endpoint}\", json=body, headers=headers\n        )\n\n    def _check_status_code(\n        self, report: ValidationReport, legacy: httpx.Response, migrated: httpx.Response,\n    ) -> None:\n        if legacy.status_code == migrated.status_code:\n            report.add_check(\"status_code\", ValidationResult.PASS)\n        else:\n            report.add_check(\n                \"status_code\", ValidationResult.FAIL,\n                f\"Legacy returned {legacy.status_code}, migrated returned {migrated.status_code}\",\n            )\n\n    def _check_schema_compatibility(\n        self, report: ValidationReport, legacy: httpx.Response, migrated: httpx.Response,\n    ) -> None:\n        \"\"\"Compare response structure (keys at each level).\"\"\"\n        try:\n            legacy_body = legacy.json()\n            migrated_body = migrated.json()\n        except (json.JSONDecodeError, ValueError):\n            report.add_check(\"schema\", ValidationResult.WARN, \"Could not parse response as JSON\")\n            return\n\n        legacy_keys = self._extract_keys(legacy_body)\n        migrated_keys = self._extract_keys(migrated_body)\n\n        missing = legacy_keys - migrated_keys\n        added = migrated_keys - legacy_keys\n\n        if not missing and not added:\n            report.add_check(\"schema\", ValidationResult.PASS)\n        elif missing:\n            report.add_check(\n                \"schema\", ValidationResult.FAIL,\n                f\"Missing keys in migrated response: {missing}\",\n            )\n        elif added and self.schema_strict:\n            report.add_check(\n                \"schema\", ValidationResult.FAIL,\n                f\"Unexpected keys in migrated response: {added}\",\n            )\n        else:\n            report.add_check(\n                \"schema\", ValidationResult.WARN,\n                f\"New keys in migrated response: {added}\",\n            )\n\n    def _check_data_equivalence(\n        self, report: ValidationReport, legacy: httpx.Response, migrated: httpx.Response,\n    ) -> None:\n        \"\"\"Check that the actual data values match.\"\"\"\n        try:\n            legacy_body = legacy.json()\n            migrated_body = migrated.json()\n        except (json.JSONDecodeError, ValueError):\n            return\n\n        # If migrated response wraps data in an envelope, unwrap it\n        if isinstance(migrated_body, dict) and \"data\" in migrated_body and \"meta\" in migrated_body:\n            migrated_body = migrated_body[\"data\"]\n\n        legacy_hash = hashlib.sha256(json.dumps(legacy_body, sort_keys=True).encode()).hexdigest()\n        migrated_hash = hashlib.sha256(json.dumps(migrated_body, sort_keys=True).encode()).hexdigest()\n\n        if legacy_hash == migrated_hash:\n            report.add_check(\"data_equivalence\", ValidationResult.PASS)\n        else:\n            report.add_check(\n                \"data_equivalence\", ValidationResult.WARN,\n                \"Response data differs (may be expected for dynamic fields like timestamps)\",\n            )\n\n    def _check_402_headers(self, report: ValidationReport, response: httpx.Response) -> None:\n        \"\"\"Verify that 402 responses include required negotiation headers.\"\"\"\n        required_headers = [\"x-price\", \"x-currency\", \"x-payment-url\"]\n        missing = [h for h in required_headers if h not in response.headers]\n\n        if not missing:\n            report.add_check(\"402_headers\", ValidationResult.PASS)\n        else:\n            report.add_check(\n                \"402_headers\", ValidationResult.FAIL,\n                f\"Missing 402 headers: {missing}\",\n            )\n\n    async def _check_performance(\n        self, report: ValidationReport, endpoint: str, method: str, body: Any, headers: dict,\n    ) -> None:\n        \"\"\"Check that migration hasn't introduced unacceptable latency.\"\"\"\n        # Run 5 requests against each and compare average\n        legacy_latencies = []\n        migrated_latencies = []\n\n        for _ in range(5):\n            start = time.time()\n            await self._request(self.legacy_url, endpoint, method, body, headers)\n            legacy_latencies.append((time.time() - start) * 1000)\n\n            start = time.time()\n            await self._request(self.migrated_url, endpoint, method, body, headers)\n            migrated_latencies.append((time.time() - start) * 1000)\n\n        avg_legacy = sum(legacy_latencies) \u002F len(legacy_latencies)\n        avg_migrated = sum(migrated_latencies) \u002F len(migrated_latencies)\n        delta = avg_migrated - avg_legacy\n\n        if delta \u003C= self.tolerance_ms:\n            report.add_check(\n                \"performance\", ValidationResult.PASS,\n                f\"Latency delta: {delta:.1f}ms (within {self.tolerance_ms}ms tolerance)\",\n            )\n        elif delta \u003C= self.tolerance_ms * 2:\n            report.add_check(\n                \"performance\", ValidationResult.WARN,\n                f\"Latency delta: {delta:.1f}ms (approaching tolerance of {self.tolerance_ms}ms)\",\n            )\n        else:\n            report.add_check(\n                \"performance\", ValidationResult.FAIL,\n                f\"Latency delta: {delta:.1f}ms (exceeds tolerance of {self.tolerance_ms}ms)\",\n            )\n\n    def _extract_keys(self, obj: Any, prefix: str = \"\") -> set[str]:\n        \"\"\"Recursively extract all key paths from a JSON object.\"\"\"\n        keys = set()\n        if isinstance(obj, dict):\n            for k, v in obj.items():\n                full_key = f\"{prefix}.{k}\" if prefix else k\n                keys.add(full_key)\n                keys.update(self._extract_keys(v, full_key))\n        elif isinstance(obj, list) and obj:\n            keys.update(self._extract_keys(obj[0], f\"{prefix}[]\"))\n        return keys\n\n    async def close(self):\n        await self._client.aclose()\n```\n\n### Running Validation\n\nRun the validator as part of your CI pipeline or as a standalone validation script:\n\n```python\nimport asyncio\n\n\nasync def validate_migration():\n    validator = MigrationValidator(\n        legacy_base_url=\"http:\u002F\u002Flocalhost:8000\",\n        migrated_base_url=\"http:\u002F\u002Flocalhost:8001\",\n        tolerance_ms=50.0,\n    )\n\n    endpoints_to_validate = [\n        {\n            \"endpoint\": \"\u002Fapi\u002Fv1\u002Fsearch\",\n            \"method\": \"GET\",\n            \"human_headers\": {\"Authorization\": \"Bearer test-jwt-token\"},\n            \"agent_headers\": {\"X-Agent-Id\": \"test-agent-001\"},\n        },\n        {\n            \"endpoint\": \"\u002Fapi\u002Fv1\u002Fanalyze\",\n            \"method\": \"POST\",\n            \"body\": {\"text\": \"sample input for validation\"},\n            \"human_headers\": {\"Authorization\": \"Bearer test-jwt-token\"},\n            \"agent_headers\": {\"X-Agent-Id\": \"test-agent-001\"},\n        },\n    ]\n\n    reports = []\n    for ep in endpoints_to_validate:\n        report = await validator.validate_endpoint(**ep)\n        reports.append(report)\n        print(report.summary())\n        for check in report.checks:\n            status = \"OK\" if check[\"result\"] == \"pass\" else check[\"result\"].upper()\n            detail = f\" - {check['detail']}\" if check[\"detail\"] else \"\"\n            print(f\"  [{status}] {check['name']}{detail}\")\n\n    await validator.close()\n\n    # Fail CI if any endpoint fails validation\n    all_passed = all(r.passed for r in reports)\n    if not all_passed:\n        print(\"\\nMigration validation FAILED\")\n        exit(1)\n    else:\n        print(\"\\nAll migration validations passed\")\n\n\nasyncio.run(validate_migration())\n```\n\n### Contract Testing Between Old and New\n\nBeyond schema comparison, contract tests verify specific response invariants that your API consumers depend on. Define these contracts explicitly:\n\n```python\n@dataclass\nclass ResponseContract:\n    \"\"\"Defines expected properties of a response that must not change during migration.\"\"\"\n    endpoint: str\n    status_code: int\n    required_fields: list[str]\n    field_types: dict[str, type]\n    value_constraints: dict[str, callable]  # field -> validator function\n\n    def validate(self, response_body: dict) -> list[str]:\n        \"\"\"Returns list of contract violations.\"\"\"\n        violations = []\n\n        for field_path in self.required_fields:\n            if not self._has_field(response_body, field_path):\n                violations.append(f\"Missing required field: {field_path}\")\n\n        for field_path, expected_type in self.field_types.items():\n            value = self._get_field(response_body, field_path)\n            if value is not None and not isinstance(value, expected_type):\n                violations.append(\n                    f\"Type mismatch for {field_path}: expected {expected_type.__name__}, \"\n                    f\"got {type(value).__name__}\"\n                )\n\n        for field_path, validator in self.value_constraints.items():\n            value = self._get_field(response_body, field_path)\n            if value is not None and not validator(value):\n                violations.append(f\"Value constraint failed for {field_path}: {value}\")\n\n        return violations\n\n    def _has_field(self, obj: dict, path: str) -> bool:\n        parts = path.split(\".\")\n        current = obj\n        for part in parts:\n            if isinstance(current, dict) and part in current:\n                current = current[part]\n            else:\n                return False\n        return True\n\n    def _get_field(self, obj: dict, path: str) -> Any:\n        parts = path.split(\".\")\n        current = obj\n        for part in parts:\n            if isinstance(current, dict) and part in current:\n                current = current[part]\n            else:\n                return None\n        return current\n\n\n# Example contract definition\nsearch_contract = ResponseContract(\n    endpoint=\"\u002Fapi\u002Fv1\u002Fsearch\",\n    status_code=200,\n    required_fields=[\"results\", \"total_count\"],\n    field_types={\n        \"results\": list,\n        \"total_count\": int,\n    },\n    value_constraints={\n        \"total_count\": lambda v: v >= 0,\n    },\n)\n```\n\n---\n\n## Chapter 7: Testing Migration\n\nTesting a migration is not the same as testing new code. You are not verifying that something works — you are verifying that it works the same way it did before, plus new capabilities. The testing strategy has three phases: pre-migration baseline capture, parallel validation during migration, and post-migration regression testing.\n\n### Phase 1: Baseline Capture\n\nBefore touching any code, capture baseline responses for every endpoint you plan to migrate. These baselines become the ground truth for comparison:\n\n```python\nimport json\nimport time\nimport os\nfrom dataclasses import dataclass, asdict\nfrom typing import Any\n\nimport httpx\n\n\n@dataclass\nclass BaselineCapture:\n    endpoint: str\n    method: str\n    request_body: Any\n    response_status: int\n    response_body: Any\n    response_headers: dict[str, str]\n    latency_ms: float\n    captured_at: float\n\n\nclass BaselineRecorder:\n    \"\"\"Records baseline API responses for migration comparison.\"\"\"\n\n    def __init__(self, base_url: str, output_dir: str = \".\u002Fmigration_baselines\"):\n        self.base_url = base_url.rstrip(\"\u002F\")\n        self.output_dir = output_dir\n        os.makedirs(output_dir, exist_ok=True)\n\n    async def capture(\n        self, endpoint: str, method: str = \"GET\", body: Any = None,\n        headers: dict = None, iterations: int = 10,\n    ) -> list[BaselineCapture]:\n        \"\"\"Capture multiple baseline responses for statistical comparison.\"\"\"\n        captures = []\n        async with httpx.AsyncClient(timeout=30.0) as client:\n            for _ in range(iterations):\n                start = time.time()\n                if method.upper() == \"GET\":\n                    resp = await client.get(\n                        f\"{self.base_url}{endpoint}\", headers=headers or {}\n                    )\n                else:\n                    resp = await client.request(\n                        method, f\"{self.base_url}{endpoint}\",\n                        json=body, headers=headers or {},\n                    )\n                latency = (time.time() - start) * 1000\n\n                try:\n                    resp_body = resp.json()\n                except ValueError:\n                    resp_body = resp.text\n\n                capture = BaselineCapture(\n                    endpoint=endpoint,\n                    method=method,\n                    request_body=body,\n                    response_status=resp.status_code,\n                    response_body=resp_body,\n                    response_headers=dict(resp.headers),\n                    latency_ms=latency,\n                    captured_at=time.time(),\n                )\n                captures.append(capture)\n\n        # Save to disk\n        filename = endpoint.replace(\"\u002F\", \"_\").strip(\"_\") + \".json\"\n        filepath = os.path.join(self.output_dir, filename)\n        with open(filepath, \"w\") as f:\n            json.dump([asdict(c) for c in captures], f, indent=2, default=str)\n\n        return captures\n```\n\nRun the baseline recorder against every endpoint in your migration list. Store the output in version control. These files serve as regression evidence — if something breaks during migration, you have concrete proof of what the correct behavior was.\n\n### Phase 2: Shadow Traffic Validation\n\nShadow traffic sends a copy of every real production request to the migrated endpoint and compares responses without affecting the actual client. The client gets the legacy response, but the migrated response is captured and compared asynchronously:\n\n```python\nimport asyncio\nimport time\nimport json\nimport logging\nfrom typing import Any\n\nimport httpx\n\nlogger = logging.getLogger(\"shadow_traffic\")\n\n\nclass ShadowTrafficValidator:\n    \"\"\"\n    Replays production traffic against migrated endpoints.\n    Compares responses without affecting production clients.\n    \"\"\"\n\n    def __init__(\n        self,\n        migrated_base_url: str,\n        mismatch_log: str = \".\u002Fshadow_mismatches.jsonl\",\n    ):\n        self.migrated_url = migrated_base_url.rstrip(\"\u002F\")\n        self.mismatch_log = mismatch_log\n        self._client = httpx.AsyncClient(timeout=10.0)\n        self._stats = {\"total\": 0, \"matched\": 0, \"mismatched\": 0, \"errors\": 0}\n\n    async def shadow_request(\n        self,\n        endpoint: str,\n        method: str,\n        body: Any,\n        headers: dict,\n        legacy_status: int,\n        legacy_body: Any,\n    ) -> None:\n        \"\"\"Send shadow request and compare with legacy response.\"\"\"\n        self._stats[\"total\"] += 1\n\n        # Remove auth headers that might not work against the migrated version\n        shadow_headers = {\n            k: v for k, v in headers.items()\n            if k.lower() not in (\"cookie\", \"x-csrf-token\")\n        }\n\n        try:\n            start = time.time()\n            if method.upper() == \"GET\":\n                resp = await self._client.get(\n                    f\"{self.migrated_url}{endpoint}\", headers=shadow_headers\n                )\n            else:\n                resp = await self._client.request(\n                    method, f\"{self.migrated_url}{endpoint}\",\n                    json=body, headers=shadow_headers,\n                )\n            latency = (time.time() - start) * 1000\n\n            # Compare status codes\n            if resp.status_code != legacy_status:\n                self._log_mismatch(endpoint, \"status_code\", legacy_status, resp.status_code)\n                self._stats[\"mismatched\"] += 1\n                return\n\n            # Compare response bodies (ignoring dynamic fields)\n            try:\n                migrated_body = resp.json()\n                if not self._bodies_equivalent(legacy_body, migrated_body):\n                    self._log_mismatch(endpoint, \"body\", legacy_body, migrated_body)\n                    self._stats[\"mismatched\"] += 1\n                    return\n            except (json.JSONDecodeError, ValueError):\n                pass\n\n            self._stats[\"matched\"] += 1\n\n        except Exception as exc:\n            self._stats[\"errors\"] += 1\n            logger.error(f\"Shadow request failed for {endpoint}: {exc}\")\n\n    def _bodies_equivalent(self, legacy: Any, migrated: Any) -> bool:\n        \"\"\"Compare bodies, ignoring known dynamic fields.\"\"\"\n        dynamic_fields = {\"timestamp\", \"request_id\", \"trace_id\", \"generated_at\"}\n\n        if isinstance(legacy, dict) and isinstance(migrated, dict):\n            # If migrated wraps in envelope, unwrap\n            if \"data\" in migrated and \"meta\" in migrated:\n                migrated = migrated[\"data\"]\n\n            for key in set(legacy.keys()) | set(migrated.keys()):\n                if key in dynamic_fields:\n                    continue\n                if key not in legacy or key not in migrated:\n                    return False\n                if not self._bodies_equivalent(legacy[key], migrated[key]):\n                    return False\n            return True\n\n        if isinstance(legacy, list) and isinstance(migrated, list):\n            if len(legacy) != len(migrated):\n                return False\n            return all(\n                self._bodies_equivalent(a, b) for a, b in zip(legacy, migrated)\n            )\n\n        return legacy == migrated\n\n    def _log_mismatch(\n        self, endpoint: str, field: str, expected: Any, actual: Any,\n    ) -> None:\n        entry = {\n            \"timestamp\": time.time(),\n            \"endpoint\": endpoint,\n            \"field\": field,\n            \"expected\": str(expected)[:500],\n            \"actual\": str(actual)[:500],\n        }\n        with open(self.mismatch_log, \"a\") as f:\n            f.write(json.dumps(entry) + \"\\n\")\n\n    @property\n    def match_rate(self) -> float:\n        if self._stats[\"total\"] == 0:\n            return 0.0\n        return self._stats[\"matched\"] \u002F self._stats[\"total\"]\n\n    async def close(self):\n        await self._client.aclose()\n```\n\nIntegrate shadow validation into your production middleware. After the legacy handler returns a response to the client, fire off the shadow request asynchronously:\n\n```python\nimport asyncio\nfrom fastapi import Request, Response\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\nshadow_validator = ShadowTrafficValidator(migrated_base_url=\"http:\u002F\u002Flocalhost:8001\")\n\n\nclass ShadowTrafficMiddleware(BaseHTTPMiddleware):\n    async def dispatch(self, request: Request, call_next) -> Response:\n        # Process request normally\n        body = await request.body()\n        response = await call_next(request)\n\n        # Fire shadow request in background (don't block the response)\n        try:\n            resp_body = json.loads(response.body) if hasattr(response, \"body\") else None\n        except (json.JSONDecodeError, ValueError):\n            resp_body = None\n\n        asyncio.create_task(\n            shadow_validator.shadow_request(\n                endpoint=request.url.path,\n                method=request.method,\n                body=json.loads(body) if body else None,\n                headers=dict(request.headers),\n                legacy_status=response.status_code,\n                legacy_body=resp_body,\n            )\n        )\n\n        return response\n```\n\n### Rollback Procedures\n\nEvery migration needs a rollback plan. Document rollback steps for each migration stage:\n\n**Stage 1 rollback (Discovery).** Remove the `wrap_endpoint` decorator or disable the middleware via feature flag. No data to clean up — discovery mode does not create escrows or process payments.\n\n**Stage 2 rollback (Payment).** Disable payment verification in the feature flags. Any in-flight escrows will expire and refund automatically after the settlement timeout. Communicate the maintenance window to agent consumers via your A2A protocol card status field.\n\n**Stage 3 rollback (Full).** Revert to the pre-migration code deployment. If using the reverse proxy routing approach, switch the nginx config to route all traffic to the legacy upstream. Agent sessions in progress will fail — this is acceptable because agent sessions are designed to be retryable.\n\n### Monitoring During Migration\n\nSet up alerts for these conditions during each migration phase:\n\n```python\nMIGRATION_ALERTS = {\n    \"error_rate_spike\": {\n        \"condition\": \"error_rate > baseline_error_rate * 1.5\",\n        \"action\": \"Pause migration, investigate\",\n        \"severity\": \"high\",\n    },\n    \"latency_regression\": {\n        \"condition\": \"p95_latency > baseline_p95 + 100ms\",\n        \"action\": \"Check payment verification service health\",\n        \"severity\": \"medium\",\n    },\n    \"402_misconfiguration\": {\n        \"condition\": \"402_responses_for_human_callers > 0\",\n        \"action\": \"Immediate rollback — caller classification is broken\",\n        \"severity\": \"critical\",\n    },\n    \"shadow_mismatch_rate\": {\n        \"condition\": \"shadow_match_rate \u003C 0.95\",\n        \"action\": \"Stop migration, review mismatches\",\n        \"severity\": \"high\",\n    },\n    \"payment_verification_timeout\": {\n        \"condition\": \"payment_verification_p95 > 5000ms\",\n        \"action\": \"Enable verification cache, check GreenHelix status\",\n        \"severity\": \"medium\",\n    },\n}\n```\n\nThe most critical alert is `402_misconfiguration`. If human callers ever receive a 402 response, the caller classification logic is broken and the migration must be rolled back immediately. This is the one failure mode that directly impacts existing users.\n\n---\n\n## Chapter 8: Performance Comparison\n\nAdding a commerce layer to your API adds latency. The question is how much and whether it matters. This chapter provides the benchmarking framework to measure the exact overhead and the optimization strategies to minimize it.\n\n### Benchmarking Framework\n\n```python\nimport asyncio\nimport time\nimport statistics\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nimport httpx\n\n\n@dataclass\nclass BenchmarkResult:\n    endpoint: str\n    variant: str  # \"legacy\" or \"migrated\"\n    requests: int\n    avg_latency_ms: float\n    p50_latency_ms: float\n    p95_latency_ms: float\n    p99_latency_ms: float\n    min_latency_ms: float\n    max_latency_ms: float\n    error_count: int\n    throughput_rps: float\n\n\nclass MigrationBenchmark:\n    \"\"\"Benchmarks legacy vs migrated endpoint performance.\"\"\"\n\n    def __init__(\n        self,\n        legacy_url: str,\n        migrated_url: str,\n        concurrency: int = 10,\n        duration_seconds: int = 30,\n    ):\n        self.legacy_url = legacy_url.rstrip(\"\u002F\")\n        self.migrated_url = migrated_url.rstrip(\"\u002F\")\n        self.concurrency = concurrency\n        self.duration = duration_seconds\n\n    async def run(\n        self,\n        endpoint: str,\n        method: str = \"GET\",\n        body: object = None,\n        headers: dict = None,\n    ) -> dict[str, BenchmarkResult]:\n        \"\"\"Run benchmark against both legacy and migrated endpoints.\"\"\"\n        legacy_result = await self._benchmark_variant(\n            self.legacy_url, endpoint, method, body, headers or {}, \"legacy\"\n        )\n        migrated_result = await self._benchmark_variant(\n            self.migrated_url, endpoint, method, body, headers or {}, \"migrated\"\n        )\n\n        return {\n            \"legacy\": legacy_result,\n            \"migrated\": migrated_result,\n            \"overhead_ms\": migrated_result.avg_latency_ms - legacy_result.avg_latency_ms,\n            \"overhead_pct\": (\n                (migrated_result.avg_latency_ms - legacy_result.avg_latency_ms)\n                \u002F legacy_result.avg_latency_ms * 100\n                if legacy_result.avg_latency_ms > 0 else 0\n            ),\n            \"throughput_delta_rps\": (\n                migrated_result.throughput_rps - legacy_result.throughput_rps\n            ),\n        }\n\n    async def _benchmark_variant(\n        self,\n        base_url: str,\n        endpoint: str,\n        method: str,\n        body: object,\n        headers: dict,\n        variant: str,\n    ) -> BenchmarkResult:\n        latencies: list[float] = []\n        errors = 0\n        start_time = time.time()\n\n        async def worker():\n            nonlocal errors\n            async with httpx.AsyncClient(timeout=30.0) as client:\n                while time.time() - start_time \u003C self.duration:\n                    req_start = time.time()\n                    try:\n                        if method.upper() == \"GET\":\n                            resp = await client.get(\n                                f\"{base_url}{endpoint}\", headers=headers\n                            )\n                        else:\n                            resp = await client.request(\n                                method, f\"{base_url}{endpoint}\",\n                                json=body, headers=headers,\n                            )\n                        latency = (time.time() - req_start) * 1000\n                        latencies.append(latency)\n                        if resp.status_code >= 500:\n                            errors += 1\n                    except Exception:\n                        errors += 1\n\n        workers = [asyncio.create_task(worker()) for _ in range(self.concurrency)]\n        await asyncio.gather(*workers)\n\n        total_time = time.time() - start_time\n\n        if not latencies:\n            return BenchmarkResult(\n                endpoint=endpoint, variant=variant, requests=0,\n                avg_latency_ms=0, p50_latency_ms=0, p95_latency_ms=0,\n                p99_latency_ms=0, min_latency_ms=0, max_latency_ms=0,\n                error_count=errors, throughput_rps=0,\n            )\n\n        sorted_latencies = sorted(latencies)\n        p50_idx = int(len(sorted_latencies) * 0.50)\n        p95_idx = int(len(sorted_latencies) * 0.95)\n        p99_idx = int(len(sorted_latencies) * 0.99)\n\n        return BenchmarkResult(\n            endpoint=endpoint,\n            variant=variant,\n            requests=len(latencies),\n            avg_latency_ms=round(statistics.mean(latencies), 2),\n            p50_latency_ms=round(sorted_latencies[p50_idx], 2),\n            p95_latency_ms=round(sorted_latencies[p95_idx], 2),\n            p99_latency_ms=round(sorted_latencies[min(p99_idx, len(sorted_latencies) - 1)], 2),\n            min_latency_ms=round(sorted_latencies[0], 2),\n            max_latency_ms=round(sorted_latencies[-1], 2),\n            error_count=errors,\n            throughput_rps=round(len(latencies) \u002F total_time, 2),\n        )\n```\n\n### Understanding the Latency Breakdown\n\nThe commerce layer adds latency at four points:\n\n1. **Caller classification** (\u003C 1ms): Header inspection and string matching. Negligible.\n\n2. **Payment verification** (10-100ms): Network call to GreenHelix to verify the payment token. This is the dominant cost. With the verification cache enabled, repeat requests from the same agent with the same token skip this call entirely, reducing it to \u003C 1ms.\n\n3. **Identity verification** (5-50ms): Ed25519 signature verification is a local CPU operation (\u003C 1ms), but resolving the agent identity against GreenHelix adds a network call. Cache agent identity lookups for 5 minutes to amortize this cost.\n\n4. **Response transformation** (\u003C 1ms): JSON wrapping is a memory operation. Even for large responses (1MB+), the transformation adds under 1ms.\n\nThe total expected overhead for a cache-miss agent request is 15-150ms, dominated by payment and identity verification network calls. With warm caches, the overhead drops to 1-3ms.\n\n### Optimization Strategies\n\n**Connection pooling.** The `httpx.AsyncClient` used for GreenHelix communication should be a long-lived singleton with connection pooling enabled. Creating a new HTTP client per request adds 50-100ms of connection setup overhead:\n\n```python\n# Bad: new client per request\nasync def verify_payment(token):\n    async with httpx.AsyncClient() as client:  # Connection setup every time\n        return await client.post(...)\n\n# Good: shared client with connection pool\n_greenhelix_client = httpx.AsyncClient(\n    base_url=\"https:\u002F\u002Fapi.greenhelix.net\",\n    timeout=10.0,\n    limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),\n)\n\nasync def verify_payment(token):\n    return await _greenhelix_client.post(...)  # Reuses connections\n```\n\n**Batch verification.** If your API serves requests in bursts (common with agent orchestration patterns where one agent dispatches multiple sub-tasks), batch multiple payment verifications into a single GreenHelix API call:\n\n```python\nasync def verify_payments_batch(tokens: list[dict]) -> list[dict]:\n    \"\"\"Verify multiple payment tokens in one API call.\"\"\"\n    response = await _greenhelix_client.post(\n        \"\u002Fv1\u002Fpayments\u002Fverify-batch\",\n        json={\"tokens\": tokens},\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n    )\n    return response.json()[\"results\"]\n```\n\n**Preemptive caching.** Agents that frequently call the same endpoint can be given a bulk payment token that covers N future requests. The verification cache stores the token with a remaining-uses counter instead of a simple boolean:\n\n```python\n@dataclass\nclass BulkTokenEntry:\n    token: str\n    remaining_uses: int\n    endpoint: str\n    verified_at: float\n    ttl_seconds: int = 3600\n\n    @property\n    def is_valid(self) -> bool:\n        return self.remaining_uses > 0 and time.time() - self.verified_at \u003C self.ttl_seconds\n\n    def consume(self) -> bool:\n        if not self.is_valid:\n            return False\n        self.remaining_uses -= 1\n        return True\n```\n\n**Async settlement.** Payment settlement (releasing escrow funds to the seller) does not need to happen before the response is sent. Verify the token synchronously, send the response, then settle asynchronously. This removes settlement latency from the request path entirely:\n\n```python\nasync def handle_agent_request(request: Request):\n    # Verify payment (synchronous, blocks response)\n    payment = await verify_payment(request.headers[\"x-402-payment-token\"])\n\n    # Process business logic\n    result = await business_logic(request)\n\n    # Settle payment (asynchronous, does not block response)\n    asyncio.create_task(settle_payment(payment[\"escrow_id\"]))\n\n    return result\n```\n\n### Throughput Considerations\n\nAgent traffic patterns differ from human traffic. Humans send requests with natural pauses (reading, clicking, thinking). Agents send bursts of requests as fast as the API can respond. Your API might handle 100 requests per second from human users comfortably but struggle at 1000 requests per second from agents, even though the per-request processing time is the same. The bottleneck shifts from business logic to the commerce layer — specifically, the connection pool to GreenHelix for payment verification.\n\nSize your connection pool based on expected agent throughput. A pool of 20 keepalive connections to GreenHelix can handle approximately 200 verification requests per second (assuming 100ms average verification time). For higher throughput, increase the pool or enable the verification cache aggressively.\n\nMonitor these throughput metrics during migration:\n\n- Requests per second by caller type (human vs agent)\n- GreenHelix verification latency (p50, p95, p99)\n- Connection pool utilization (active vs idle connections)\n- Cache hit rate for payment verification\n- Queue depth if you implement request queuing\n\n---\n\n## What's Next\n\nYou now have a complete framework for migrating any REST API to support agent commerce. The `LegacyApiAdapter` wraps your existing endpoints without modifying business logic. The x402 middleware handles payment negotiation at the HTTP layer. The `AuthBridge` runs agent Ed25519 authentication alongside your existing auth system. The `MigrationValidator` automates regression testing throughout the migration. And the benchmarking framework quantifies the exact performance cost of each component.\n\nThe migration order should be:\n\n1. Run the assessment checklist on your API.\n2. Deploy the `LegacyApiAdapter` in discovery mode (402 responses, no payment processing) on your highest-value read endpoints.\n3. Monitor agent traffic patterns for one to two weeks.\n4. Enable payment processing on the endpoints where agents are actually sending requests.\n5. Roll out identity verification.\n6. Migrate the remaining endpoints based on observed demand.\n7. Run the `MigrationValidator` continuously in CI.\n\nThe GreenHelix platform documentation at [https:\u002F\u002Fdocs.greenhelix.net](https:\u002F\u002Fdocs.greenhelix.net) covers escrow API details, A2A protocol card registration, and agent identity management. The x402 specification at [https:\u002F\u002Fwww.x402.org](https:\u002F\u002Fwww.x402.org) defines the full payment header protocol.\n\nStart with one endpoint. Prove it works. Then migrate the rest.\n\n",{"name":5,"tags":24,"type":29,"author":33,"install":34,"license":15,"version":35,"metadata":36,"price_usd":42,"executable":20,"credentials":43,"description":7,"content_type":44,"compatibility":45},[25,26,27,28,29,30,31,32],"migration","rest-api","retrofit","x402","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":37},{"requires":38,"primaryEnv":40},{"env":39},[40,41],"GREENHELIX_API_KEY","AGENT_SIGNING_KEY",39,[40,41],"markdown",[31],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-commerce-migration",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":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-commerce-migration",{"tool":61,"command":62},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-commerce-migration",{"tool":64,"command":65},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-commerce-migration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-commerce-migration\u002FSKILL.md",true,[],[70,77,84,91,98,105],{"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},"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":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},"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":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},"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":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},"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":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},"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":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"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",[],[]]