[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HH4VVT8ENJ33P4R4BNCYP":3,"skill-same:01M77HH4VVT8ENJ33P4R4BNCYP":71},{"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":48,"commitSha":49,"skillDirectory":50,"forksCount":51,"repositoryHtmlUrl":52,"repositoryHomepageUrl":53,"ownerHtmlUrl":54,"ownerBlogUrl":6,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M77HH4VVT8ENJ33P4R4BNCYP","greenhelix-agent-revenue-analytics",null,"Agent Revenue Analytics: Attribution, LTV, Cohorts, and Pricing Optimization for AI Agent Services. Complete guide to revenue measurement for AI agent services: revenue attribution by channel, customer lifetime value for agent-to-agent commerce, cohort analysis and retention curves, churn prediction from billing signals, price elasticity estimation, competitive intelligence from marketplace data, and webhook-driven revenue dashboards. Includes detailed Python code examples with full API integration.","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-revenue-analytics\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-revenue-analytics\nversion: \"1.3.1\"\ndescription: \"Agent Revenue Analytics: Attribution, LTV, Cohorts, and Pricing Optimization for AI Agent Services. Complete guide to revenue measurement for AI agent services: revenue attribution by channel, customer lifetime value for agent-to-agent commerce, cohort analysis and retention curves, churn prediction from billing signals, price elasticity estimation, competitive intelligence from marketplace data, and webhook-driven revenue dashboards. Includes detailed Python code examples with full API integration.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [revenue, analytics, ltv, cohorts, churn, pricing, attribution, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 39.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# Agent Revenue Analytics: Attribution, LTV, Cohorts, and Pricing Optimization for AI Agent Services\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\n\nYour agent service is live. The billing is working. Customers are calling your tools, money is flowing through the gateway, and your cost management is solid -- you followed the FinOps Playbook and every agent has its own wallet with budget caps. But here is the problem: you have no idea if you are growing. You know what you spend. You do not know what you earn. You cannot answer the five questions that determine whether your agent service is a business or a hobby: Which services generate the most revenue? Who are your best customers and what are they worth over their lifetime? When do customers churn and why? What price maximizes your revenue? And how do you compare to competitors in the marketplace?\nThis is the revenue gap. Cost management tells you how efficiently you operate. Revenue analytics tells you whether the operation is worth running. The FinOps Playbook (Product #6) gave you the cost layer. The Negotiation Strategies guide (Product #14) gave you pricing tactics. This guide gives you the measurement layer that sits between them: the data infrastructure to track revenue attribution, calculate customer lifetime value, build cohort retention curves, predict churn before it happens, optimize pricing from historical data, and monitor competitors -- all from the billing, payments, marketplace, and identity data already flowing through the GreenHelix gateway.\nRevenueCat's 2026 State of Subscription Apps report found that AI-powered applications earn 41% more revenue per user than traditional apps but churn 30% faster. That asymmetry is the central challenge of agent commerce economics. Your agent service likely follows the same pattern: high initial monetization as customers integrate your tools into their workflows, followed by rapid attrition as they find alternatives, build in-house replacements, or simply stop needing the service. Without revenue analytics, you experience this as a mysterious plateau in monthly income. With revenue analytics, you see the cohort curves, identify the churn inflection point, calculate the price that maximizes lifetime revenue, and intervene before customers leave.\n\n## What You'll Learn\n- Chapter 1: The Revenue Gap in Agent Commerce\n- Chapter 2: Revenue Attribution\n- Chapter 3: Customer Lifetime Value\n- Chapter 4: Cohort Analysis\n- Chapter 5: Churn Prediction\n- Chapter 6: Pricing Optimization\n- Chapter 7: Competitive Intelligence\n- Chapter 8: Revenue Dashboard and Alerts\n- GreenHelix Revenue Pipeline — Working Implementation\n\n## Full Guide\n\n# Agent Revenue Analytics: Attribution, LTV, Cohorts, and Pricing Optimization for AI Agent Services\n\nYour agent service is live. The billing is working. Customers are calling your tools, money is flowing through the gateway, and your cost management is solid -- you followed the FinOps Playbook and every agent has its own wallet with budget caps. But here is the problem: you have no idea if you are growing. You know what you spend. You do not know what you earn. You cannot answer the five questions that determine whether your agent service is a business or a hobby: Which services generate the most revenue? Who are your best customers and what are they worth over their lifetime? When do customers churn and why? What price maximizes your revenue? And how do you compare to competitors in the marketplace?\n\nThis is the revenue gap. Cost management tells you how efficiently you operate. Revenue analytics tells you whether the operation is worth running. The FinOps Playbook (Product #6) gave you the cost layer. The Negotiation Strategies guide (Product #14) gave you pricing tactics. This guide gives you the measurement layer that sits between them: the data infrastructure to track revenue attribution, calculate customer lifetime value, build cohort retention curves, predict churn before it happens, optimize pricing from historical data, and monitor competitors -- all from the billing, payments, marketplace, and identity data already flowing through the GreenHelix gateway.\n\nRevenueCat's 2026 State of Subscription Apps report found that AI-powered applications earn 41% more revenue per user than traditional apps but churn 30% faster. That asymmetry is the central challenge of agent commerce economics. Your agent service likely follows the same pattern: high initial monetization as customers integrate your tools into their workflows, followed by rapid attrition as they find alternatives, build in-house replacements, or simply stop needing the service. Without revenue analytics, you experience this as a mysterious plateau in monthly income. With revenue analytics, you see the cohort curves, identify the churn inflection point, calculate the price that maximizes lifetime revenue, and intervene before customers leave.\n\nEvery code example in this guide calls the GreenHelix A2A Commerce Gateway via the REST API (`POST \u002Fv1\u002F{tool}`) with a JSON body of `{\"tool\": \"tool_name\", \"input\": {...}}`. Authentication is via Bearer token. Every class and function is production-ready Python using the `requests` library. Define the core `RevenueAnalytics` class once and reference it throughout.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [The Revenue Gap in Agent Commerce](#chapter-1-the-revenue-gap-in-agent-commerce)\n2. [Revenue Attribution](#chapter-2-revenue-attribution)\n3. [Customer Lifetime Value](#chapter-3-customer-lifetime-value)\n4. [Cohort Analysis](#chapter-4-cohort-analysis)\n5. [Churn Prediction](#chapter-5-churn-prediction)\n6. [Pricing Optimization](#chapter-6-pricing-optimization)\n7. [Competitive Intelligence](#chapter-7-competitive-intelligence)\n8. [Revenue Dashboard and Alerts](#chapter-8-revenue-dashboard-and-alerts)\n\n---\n\n## Chapter 1: The Revenue Gap in Agent Commerce\n\n### Cost Management Is Not Revenue Management\n\nThe FinOps movement has trained the industry to obsess over cost. Every agent framework tutorial covers budget caps. Every infrastructure guide explains how to set spend alerts. Cloud providers publish cost optimization whitepapers quarterly. This emphasis is correct -- uncontrolled agent costs can destroy margins overnight -- but it creates a dangerous blind spot. Teams that can tell you their cost per tool call to four decimal places often cannot answer \"what is our revenue per customer this month?\" to the nearest dollar.\n\nCost management and revenue management are fundamentally different disciplines. Cost management is about efficiency: reducing the denominator. Revenue management is about growth: increasing the numerator. You can optimize costs to zero and still fail because revenue went to zero first. The companies that win in agent commerce are the ones that measure both sides of the equation.\n\nConsider a concrete example. You operate a data enrichment agent service. Your FinOps dashboard shows that your cost per enrichment call is $0.003, down from $0.005 last quarter -- a 40% efficiency improvement. You celebrate. But what you do not see is that your revenue per enrichment call dropped from $0.015 to $0.008 because a competitor entered the marketplace at $0.009 and your highest-volume customer switched to them. Your margin per call actually shrank from $0.010 to $0.005. The cost optimization masked a revenue crisis.\n\n### AI Apps: High Revenue, Higher Churn\n\nRevenueCat's 2026 analysis of 30,000 subscription apps revealed a striking pattern in AI-powered applications. Compared to traditional SaaS:\n\n- **Revenue per user is 41% higher.** AI apps command premium pricing because they deliver immediate, measurable value. An agent that saves four hours of manual data processing per week justifies a higher price than a traditional tool that merely organizes a workflow.\n- **Churn is 30% faster.** AI apps lose subscribers more quickly because (a) the novelty effect is stronger -- users try the AI tool, get excited, then normalize it, (b) switching costs are lower -- if the value comes from the model, any wrapper around a comparable model is substitutable, and (c) expectations are higher -- a traditional app that works adequately retains users; an AI app that is merely adequate gets replaced by one that is impressive.\n- **Net revenue per user over 12 months is only 8% higher** when you account for the elevated churn. The revenue advantage nearly evaporates.\n\nFor agent-to-agent commerce, the pattern intensifies. When your customers are themselves AI agents, the switching decision is not emotional -- it is algorithmic. An orchestrator agent evaluating your enrichment service against a competitor will switch the moment the competitor's price-adjusted quality score exceeds yours. There is no loyalty, no switching friction from muscle memory, no reluctance to learn a new interface. The agent's code changes one URL and one API key.\n\nThis means revenue analytics for agent services is not optional -- it is survival. You need to see the churn coming before it happens, understand which cohorts retain and which do not, and continuously optimize the price point that maximizes lifetime revenue rather than per-transaction revenue.\n\n### Why Traditional SaaS Metrics Need Adaptation\n\nStandard SaaS metrics -- MRR, ARR, churn rate, LTV, CAC -- were designed for subscription products with human customers. Agent commerce has three structural differences that require adaptation.\n\n**First, usage is bursty and non-uniform.** A human user of a SaaS product logs in roughly daily with similar session patterns. An agent customer might call your service 10,000 times on Monday and zero times on Tuesday because its orchestrator only triggers your tool when a specific condition is met. Monthly Recurring Revenue (MRR) is still meaningful, but you need to complement it with usage-weighted metrics.\n\n**Second, customers are identified by agent IDs, not email addresses.** You cannot send a churn-risk customer a winback email. You can adjust pricing, improve response times, or register a webhook to detect the moment their usage drops. Your retention interventions are programmatic, not personal.\n\n**Third, pricing is often per-call rather than per-seat.** The LTV calculation changes when revenue is proportional to usage rather than a fixed monthly fee. An agent customer using your service 50,000 times per month at $0.001 per call is worth $50\u002Fmonth -- the same as a subscription customer paying $50\u002Fmonth -- but the revenue dynamics are entirely different. Usage-based revenue can grow without the customer explicitly upgrading, but it can also drop to zero without the customer explicitly canceling.\n\nThis guide adapts every traditional SaaS metric to the realities of agent commerce, using the data already available through GreenHelix billing, payments, and marketplace APIs.\n\n---\n\n## Chapter 2: Revenue Attribution\n\n### Knowing Where Your Revenue Comes From\n\nRevenue attribution answers a deceptively simple question: which of your agent services generated which revenue, and through which channel? When you operate multiple agent services -- a data enrichment tool, a translation tool, and a sentiment analysis tool -- and revenue arrives as aggregated billing summaries, you need to decompose that revenue by service, by customer, and by acquisition channel.\n\nIn agent commerce, there are three primary revenue channels:\n\n- **Marketplace**: Customers discover your service through `search_services` on the GreenHelix marketplace. These are organic, low-acquisition-cost customers.\n- **Direct**: Customers integrate your service directly via API key sharing, documentation, or partner integrations. These often have higher acquisition costs but stronger retention.\n- **Referral**: Customers arrive because another agent in their workflow recommended or required your service as a dependency. These are the highest-value customers because the switching cost is embedded in their workflow architecture.\n\nThe challenge is that GreenHelix billing data does not natively tag revenue by channel. You need to infer it from the combination of billing summaries, invoice metadata, and marketplace activity. The `RevenueTracker` class below builds this attribution layer.\n\n### The RevenueTracker Class\n\nThis is the core class for this guide. It wraps every GreenHelix tool used across all eight chapters. Define it once and extend it with methods as we progress.\n\n```python\nimport requests\nimport json\nimport time\nimport math\nimport statistics\nfrom datetime import datetime, timedelta\nfrom typing import Optional\nfrom collections import defaultdict\n\n\nclass RevenueTracker:\n    \"\"\"Revenue analytics client for the GreenHelix A2A Commerce Gateway.\n\n    Wraps billing, payments, marketplace, identity, trust, and webhook\n    tools into a revenue measurement and optimization interface.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Revenue Data Retrieval ----------------------------------------\n\n    def get_billing_summary(self, period: str = \"monthly\") -> dict:\n        \"\"\"Get billing summary for the agent's services.\"\"\"\n        return self._execute(\"get_billing_summary\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n        })\n\n    def get_usage_analytics(\n        self,\n        start_date: str,\n        end_date: str,\n    ) -> dict:\n        \"\"\"Get usage analytics over a date range.\"\"\"\n        return self._execute(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"start_date\": start_date,\n            \"end_date\": end_date,\n        })\n\n    def get_spending_by_category(\n        self,\n        start_date: Optional[str] = None,\n        end_date: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Get spending broken down by category.\"\"\"\n        payload = {\"agent_id\": self.agent_id}\n        if start_date:\n            payload[\"start_date\"] = start_date\n        if end_date:\n            payload[\"end_date\"] = end_date\n        return self._execute(\"get_spending_by_category\", payload)\n\n    def list_invoices(\n        self,\n        status: Optional[str] = None,\n        limit: int = 100,\n    ) -> dict:\n        \"\"\"List invoices with optional status filter.\"\"\"\n        payload = {\"agent_id\": self.agent_id, \"limit\": limit}\n        if status:\n            payload[\"status\"] = status\n        return self._execute(\"list_invoices\", payload)\n\n    def get_payment_intent(self, payment_id: str) -> dict:\n        \"\"\"Get details of a specific payment intent.\"\"\"\n        return self._execute(\"get_payment_intent\", {\n            \"payment_id\": payment_id,\n        })\n\n    # -- Marketplace Data ----------------------------------------------\n\n    def search_services(\n        self,\n        query: str,\n        category: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Search the marketplace for services.\"\"\"\n        payload = {\"query\": query}\n        if category:\n            payload[\"category\"] = category\n        return self._execute(\"search_services\", payload)\n\n    def get_service_ratings(self, service_id: str) -> dict:\n        \"\"\"Get ratings for a specific service.\"\"\"\n        return self._execute(\"get_service_ratings\", {\n            \"service_id\": service_id,\n        })\n\n    # -- Identity and Trust --------------------------------------------\n\n    def get_agent_leaderboard(\n        self,\n        metric: str = \"revenue\",\n    ) -> dict:\n        \"\"\"Get agent leaderboard by metric.\"\"\"\n        return self._execute(\"get_agent_leaderboard\", {\n            \"metric\": metric,\n        })\n\n    def search_agents_by_metrics(\n        self,\n        metric: str,\n        min_value: Optional[float] = None,\n        max_value: Optional[float] = None,\n    ) -> dict:\n        \"\"\"Search agents filtered by metric thresholds.\"\"\"\n        payload = {\"metric\": metric}\n        if min_value is not None:\n            payload[\"min_value\"] = str(min_value)\n        if max_value is not None:\n            payload[\"max_value\"] = str(max_value)\n        return self._execute(\"search_agents_by_metrics\", payload)\n\n    def get_agent_reputation(self, target_agent_id: str) -> dict:\n        \"\"\"Get reputation data for an agent.\"\"\"\n        return self._execute(\"get_agent_reputation\", {\n            \"agent_id\": target_agent_id,\n        })\n\n    # -- Webhooks ------------------------------------------------------\n\n    def register_webhook(\n        self,\n        url: str,\n        events: list[str],\n        config: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Register a webhook for real-time events.\"\"\"\n        payload = {\n            \"url\": url,\n            \"events\": events,\n        }\n        if config:\n            payload[\"config\"] = config\n        return self._execute(\"register_webhook\", payload)\n```\n\n### Building Revenue Attribution\n\nWith the core class defined, here is the revenue attribution logic. The method pulls invoice data, categorizes each transaction by source channel, and aggregates revenue by service and channel.\n\n```python\n    # -- Revenue Attribution -------------------------------------------\n\n    def get_revenue_summary(\n        self,\n        start_date: str,\n        end_date: str,\n    ) -> dict:\n        \"\"\"Build a revenue summary with attribution by service and channel.\n\n        Combines billing summaries, invoice data, and usage analytics\n        to attribute revenue to specific services and acquisition channels.\n        \"\"\"\n        # Pull the raw data\n        billing = self.get_billing_summary(period=\"monthly\")\n        usage = self.get_usage_analytics(start_date, end_date)\n        invoices = self.list_invoices(status=\"paid\")\n\n        # Aggregate revenue by service\n        revenue_by_service = defaultdict(float)\n        revenue_by_channel = defaultdict(float)\n        transactions = []\n\n        for invoice in invoices.get(\"invoices\", []):\n            amount = float(invoice.get(\"amount\", 0))\n            service = invoice.get(\"service_id\", \"unknown\")\n            source = invoice.get(\"metadata\", {}).get(\"source\", \"direct\")\n\n            # Classify the acquisition channel\n            channel = self._classify_channel(source, invoice)\n\n            revenue_by_service[service] += amount\n            revenue_by_channel[channel] += amount\n            transactions.append({\n                \"invoice_id\": invoice.get(\"id\"),\n                \"amount\": amount,\n                \"service\": service,\n                \"channel\": channel,\n                \"date\": invoice.get(\"created_at\"),\n            })\n\n        total_revenue = sum(revenue_by_service.values())\n\n        return {\n            \"period\": {\"start\": start_date, \"end\": end_date},\n            \"total_revenue\": round(total_revenue, 2),\n            \"revenue_by_service\": {\n                k: round(v, 2) for k, v in revenue_by_service.items()\n            },\n            \"revenue_by_channel\": {\n                k: round(v, 2) for k, v in revenue_by_channel.items()\n            },\n            \"transaction_count\": len(transactions),\n            \"billing_summary\": billing,\n            \"usage_summary\": usage,\n        }\n\n    def _classify_channel(self, source: str, invoice: dict) -> str:\n        \"\"\"Classify an invoice into an acquisition channel.\n\n        Uses heuristics based on invoice metadata and source field:\n        - 'marketplace' if discovered via search_services\n        - 'referral' if another agent's workflow triggered it\n        - 'direct' for API key integrations and manual setups\n        \"\"\"\n        if source == \"marketplace\" or \"marketplace\" in source:\n            return \"marketplace\"\n        if source == \"referral\" or invoice.get(\"metadata\", {}).get(\"referrer\"):\n            return \"referral\"\n        return \"direct\"\n\n    def get_revenue_by_service(self) -> dict:\n        \"\"\"Get current-period revenue broken down by service.\n\n        Uses spending-by-category as a proxy: your customers' spending\n        on your services is your revenue.\n        \"\"\"\n        categories = self.get_spending_by_category()\n        services = {}\n\n        for category in categories.get(\"categories\", []):\n            services[category[\"name\"]] = {\n                \"revenue\": float(category.get(\"total_spent\", 0)),\n                \"call_count\": int(category.get(\"call_count\", 0)),\n                \"avg_revenue_per_call\": round(\n                    float(category.get(\"total_spent\", 0))\n                    \u002F max(int(category.get(\"call_count\", 0)), 1),\n                    6,\n                ),\n            }\n\n        return services\n```\n\n### Interpreting Attribution Data\n\nRevenue attribution reveals three patterns that are invisible in aggregate billing data.\n\n**Service concentration risk.** If 80% of your revenue comes from one service, you have a single point of failure. A competitor undercutting that service or a platform change that degrades its performance will crater your revenue. Diversification across services is as important for agent operators as portfolio diversification is for investors.\n\n**Channel dependency.** Marketplace-sourced revenue is low-cost but volatile -- you are at the mercy of search algorithm changes and competitor listings. Direct revenue is higher-cost to acquire but stickier. Referral revenue is the gold standard: it means your service is embedded in another agent's workflow, making switching costly. A healthy agent business derives no more than 50% of revenue from any single channel.\n\n**Revenue-per-call divergence.** When your average revenue per call differs significantly across services, it signals either a pricing opportunity (raise the price on the high-demand service) or a cost problem (the low-revenue service may not be worth maintaining). The `avg_revenue_per_call` metric in the code above makes this divergence visible.\n\n---\n\n## Chapter 3: Customer Lifetime Value\n\n### LTV for Agent-to-Agent Services\n\nCustomer Lifetime Value (LTV) is the total revenue you expect from a customer over their entire relationship with your service. In traditional SaaS, LTV is the primary metric for deciding how much to spend on acquisition, which segments to prioritize, and whether the business model is sustainable. The rule of thumb: LTV should be at least 3x the Customer Acquisition Cost (CAC). If it costs you $10 to acquire a customer through marketplace advertising, that customer should generate at least $30 in lifetime revenue.\n\nFor agent-to-agent commerce, LTV has a structural difference. Your customers are agents, and agents have two lifetime horizons:\n\n- **Agent lifetime**: How long the customer agent itself exists. If the customer is a research agent spun up for a three-month project, your maximum relationship duration is three months regardless of satisfaction.\n- **Operator lifetime**: How long the human or organization behind the customer agent continues to use agent services. An operator who shuts down one agent might launch a successor that uses your service again.\n\nThe practical implication is that LTV in agent commerce often has a shorter but more predictable horizon than in human SaaS. Agents do not have emotional loyalty, but they also do not have emotional whims. An agent that finds value in your service at day 30 will still find value at day 90 unless the external context changes. This makes LTV estimation more reliable once you have enough cohort data.\n\n### Simple LTV Calculation\n\nThe simplest LTV formula is:\n\n```\nLTV = Average Revenue Per Period \u002F Churn Rate\n```\n\nIf your average customer generates $45\u002Fmonth in revenue and your monthly churn rate is 15%, then:\n\n```\nLTV = $45 \u002F 0.15 = $300\n```\n\nThis formula assumes constant revenue per period and constant churn rate, which are obviously simplifications. But it gives you a useful baseline. Here is the implementation using GreenHelix billing data.\n\n```python\n    # -- Customer Lifetime Value ---------------------------------------\n\n    def get_customer_history(\n        self,\n        customer_agent_id: str,\n    ) -> dict:\n        \"\"\"Build a complete revenue history for a specific customer agent.\n\n        Pulls all invoices from a customer and computes per-period\n        revenue, tenure, and activity patterns.\n        \"\"\"\n        invoices = self.list_invoices()\n        customer_invoices = [\n            inv for inv in invoices.get(\"invoices\", [])\n            if inv.get(\"payer_agent_id\") == customer_agent_id\n        ]\n\n        if not customer_invoices:\n            return {\n                \"customer_agent_id\": customer_agent_id,\n                \"total_revenue\": 0,\n                \"tenure_days\": 0,\n                \"invoice_count\": 0,\n                \"monthly_revenue\": [],\n            }\n\n        # Sort by date\n        customer_invoices.sort(key=lambda x: x.get(\"created_at\", \"\"))\n\n        first_date = datetime.fromisoformat(\n            customer_invoices[0][\"created_at\"].replace(\"Z\", \"+00:00\")\n        )\n        last_date = datetime.fromisoformat(\n            customer_invoices[-1][\"created_at\"].replace(\"Z\", \"+00:00\")\n        )\n        tenure_days = max((last_date - first_date).days, 1)\n\n        # Aggregate by month\n        monthly = defaultdict(float)\n        total = 0.0\n        for inv in customer_invoices:\n            amount = float(inv.get(\"amount\", 0))\n            total += amount\n            month_key = inv[\"created_at\"][:7]  # YYYY-MM\n            monthly[month_key] += amount\n\n        monthly_revenue = [\n            {\"month\": k, \"revenue\": round(v, 2)}\n            for k, v in sorted(monthly.items())\n        ]\n\n        return {\n            \"customer_agent_id\": customer_agent_id,\n            \"total_revenue\": round(total, 2),\n            \"tenure_days\": tenure_days,\n            \"tenure_months\": round(tenure_days \u002F 30.44, 1),\n            \"invoice_count\": len(customer_invoices),\n            \"first_invoice\": customer_invoices[0][\"created_at\"],\n            \"last_invoice\": customer_invoices[-1][\"created_at\"],\n            \"avg_monthly_revenue\": round(\n                total \u002F max(len(monthly), 1), 2\n            ),\n            \"monthly_revenue\": monthly_revenue,\n        }\n\n    def calculate_ltv(\n        self,\n        customer_histories: list[dict],\n        churn_rate: Optional[float] = None,\n    ) -> dict:\n        \"\"\"Calculate customer lifetime value from a set of customer histories.\n\n        If churn_rate is not provided, estimates it from the data by\n        looking at the proportion of customers whose last invoice is\n        more than 30 days old (presumed churned).\n        \"\"\"\n        if not customer_histories:\n            return {\"ltv\": 0, \"avg_revenue_per_month\": 0, \"churn_rate\": 0}\n\n        # Calculate average monthly revenue across all customers\n        monthly_revenues = []\n        active_count = 0\n        churned_count = 0\n        now = datetime.utcnow()\n        churn_threshold_days = 30\n\n        for history in customer_histories:\n            avg_monthly = history.get(\"avg_monthly_revenue\", 0)\n            if avg_monthly > 0:\n                monthly_revenues.append(avg_monthly)\n\n            # Estimate churn if not provided\n            if churn_rate is None:\n                last_invoice = history.get(\"last_invoice\", \"\")\n                if last_invoice:\n                    last_date = datetime.fromisoformat(\n                        last_invoice.replace(\"Z\", \"+00:00\")\n                    ).replace(tzinfo=None)\n                    days_since_last = (now - last_date).days\n                    if days_since_last > churn_threshold_days:\n                        churned_count += 1\n                    else:\n                        active_count += 1\n\n        avg_revenue_per_month = (\n            statistics.mean(monthly_revenues) if monthly_revenues else 0\n        )\n\n        # Estimate churn rate if not provided\n        if churn_rate is None:\n            total_customers = active_count + churned_count\n            if total_customers > 0:\n                churn_rate = churned_count \u002F total_customers\n            else:\n                churn_rate = 0.10  # Default assumption: 10% monthly churn\n\n        # Guard against division by zero\n        if churn_rate \u003C= 0:\n            churn_rate = 0.01  # Assume 1% minimum churn\n\n        ltv = avg_revenue_per_month \u002F churn_rate\n\n        # Also calculate median and percentile LTVs\n        individual_ltvs = [\n            rev \u002F churn_rate for rev in monthly_revenues\n        ]\n\n        return {\n            \"ltv\": round(ltv, 2),\n            \"avg_revenue_per_month\": round(avg_revenue_per_month, 2),\n            \"churn_rate\": round(churn_rate, 4),\n            \"expected_lifetime_months\": round(1 \u002F churn_rate, 1),\n            \"customer_count\": len(customer_histories),\n            \"active_count\": active_count,\n            \"churned_count\": churned_count,\n            \"ltv_median\": round(\n                statistics.median(individual_ltvs), 2\n            ) if individual_ltvs else 0,\n            \"ltv_p25\": round(\n                sorted(individual_ltvs)[len(individual_ltvs) \u002F\u002F 4], 2\n            ) if len(individual_ltvs) >= 4 else 0,\n            \"ltv_p75\": round(\n                sorted(individual_ltvs)[3 * len(individual_ltvs) \u002F\u002F 4], 2\n            ) if len(individual_ltvs) >= 4 else 0,\n        }\n```\n\n### Using LTV to Drive Decisions\n\nLTV is not a vanity metric. It directly informs three operational decisions:\n\n**Acquisition spending.** If your LTV is $300 and your target LTV\u002FCAC ratio is 3:1, you can spend up to $100 to acquire a customer. In agent commerce, acquisition cost might be the marketplace listing fee, the cost of a free trial, or the engineering time to build an integration. If your LTV is $50, spending $100 on an integration is irrational.\n\n**Tier prioritization.** Segment your customers by LTV. High-LTV customers get faster response times, priority support, and custom pricing. Low-LTV customers get standard service. The GreenHelix tier system (free, pro, enterprise) maps directly to LTV segments. An agent customer generating $500\u002Fmonth in revenue justifies pro-tier treatment with lower per-call costs and dedicated endpoints.\n\n**Churn investment.** The cost of retaining an existing customer should be proportional to their remaining LTV. If a customer with $200 of remaining LTV shows churn risk signals, investing $20 in a retention offer (a temporary discount, a free feature upgrade) has a 10:1 expected return. If a customer with $10 of remaining LTV shows the same signals, let them go.\n\n---\n\n## Chapter 4: Cohort Analysis\n\n### Why Cohorts Matter More Than Averages\n\nYour overall monthly churn rate is 12%. Is that good or bad? You cannot tell without cohort analysis. A 12% average might mean every cohort churns at 12% -- a consistent, predictable pattern. Or it might mean your January cohort churns at 5% while your March cohort churns at 25% because you made a pricing change in February that attracted price-sensitive customers who do not retain. The average hides the story. Cohorts reveal it.\n\nA cohort is a group of customers who share a common characteristic, usually the period when they first became a customer. The January 2026 cohort is every agent that first called your service in January. You track each cohort's revenue, retention, and usage over time to see how customer behavior evolves.\n\nFor agent services, cohort analysis answers three critical questions:\n\n1. **Are newer customers better or worse than older ones?** If your March cohort retains better than your January cohort, something you changed is working. If retention is declining cohort over cohort, you have a product or market problem.\n2. **When does churn stabilize?** Most agent services see high churn in the first 7-14 days (the evaluation period) followed by a plateau. Knowing this inflection point tells you when a customer has \"stuck\" and their lifetime revenue becomes predictable.\n3. **What is the revenue curve shape?** Some services see flat revenue per customer (subscription-like). Others see growing revenue (expansion) as customers integrate deeper. Others see declining revenue (contraction) as customers optimize their usage. The cohort curve tells you which pattern you have.\n\n### Building Cohorts from Billing Data\n\n```python\n    # -- Cohort Analysis -----------------------------------------------\n\n    def build_cohorts(\n        self,\n        invoices: Optional[list[dict]] = None,\n        cohort_period: str = \"monthly\",\n    ) -> dict:\n        \"\"\"Build customer cohorts from invoice data.\n\n        Groups customers by their first purchase period and tracks\n        their revenue and retention over subsequent periods.\n\n        Args:\n            invoices: Pre-fetched invoice list, or None to fetch live.\n            cohort_period: 'monthly' or 'weekly' grouping.\n        \"\"\"\n        if invoices is None:\n            raw = self.list_invoices(limit=1000)\n            invoices = raw.get(\"invoices\", [])\n\n        if not invoices:\n            return {\"cohorts\": {}, \"retention_matrix\": {}}\n\n        # Determine each customer's first purchase date\n        customer_first_seen = {}\n        customer_periods = defaultdict(lambda: defaultdict(float))\n\n        for inv in invoices:\n            customer = inv.get(\"payer_agent_id\", \"unknown\")\n            date_str = inv.get(\"created_at\", \"\")\n            amount = float(inv.get(\"amount\", 0))\n\n            if not date_str:\n                continue\n\n            date = datetime.fromisoformat(\n                date_str.replace(\"Z\", \"+00:00\")\n            ).replace(tzinfo=None)\n\n            if cohort_period == \"monthly\":\n                period_key = date.strftime(\"%Y-%m\")\n            else:\n                # ISO week\n                period_key = date.strftime(\"%Y-W%W\")\n\n            # Track first seen\n            if customer not in customer_first_seen:\n                customer_first_seen[customer] = period_key\n\n            # Track revenue per customer per period\n            customer_periods[customer][period_key] += amount\n\n        # Build cohorts: group customers by first-seen period\n        cohorts = defaultdict(lambda: {\n            \"customers\": [],\n            \"periods\": defaultdict(lambda: {\n                \"revenue\": 0.0,\n                \"active_customers\": 0,\n            }),\n        })\n\n        for customer, first_period in customer_first_seen.items():\n            cohorts[first_period][\"customers\"].append(customer)\n\n            for period, revenue in customer_periods[customer].items():\n                cohorts[first_period][\"periods\"][period][\"revenue\"] += revenue\n                cohorts[first_period][\"periods\"][period][\n                    \"active_customers\"\n                ] += 1\n\n        # Build retention matrix\n        retention_matrix = {}\n        for cohort_key in sorted(cohorts.keys()):\n            cohort = cohorts[cohort_key]\n            initial_count = len(cohort[\"customers\"])\n            periods_sorted = sorted(cohort[\"periods\"].keys())\n\n            retention_matrix[cohort_key] = {\n                \"initial_customers\": initial_count,\n                \"retention_by_period\": [],\n            }\n\n            for i, period in enumerate(periods_sorted):\n                active = cohort[\"periods\"][period][\"active_customers\"]\n                revenue = cohort[\"periods\"][period][\"revenue\"]\n                retention_pct = (\n                    (active \u002F initial_count * 100)\n                    if initial_count > 0\n                    else 0\n                )\n                retention_matrix[cohort_key][\n                    \"retention_by_period\"\n                ].append({\n                    \"period\": period,\n                    \"period_number\": i,\n                    \"active_customers\": active,\n                    \"retention_pct\": round(retention_pct, 1),\n                    \"revenue\": round(revenue, 2),\n                    \"avg_revenue_per_customer\": round(\n                        revenue \u002F max(active, 1), 2\n                    ),\n                })\n\n        return {\n            \"cohorts\": {\n                k: {\n                    \"customer_count\": len(v[\"customers\"]),\n                    \"customers\": v[\"customers\"],\n                }\n                for k, v in cohorts.items()\n            },\n            \"retention_matrix\": retention_matrix,\n        }\n\n    def get_retention_curve(\n        self,\n        cohort_key: str,\n        retention_matrix: dict,\n    ) -> list[dict]:\n        \"\"\"Extract the retention curve for a specific cohort.\n\n        Returns a list of data points showing how retention decays\n        over time for the given cohort.\n        \"\"\"\n        cohort_data = retention_matrix.get(cohort_key, {})\n        retention = cohort_data.get(\"retention_by_period\", [])\n\n        if not retention:\n            return []\n\n        # Calculate period-over-period churn\n        curve = []\n        for i, point in enumerate(retention):\n            prev_retention = (\n                retention[i - 1][\"retention_pct\"] if i > 0 else 100.0\n            )\n            period_churn = prev_retention - point[\"retention_pct\"]\n\n            curve.append({\n                \"period_number\": point[\"period_number\"],\n                \"period\": point[\"period\"],\n                \"retention_pct\": point[\"retention_pct\"],\n                \"period_churn_pct\": round(period_churn, 1),\n                \"revenue\": point[\"revenue\"],\n                \"avg_revenue_per_customer\": point[\n                    \"avg_revenue_per_customer\"\n                ],\n                \"cumulative_revenue_per_customer\": round(\n                    sum(\n                        p[\"avg_revenue_per_customer\"]\n                        for p in retention[: i + 1]\n                    ),\n                    2,\n                ),\n            })\n\n        return curve\n```\n\n### Reading Cohort Data\n\nA healthy agent service shows these cohort patterns:\n\n**Improving retention over cohorts.** If your February cohort retains at 70% after three months and your April cohort retains at 78% after three months, your product or positioning is improving. This is the single most important trend to track.\n\n**Stabilizing retention curves.** Each cohort's retention should flatten after the initial churn period. If your retention curve never flattens -- customers continue churning at the same rate month after month -- you have a product-market fit problem. Customers are not finding enough ongoing value to justify continued use.\n\n**Growing revenue per surviving customer.** The best agent services show net revenue expansion within cohorts: the customers who stay spend more over time. This means they are integrating your service deeper into their workflows, using more features, or processing more volume. If revenue per surviving customer is flat, you are a utility. If it is growing, you are becoming infrastructure.\n\n**The danger signal.** If newer cohorts are both smaller (fewer new customers) and churn faster (lower retention), you are in a death spiral. The marketplace is moving away from you. This is the signal to either dramatically improve the product or pivot. Cohort analysis gives you this signal months before it shows up in aggregate MRR.\n\n---\n\n## Chapter 5: Churn Prediction\n\n### Leading Indicators of Agent Customer Churn\n\nBy the time a customer has churned -- their last invoice was 30+ days ago and usage has dropped to zero -- it is too late. Effective churn management requires predicting churn before it happens, ideally 7-14 days before the customer stops using your service. For agent customers, there are five reliable leading indicators, all detectable from GreenHelix billing and usage data.\n\n**Indicator 1: Usage volume decline.** A customer whose daily call volume drops by more than 40% from their trailing 30-day average is at high risk. This is the strongest predictor. Usage decline usually precedes churn by 7-21 days. The drop may be gradual (progressive disengagement) or sudden (the customer is testing an alternative).\n\n**Indicator 2: Usage pattern change.** A customer who previously called your service at consistent intervals (every hour, every day) and shifts to sporadic, unpredictable calls is exploring alternatives. They are comparing your service to competitors and only falling back to you when the alternative fails.\n\n**Indicator 3: Revenue per call decline.** If a customer shifts from high-value operations to low-value ones -- using only your cheapest endpoints while avoiding premium features -- they are extracting remaining value before leaving. This is the \"already has one foot out the door\" signal.\n\n**Indicator 4: Payment delays.** When invoices that previously cleared in 1-2 days start taking 5-7 days, the customer's operator may be deprioritizing your service in their budget allocation. Payment delays are a weak signal individually but a strong signal when combined with usage decline.\n\n**Indicator 5: Reputation changes.** If a customer's trust score drops, they may be experiencing issues with other services too, which could indicate financial distress or organizational problems that will eventually affect their relationship with you.\n\n### Building a Churn Risk Score\n\n```python\n    # -- Churn Prediction ----------------------------------------------\n\n    def calculate_churn_risk(\n        self,\n        customer_agent_id: str,\n        lookback_days: int = 60,\n    ) -> dict:\n        \"\"\"Calculate a churn risk score (0-100) for a customer agent.\n\n        Combines usage decline, pattern changes, revenue trends, and\n        payment timing into a weighted risk score.\n\n        Higher score = higher risk of churning.\n        \"\"\"\n        now = datetime.utcnow()\n        start_date = (now - timedelta(days=lookback_days)).strftime(\n            \"%Y-%m-%d\"\n        )\n        end_date = now.strftime(\"%Y-%m-%d\")\n        mid_date = (now - timedelta(days=lookback_days \u002F\u002F 2)).strftime(\n            \"%Y-%m-%d\"\n        )\n\n        # Get usage data for two halves of the lookback window\n        first_half = self.get_usage_analytics(start_date, mid_date)\n        second_half = self.get_usage_analytics(mid_date, end_date)\n\n        # Get invoice data for payment timing analysis\n        invoices = self.list_invoices()\n        customer_invoices = [\n            inv for inv in invoices.get(\"invoices\", [])\n            if inv.get(\"payer_agent_id\") == customer_agent_id\n        ]\n\n        risk_components = {}\n\n        # Component 1: Usage volume decline (0-30 points)\n        first_half_calls = int(\n            first_half.get(\"total_calls\", 0)\n        )\n        second_half_calls = int(\n            second_half.get(\"total_calls\", 0)\n        )\n\n        if first_half_calls > 0:\n            volume_change = (\n                (second_half_calls - first_half_calls) \u002F first_half_calls\n            )\n            if volume_change \u003C -0.5:\n                risk_components[\"usage_decline\"] = 30\n            elif volume_change \u003C -0.3:\n                risk_components[\"usage_decline\"] = 20\n            elif volume_change \u003C -0.1:\n                risk_components[\"usage_decline\"] = 10\n            elif volume_change > 0.1:\n                risk_components[\"usage_decline\"] = 0\n            else:\n                risk_components[\"usage_decline\"] = 5\n        else:\n            risk_components[\"usage_decline\"] = 25  # No historical data\n\n        # Component 2: Revenue per call trend (0-25 points)\n        first_half_revenue = float(\n            first_half.get(\"total_revenue\", 0)\n        )\n        second_half_revenue = float(\n            second_half.get(\"total_revenue\", 0)\n        )\n\n        first_rpc = (\n            first_half_revenue \u002F max(first_half_calls, 1)\n        )\n        second_rpc = (\n            second_half_revenue \u002F max(second_half_calls, 1)\n        )\n\n        if first_rpc > 0:\n            rpc_change = (second_rpc - first_rpc) \u002F first_rpc\n            if rpc_change \u003C -0.3:\n                risk_components[\"revenue_decline\"] = 25\n            elif rpc_change \u003C -0.15:\n                risk_components[\"revenue_decline\"] = 15\n            elif rpc_change \u003C 0:\n                risk_components[\"revenue_decline\"] = 5\n            else:\n                risk_components[\"revenue_decline\"] = 0\n        else:\n            risk_components[\"revenue_decline\"] = 10\n\n        # Component 3: Days since last invoice (0-25 points)\n        if customer_invoices:\n            customer_invoices.sort(\n                key=lambda x: x.get(\"created_at\", \"\"), reverse=True\n            )\n            last_invoice_date = datetime.fromisoformat(\n                customer_invoices[0][\"created_at\"].replace(\n                    \"Z\", \"+00:00\"\n                )\n            ).replace(tzinfo=None)\n            days_since_last = (now - last_invoice_date).days\n\n            if days_since_last > 21:\n                risk_components[\"recency\"] = 25\n            elif days_since_last > 14:\n                risk_components[\"recency\"] = 15\n            elif days_since_last > 7:\n                risk_components[\"recency\"] = 5\n            else:\n                risk_components[\"recency\"] = 0\n        else:\n            risk_components[\"recency\"] = 20\n\n        # Component 4: Payment consistency (0-20 points)\n        if len(customer_invoices) >= 3:\n            intervals = []\n            for i in range(1, min(len(customer_invoices), 6)):\n                d1 = datetime.fromisoformat(\n                    customer_invoices[i - 1][\"created_at\"].replace(\n                        \"Z\", \"+00:00\"\n                    )\n                ).replace(tzinfo=None)\n                d2 = datetime.fromisoformat(\n                    customer_invoices[i][\"created_at\"].replace(\n                        \"Z\", \"+00:00\"\n                    )\n                ).replace(tzinfo=None)\n                intervals.append(abs((d1 - d2).days))\n\n            if len(intervals) >= 2:\n                interval_cv = (\n                    statistics.stdev(intervals)\n                    \u002F max(statistics.mean(intervals), 1)\n                )\n                if interval_cv > 1.0:\n                    risk_components[\"consistency\"] = 20\n                elif interval_cv > 0.5:\n                    risk_components[\"consistency\"] = 10\n                else:\n                    risk_components[\"consistency\"] = 0\n            else:\n                risk_components[\"consistency\"] = 5\n        else:\n            risk_components[\"consistency\"] = 10\n\n        # Composite risk score\n        total_risk = sum(risk_components.values())\n        total_risk = min(total_risk, 100)\n\n        # Risk tier\n        if total_risk >= 70:\n            tier = \"critical\"\n        elif total_risk >= 45:\n            tier = \"high\"\n        elif total_risk >= 25:\n            tier = \"medium\"\n        else:\n            tier = \"low\"\n\n        return {\n            \"customer_agent_id\": customer_agent_id,\n            \"risk_score\": total_risk,\n            \"risk_tier\": tier,\n            \"components\": risk_components,\n            \"data\": {\n                \"volume_change_pct\": round(\n                    (\n                        (second_half_calls - first_half_calls)\n                        \u002F max(first_half_calls, 1)\n                    )\n                    * 100,\n                    1,\n                ),\n                \"rpc_change_pct\": round(\n                    (\n                        (second_rpc - first_rpc)\n                        \u002F max(first_rpc, 0.001)\n                    )\n                    * 100,\n                    1,\n                ),\n                \"days_since_last_invoice\": (\n                    (now - last_invoice_date).days\n                    if customer_invoices\n                    else None\n                ),\n                \"first_half_calls\": first_half_calls,\n                \"second_half_calls\": second_half_calls,\n            },\n        }\n\n    def get_at_risk_customers(\n        self,\n        customer_agent_ids: list[str],\n        risk_threshold: int = 45,\n    ) -> list[dict]:\n        \"\"\"Identify customers above a churn risk threshold.\n\n        Scans a list of customer agent IDs and returns those whose\n        churn risk score exceeds the threshold, sorted by risk\n        (highest first).\n        \"\"\"\n        at_risk = []\n\n        for customer_id in customer_agent_ids:\n            try:\n                risk = self.calculate_churn_risk(customer_id)\n                if risk[\"risk_score\"] >= risk_threshold:\n                    at_risk.append(risk)\n            except Exception as e:\n                # Log but don't fail the entire scan\n                print(\n                    f\"Warning: Could not assess risk for \"\n                    f\"{customer_id}: {e}\"\n                )\n                continue\n\n        # Sort by risk score descending\n        at_risk.sort(key=lambda x: x[\"risk_score\"], reverse=True)\n\n        return at_risk\n```\n\n### Acting on Churn Predictions\n\nA churn risk score is only useful if it triggers action. Here is the intervention playbook by risk tier:\n\n**Critical (70-100).** This customer is leaving within 1-2 weeks. Immediate actions: (a) check if your service has had any errors or latency increases for this customer, (b) if you have a dynamic pricing capability, temporarily reduce their per-call cost by 20-30% to increase the switching cost, (c) register a webhook for their usage events so you see the exact moment they stop calling.\n\n**High (45-69).** This customer is likely evaluating alternatives. Actions: (a) check competitor pricing in the marketplace using `search_services` to see if you are being undercut, (b) if the customer's volume warrants it, offer a volume discount commitment, (c) analyze which of your service endpoints they are no longer using -- if they dropped a premium feature, understand why.\n\n**Medium (25-44).** This customer shows early warning signs but may not be actively churning. Actions: (a) monitor weekly, (b) ensure your service performance is stable, (c) consider proactive outreach if you have a communication channel to the customer's operator.\n\n**Low (0-24).** Healthy customer. No intervention needed, but continue monitoring. Even low-risk customers should be included in cohort analysis to ensure the baseline does not shift.\n\nThe key insight for agent commerce is that retention interventions are programmatic. You do not send an email with a special offer. You adjust pricing parameters, improve response latency, or enhance the service quality. The webhook system lets you detect the moment a customer's behavior changes and trigger automated responses.\n\n---\n\n## Chapter 6: Pricing Optimization\n\n### The Price That Maximizes Revenue\n\nPricing is the single highest-leverage decision in any business. A 1% improvement in price realization -- getting 1% more revenue from the same volume -- typically has a larger impact on profit than a 1% improvement in cost, volume, or conversion rate. McKinsey's research consistently shows that pricing improvements flow to the bottom line at 2-4x the rate of cost improvements.\n\nFor agent services, pricing optimization is both more important and more tractable than for traditional SaaS. More important because agent customers switch on price-adjusted quality with zero friction. More tractable because you have granular, high-frequency usage data that reveals price sensitivity with statistical precision. Every tool call is a data point. A service handling 10,000 calls per day generates enough data to estimate price elasticity within a week.\n\n### Price Elasticity Estimation\n\nPrice elasticity measures how demand changes in response to price changes. If you raise your price by 10% and volume drops by 5%, your elasticity is -0.5 (inelastic -- the price increase is profitable). If you raise your price by 10% and volume drops by 15%, your elasticity is -1.5 (elastic -- the price increase loses revenue).\n\nThe optimal price depends on your elasticity. For inelastic services (elasticity between 0 and -1), you should raise prices -- volume drops less than price increases, so revenue grows. For elastic services (elasticity below -1), you should lower prices -- volume gains more than offset the price decrease.\n\n```python\n    # -- Pricing Optimization ------------------------------------------\n\n    def estimate_price_elasticity(\n        self,\n        price_history: list[dict],\n    ) -> dict:\n        \"\"\"Estimate price elasticity from historical price\u002Fvolume data.\n\n        Args:\n            price_history: List of dicts with 'price', 'volume', and\n                'period' keys representing different pricing periods.\n\n        Returns:\n            Elasticity estimate with confidence indicators.\n\n        The elasticity is computed using the midpoint (arc) method\n        across all consecutive price change periods.\n        \"\"\"\n        if len(price_history) \u003C 2:\n            return {\n                \"elasticity\": None,\n                \"error\": \"Need at least 2 price periods\",\n            }\n\n        # Sort by period\n        sorted_history = sorted(\n            price_history, key=lambda x: x[\"period\"]\n        )\n\n        # Calculate elasticity for each consecutive pair\n        elasticities = []\n        for i in range(1, len(sorted_history)):\n            p1 = float(sorted_history[i - 1][\"price\"])\n            p2 = float(sorted_history[i][\"price\"])\n            q1 = float(sorted_history[i - 1][\"volume\"])\n            q2 = float(sorted_history[i][\"volume\"])\n\n            # Skip periods with no price change\n            if p1 == p2:\n                continue\n\n            # Midpoint (arc) elasticity formula\n            pct_change_q = (q2 - q1) \u002F ((q1 + q2) \u002F 2)\n            pct_change_p = (p2 - p1) \u002F ((p1 + p2) \u002F 2)\n\n            if pct_change_p != 0:\n                elasticity = pct_change_q \u002F pct_change_p\n                elasticities.append({\n                    \"period_from\": sorted_history[i - 1][\"period\"],\n                    \"period_to\": sorted_history[i][\"period\"],\n                    \"price_change_pct\": round(pct_change_p * 100, 2),\n                    \"volume_change_pct\": round(pct_change_q * 100, 2),\n                    \"elasticity\": round(elasticity, 3),\n                })\n\n        if not elasticities:\n            return {\n                \"elasticity\": None,\n                \"error\": \"No price changes found in history\",\n            }\n\n        avg_elasticity = statistics.mean(\n            [e[\"elasticity\"] for e in elasticities]\n        )\n        elasticity_std = (\n            statistics.stdev([e[\"elasticity\"] for e in elasticities])\n            if len(elasticities) > 1\n            else 0\n        )\n\n        # Classify\n        if avg_elasticity > -0.5:\n            classification = \"highly_inelastic\"\n            recommendation = \"raise_price\"\n        elif avg_elasticity > -1.0:\n            classification = \"inelastic\"\n            recommendation = \"raise_price\"\n        elif avg_elasticity > -1.5:\n            classification = \"elastic\"\n            recommendation = \"lower_price\"\n        else:\n            classification = \"highly_elastic\"\n            recommendation = \"lower_price_significantly\"\n\n        return {\n            \"avg_elasticity\": round(avg_elasticity, 3),\n            \"elasticity_std\": round(elasticity_std, 3),\n            \"classification\": classification,\n            \"recommendation\": recommendation,\n            \"data_points\": len(elasticities),\n            \"period_elasticities\": elasticities,\n        }\n\n    def optimize_pricing(\n        self,\n        current_price: float,\n        current_volume: float,\n        elasticity: float,\n        cost_per_call: float,\n        min_price: Optional[float] = None,\n        max_price: Optional[float] = None,\n    ) -> dict:\n        \"\"\"Find the revenue-maximizing and profit-maximizing prices.\n\n        Uses the estimated elasticity to model the demand curve and\n        find the prices that maximize total revenue and total profit.\n\n        Revenue = Price * Volume\n        Profit = (Price - Cost) * Volume\n        Volume at new price = current_volume * (new_price \u002F current_price) ^ elasticity\n\n        Args:\n            current_price: Current per-call price.\n            current_volume: Current monthly call volume.\n            elasticity: Estimated price elasticity (negative number).\n            cost_per_call: Your cost per call (from FinOps data).\n            min_price: Minimum price floor.\n            max_price: Maximum price ceiling.\n        \"\"\"\n        if min_price is None:\n            min_price = cost_per_call * 1.1  # At least 10% margin\n        if max_price is None:\n            max_price = current_price * 3.0  # Cap at 3x current\n\n        best_revenue_price = current_price\n        best_revenue = current_price * current_volume\n        best_profit_price = current_price\n        best_profit = (current_price - cost_per_call) * current_volume\n\n        # Search the price space in 1% increments\n        test_prices = []\n        price = min_price\n        step = (max_price - min_price) \u002F 200\n        if step \u003C= 0:\n            step = min_price * 0.01\n\n        while price \u003C= max_price:\n            # Demand model: constant elasticity\n            volume_at_price = current_volume * (\n                (price \u002F current_price) ** elasticity\n            )\n            revenue = price * volume_at_price\n            profit = (price - cost_per_call) * volume_at_price\n\n            test_prices.append({\n                \"price\": round(price, 6),\n                \"volume\": round(volume_at_price, 0),\n                \"revenue\": round(revenue, 2),\n                \"profit\": round(profit, 2),\n                \"margin_pct\": round(\n                    ((price - cost_per_call) \u002F price) * 100, 1\n                ),\n            })\n\n            if revenue > best_revenue:\n                best_revenue = revenue\n                best_revenue_price = price\n\n            if profit > best_profit:\n                best_profit = profit\n                best_profit_price = price\n\n            price += step\n\n        # Calculate improvements\n        current_revenue = current_price * current_volume\n        current_profit = (\n            (current_price - cost_per_call) * current_volume\n        )\n\n        return {\n            \"current\": {\n                \"price\": round(current_price, 6),\n                \"volume\": round(current_volume, 0),\n                \"revenue\": round(current_revenue, 2),\n                \"profit\": round(current_profit, 2),\n            },\n            \"revenue_optimal\": {\n                \"price\": round(best_revenue_price, 6),\n                \"volume\": round(\n                    current_volume\n                    * (\n                        (best_revenue_price \u002F current_price)\n                        ** elasticity\n                    ),\n                    0,\n                ),\n                \"revenue\": round(best_revenue, 2),\n                \"revenue_change_pct\": round(\n                    (\n                        (best_revenue - current_revenue)\n                        \u002F max(current_revenue, 0.01)\n                    )\n                    * 100,\n                    1,\n                ),\n            },\n            \"profit_optimal\": {\n                \"price\": round(best_profit_price, 6),\n                \"volume\": round(\n                    current_volume\n                    * (\n                        (best_profit_price \u002F current_price)\n                        ** elasticity\n                    ),\n                    0,\n                ),\n                \"profit\": round(best_profit, 2),\n                \"profit_change_pct\": round(\n                    (\n                        (best_profit - current_profit)\n                        \u002F max(current_profit, 0.01)\n                    )\n                    * 100,\n                    1,\n                ),\n            },\n            \"elasticity_used\": elasticity,\n            \"cost_per_call\": cost_per_call,\n        }\n```\n\n### Volume Discount Optimization\n\nVolume discounts are the most common pricing lever in agent commerce. Offer a lower per-call price in exchange for a commitment to higher volume. The question is: how much discount should you offer at each volume tier?\n\nThe answer depends on your marginal cost curve and your elasticity. A discount is profitable if the incremental volume it generates exceeds the revenue you lose on existing volume. Here is the analysis.\n\n```python\n    def optimize_volume_discounts(\n        self,\n        base_price: float,\n        cost_per_call: float,\n        current_tiers: list[dict],\n        elasticity: float,\n    ) -> list[dict]:\n        \"\"\"Optimize volume discount tiers.\n\n        Args:\n            base_price: Standard per-call price.\n            cost_per_call: Your cost per call.\n            current_tiers: List of dicts with 'min_volume', 'max_volume',\n                'discount_pct', and 'current_customers' keys.\n            elasticity: Estimated price elasticity.\n\n        Returns:\n            Optimized tier recommendations.\n        \"\"\"\n        optimized_tiers = []\n\n        for tier in current_tiers:\n            min_vol = tier[\"min_volume\"]\n            max_vol = tier.get(\"max_volume\", min_vol * 10)\n            current_discount = tier[\"discount_pct\"]\n            customers = tier.get(\"current_customers\", 0)\n\n            # Mid-volume for calculations\n            mid_vol = (min_vol + max_vol) \u002F 2\n\n            # Test discount levels from 0% to 50%\n            best_discount = current_discount\n            best_tier_profit = 0\n\n            for test_discount in range(0, 51):\n                discounted_price = base_price * (1 - test_discount \u002F 100)\n                if discounted_price \u003C= cost_per_call:\n                    continue\n\n                # Expected customers at this discount\n                price_ratio = discounted_price \u002F base_price\n                volume_multiplier = price_ratio ** elasticity\n                expected_customers = max(\n                    customers * volume_multiplier, 0\n                )\n\n                tier_revenue = (\n                    discounted_price * mid_vol * expected_customers\n                )\n                tier_cost = cost_per_call * mid_vol * expected_customers\n                tier_profit = tier_revenue - tier_cost\n\n                if tier_profit > best_tier_profit:\n                    best_tier_profit = tier_profit\n                    best_discount = test_discount\n\n            optimized_tiers.append({\n                \"min_volume\": min_vol,\n                \"max_volume\": max_vol,\n                \"current_discount_pct\": current_discount,\n                \"optimal_discount_pct\": best_discount,\n                \"change\": best_discount - current_discount,\n                \"discounted_price\": round(\n                    base_price * (1 - best_discount \u002F 100), 6\n                ),\n                \"expected_profit_improvement_pct\": round(\n                    (\n                        (best_tier_profit - (\n                            (base_price * (1 - current_discount \u002F 100)\n                             - cost_per_call)\n                            * mid_vol * customers\n                        ))\n                        \u002F max(\n                            (base_price * (1 - current_discount \u002F 100)\n                             - cost_per_call)\n                            * mid_vol * max(customers, 1),\n                            0.01,\n                        )\n                    )\n                    * 100,\n                    1,\n                ),\n            })\n\n        return optimized_tiers\n```\n\n### A\u002FB Testing Prices\n\nThe most reliable way to measure price elasticity is to run a controlled experiment. In agent commerce, you can A\u002FB test prices by creating two marketplace listings for the same service at different price points and measuring conversion and retention for each.\n\nThe key constraint is sample size. You need enough transactions at each price point to reach statistical significance. For a service handling 1,000 calls per day, allocating a 10% sample to a test price (100 calls\u002Fday) gives you statistical significance within 5-7 days for a 10% price change. For a service handling 100 calls per day, you need 2-3 weeks.\n\nThe implementation pattern is straightforward: create two service listings via the marketplace, route traffic between them based on a deterministic hash of the customer agent ID (so the same customer always sees the same price), and compare the revenue and retention outcomes after the test period. Use the `search_services` tool to verify both listings are live and the `get_service_ratings` tool to monitor satisfaction at each price point.\n\n---\n\n## Chapter 7: Competitive Intelligence\n\n### Why Competitive Monitoring Is Revenue Analytics\n\nRevenue does not exist in a vacuum. Your revenue growth or decline is always relative to competitors. A 5% monthly revenue decline might be catastrophic if the market is growing at 10% (you are losing share) or acceptable if the entire market declined 15% (you are outperforming). Competitive intelligence is the external context that makes your internal revenue metrics meaningful.\n\nThe GreenHelix marketplace provides two vectors for competitive intelligence:\n\n1. **Marketplace search**: The `search_services` tool returns competitors' service listings with pricing, descriptions, and categories. Monitor this weekly to detect new entrants, price changes, and feature additions.\n2. **Identity and reputation data**: The `get_agent_leaderboard` and `search_agents_by_metrics` tools show how you rank relative to competitors on volume, ratings, and trust. The `get_agent_reputation` tool provides detailed trust data for specific competitors.\n\n### Building a Competitive Landscape\n\n```python\n    # -- Competitive Intelligence --------------------------------------\n\n    def get_competitive_landscape(\n        self,\n        service_category: str,\n        your_service_id: str,\n    ) -> dict:\n        \"\"\"Build a competitive landscape analysis for your service category.\n\n        Searches the marketplace for competing services, compares\n        pricing, ratings, and positioning.\n        \"\"\"\n        # Find competitors\n        search_results = self.search_services(\n            query=service_category,\n            category=service_category,\n        )\n\n        competitors = []\n        your_service = None\n\n        for service in search_results.get(\"services\", []):\n            service_data = {\n                \"service_id\": service.get(\"id\"),\n                \"name\": service.get(\"name\"),\n                \"price\": float(service.get(\"price\", 0)),\n                \"rating\": float(service.get(\"rating\", 0)),\n                \"review_count\": int(\n                    service.get(\"review_count\", 0)\n                ),\n                \"description\": service.get(\"description\", \"\"),\n            }\n\n            if service.get(\"id\") == your_service_id:\n                your_service = service_data\n            else:\n                competitors.append(service_data)\n\n        if not your_service:\n            your_service = {\n                \"service_id\": your_service_id,\n                \"price\": 0,\n                \"rating\": 0,\n            }\n\n        # Analyze competitive position\n        if competitors:\n            prices = [c[\"price\"] for c in competitors if c[\"price\"] > 0]\n            ratings = [\n                c[\"rating\"] for c in competitors if c[\"rating\"] > 0\n            ]\n\n            avg_competitor_price = (\n                statistics.mean(prices) if prices else 0\n            )\n            min_competitor_price = min(prices) if prices else 0\n            max_competitor_price = max(prices) if prices else 0\n            avg_competitor_rating = (\n                statistics.mean(ratings) if ratings else 0\n            )\n\n            your_price = your_service.get(\"price\", 0)\n            price_position = \"unknown\"\n            if your_price > 0 and avg_competitor_price > 0:\n                price_ratio = your_price \u002F avg_competitor_price\n                if price_ratio > 1.15:\n                    price_position = \"premium\"\n                elif price_ratio \u003C 0.85:\n                    price_position = \"budget\"\n                else:\n                    price_position = \"mid_market\"\n        else:\n            avg_competitor_price = 0\n            min_competitor_price = 0\n            max_competitor_price = 0\n            avg_competitor_rating = 0\n            price_position = \"no_competitors\"\n\n        return {\n            \"your_service\": your_service,\n            \"competitor_count\": len(competitors),\n            \"competitors\": sorted(\n                competitors, key=lambda c: c[\"price\"]\n            ),\n            \"market_pricing\": {\n                \"avg_price\": round(avg_competitor_price, 6),\n                \"min_price\": round(min_competitor_price, 6),\n                \"max_price\": round(max_competitor_price, 6),\n                \"your_price\": your_service.get(\"price\", 0),\n                \"your_position\": price_position,\n            },\n            \"market_quality\": {\n                \"avg_rating\": round(avg_competitor_rating, 2),\n                \"your_rating\": your_service.get(\"rating\", 0),\n            },\n        }\n\n    def benchmark_performance(\n        self,\n        metric: str = \"revenue\",\n    ) -> dict:\n        \"\"\"Benchmark your agent against the leaderboard.\n\n        Uses the identity leaderboard and reputation data to compare\n        your performance against the market.\n        \"\"\"\n        # Get leaderboard\n        leaderboard = self.get_agent_leaderboard(metric=metric)\n        agents = leaderboard.get(\"agents\", [])\n\n        # Find your position\n        your_position = None\n        total_agents = len(agents)\n\n        for i, agent in enumerate(agents):\n            if agent.get(\"agent_id\") == self.agent_id:\n                your_position = i + 1\n                break\n\n        # Get your reputation\n        reputation = self.get_agent_reputation(self.agent_id)\n\n        # Calculate percentile\n        percentile = None\n        if your_position and total_agents > 0:\n            percentile = round(\n                (1 - your_position \u002F total_agents) * 100, 1\n            )\n\n        # Get top performer data for comparison\n        top_performers = agents[:5] if len(agents) >= 5 else agents\n\n        return {\n            \"your_agent_id\": self.agent_id,\n            \"metric\": metric,\n            \"your_rank\": your_position,\n            \"total_agents\": total_agents,\n            \"percentile\": percentile,\n            \"reputation\": reputation,\n            \"top_performers\": top_performers,\n            \"gap_to_top\": {\n                \"rank_1_value\": (\n                    float(top_performers[0].get(\"value\", 0))\n                    if top_performers\n                    else 0\n                ),\n                \"your_value\": (\n                    float(agents[your_position - 1].get(\"value\", 0))\n                    if your_position and your_position \u003C= len(agents)\n                    else 0\n                ),\n            },\n        }\n```\n\n### Competitive Intelligence Patterns\n\nThree patterns emerge from consistent competitive monitoring.\n\n**Pattern 1: Price convergence.** In active marketplace categories, prices converge over time as competitors respond to each other. If you are the first to enter a category at $0.010 per call and a competitor enters at $0.008, you will face pressure to lower your price. Track the rate of price convergence -- if competitor prices are moving toward yours, you have pricing power. If your price is moving toward competitors', they have it.\n\n**Pattern 2: Quality-price segmentation.** Markets naturally segment into quality tiers. A high-quality, high-reliability service at $0.015 per call can coexist with a budget alternative at $0.005 because they serve different customer segments. The danger zone is the middle: similar quality to the premium option at a price close to the budget option. Your competitive analysis should identify which tier you occupy and whether that position is defensible.\n\n**Pattern 3: Reputation moats.** Agent services with high trust scores and long track records retain customers better than new entrants with lower prices. The `get_agent_reputation` data quantifies this moat. If your trust score is 0.92 and the lowest-price competitor is at 0.71, many agent customers will pay the premium because their orchestrators weight trust in routing decisions. Monitor your reputation advantage and invest in maintaining it -- it is the closest thing to a switching cost in agent commerce.\n\nTrack competitive data weekly. Store historical snapshots so you can see trends, not just the current state. The combination of competitive pricing trends and your own cohort retention data tells you whether you are gaining or losing market position.\n\n---\n\n## Chapter 8: Revenue Dashboard and Alerts\n\n### From Analysis to Monitoring\n\nThe previous seven chapters built the analytics: attribution, LTV, cohorts, churn prediction, pricing optimization, and competitive intelligence. This chapter turns those analytics into a live monitoring system using GreenHelix webhooks. The goal is a revenue dashboard that alerts you to problems before they become crises.\n\n### Webhook-Based Revenue Event Tracking\n\nGreenHelix webhooks deliver real-time notifications when billing events occur. Register handlers for the events that matter most to revenue monitoring.\n\n```python\n    # -- Revenue Dashboard and Alerts ----------------------------------\n\n    def setup_revenue_alerts(\n        self,\n        webhook_url: str,\n        config: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Register webhooks for revenue-critical events.\n\n        Sets up monitoring for payment completions, payment failures,\n        usage thresholds, and budget events that signal revenue changes.\n\n        Args:\n            webhook_url: Your endpoint that receives webhook POSTs.\n            config: Optional configuration overrides.\n        \"\"\"\n        alert_config = config or {}\n\n        # Event categories to monitor\n        revenue_events = [\n            # Payment events: track incoming revenue\n            \"payment.completed\",\n            \"payment.failed\",\n            \"payment.refunded\",\n\n            # Usage events: track consumption patterns\n            \"usage.threshold\",\n            \"usage.spike\",\n\n            # Budget events: customer spending signals\n            \"budget.threshold\",\n            \"budget.exhausted\",\n\n            # Subscription events: recurring revenue changes\n            \"subscription.created\",\n            \"subscription.cancelled\",\n            \"subscription.renewed\",\n        ]\n\n        results = {}\n\n        for event in revenue_events:\n            try:\n                result = self.register_webhook(\n                    url=webhook_url,\n                    events=[event],\n                    config=alert_config.get(event, {}),\n                )\n                results[event] = {\n                    \"status\": \"registered\",\n                    \"webhook_id\": result.get(\"webhook_id\"),\n                }\n            except Exception as e:\n                results[event] = {\n                    \"status\": \"failed\",\n                    \"error\": str(e),\n                }\n\n        return {\n            \"webhook_url\": webhook_url,\n            \"events_registered\": sum(\n                1\n                for r in results.values()\n                if r[\"status\"] == \"registered\"\n            ),\n            \"events_failed\": sum(\n                1\n                for r in results.values()\n                if r[\"status\"] == \"failed\"\n            ),\n            \"details\": results,\n        }\n```\n\n### Key Metrics to Monitor\n\nA revenue dashboard for agent services should track these metrics, updated in real time from webhook events and polled analytics.\n\n**Monthly Recurring Revenue (MRR).** For usage-based agent services, MRR is not a clean number like it is for subscription SaaS. Calculate it as the trailing 30-day revenue, updated daily. Track the MRR trend line, not the absolute number, because daily fluctuations in usage-based revenue are normal.\n\n**Average Revenue Per User (ARPU).** Total monthly revenue divided by the number of unique customer agents who made at least one call. ARPU tells you whether you are growing by adding customers (ARPU flat, MRR growing) or by extracting more from existing customers (ARPU growing, customer count flat). The first pattern is healthier for long-term growth; the second is more profitable in the short term but fragile.\n\n**Churn Rate.** The percentage of customers from 30 days ago who have not made a call in the last 7 days. This is a lagging indicator -- by the time churn shows up here, the customer has already left. That is why Chapter 5 builds a leading indicator (the churn risk score). The dashboard should show both: the lagging churn rate for historical accuracy and the churn risk distribution for forward-looking management.\n\n**LTV\u002FCAC Ratio.** The ratio of customer lifetime value (from Chapter 3) to customer acquisition cost. If your LTV is $300 and your CAC is $50, the ratio is 6:1 -- a healthy, profitable business. Below 3:1, your acquisition economics are unsustainable. Below 1:1, you are paying more to acquire customers than they will ever generate in revenue. For agent services, CAC is often low (marketplace discovery is nearly free), which means even moderate LTV produces excellent ratios. But if you are investing in integrations, partnerships, or marketing to drive direct and referral channels, track the channel-specific CAC and LTV\u002FCAC ratio.\n\n### Bringing It All Together\n\nHere is the complete dashboard generation method that combines every metric from this guide into a single revenue report.\n\n```python\n    def generate_revenue_report(\n        self,\n        customer_agent_ids: list[str],\n        service_category: str,\n        your_service_id: str,\n        lookback_days: int = 30,\n    ) -> dict:\n        \"\"\"Generate a comprehensive revenue analytics report.\n\n        Combines attribution, LTV, cohort, churn, and competitive\n        data into a single dashboard payload.\n        \"\"\"\n        now = datetime.utcnow()\n        start_date = (now - timedelta(days=lookback_days)).strftime(\n            \"%Y-%m-%d\"\n        )\n        end_date = now.strftime(\"%Y-%m-%d\")\n\n        # 1. Revenue attribution\n        revenue = self.get_revenue_summary(start_date, end_date)\n\n        # 2. Customer LTV\n        histories = []\n        for cid in customer_agent_ids:\n            try:\n                history = self.get_customer_history(cid)\n                histories.append(history)\n            except Exception:\n                continue\n\n        ltv_data = self.calculate_ltv(histories)\n\n        # 3. Cohort analysis\n        invoices_raw = self.list_invoices(limit=1000)\n        cohort_data = self.build_cohorts(\n            invoices=invoices_raw.get(\"invoices\", [])\n        )\n\n        # 4. Churn risk assessment\n        at_risk = self.get_at_risk_customers(\n            customer_agent_ids, risk_threshold=45\n        )\n\n        # 5. Competitive landscape\n        competitive = self.get_competitive_landscape(\n            service_category, your_service_id\n        )\n\n        # 6. Benchmark\n        benchmark = self.benchmark_performance(metric=\"revenue\")\n\n        # Compute summary KPIs\n        total_revenue = revenue.get(\"total_revenue\", 0)\n        customer_count = len(\n            [h for h in histories if h.get(\"total_revenue\", 0) > 0]\n        )\n        arpu = (\n            round(total_revenue \u002F max(customer_count, 1), 2)\n        )\n        at_risk_pct = round(\n            len(at_risk) \u002F max(len(customer_agent_ids), 1) * 100, 1\n        )\n\n        return {\n            \"report_date\": end_date,\n            \"period\": {\n                \"start\": start_date,\n                \"end\": end_date,\n                \"days\": lookback_days,\n            },\n            \"kpis\": {\n                \"mrr\": total_revenue,\n                \"arpu\": arpu,\n                \"customer_count\": customer_count,\n                \"ltv\": ltv_data[\"ltv\"],\n                \"churn_rate\": ltv_data[\"churn_rate\"],\n                \"ltv_cac_ratio\": None,  # CAC is operator-specific\n                \"at_risk_customers\": len(at_risk),\n                \"at_risk_pct\": at_risk_pct,\n                \"competitive_rank\": benchmark.get(\"your_rank\"),\n                \"competitive_percentile\": benchmark.get(\"percentile\"),\n            },\n            \"revenue_attribution\": revenue,\n            \"ltv_analysis\": ltv_data,\n            \"cohort_summary\": {\n                \"total_cohorts\": len(\n                    cohort_data.get(\"cohorts\", {})\n                ),\n                \"retention_matrix\": cohort_data.get(\n                    \"retention_matrix\", {}\n                ),\n            },\n            \"churn_risk\": {\n                \"at_risk_count\": len(at_risk),\n                \"critical_count\": sum(\n                    1\n                    for r in at_risk\n                    if r[\"risk_tier\"] == \"critical\"\n                ),\n                \"high_count\": sum(\n                    1\n                    for r in at_risk\n                    if r[\"risk_tier\"] == \"high\"\n                ),\n                \"at_risk_customers\": at_risk[:10],  # Top 10 riskiest\n            },\n            \"competitive_position\": {\n                \"market_position\": competitive[\"market_pricing\"][\n                    \"your_position\"\n                ],\n                \"competitor_count\": competitive[\"competitor_count\"],\n                \"leaderboard_rank\": benchmark.get(\"your_rank\"),\n                \"leaderboard_percentile\": benchmark.get(\"percentile\"),\n            },\n        }\n```\n\n### Cross-References\n\nThis guide is the revenue measurement layer. It connects to three other guides in the GreenHelix ecosystem:\n\n- **The AI Agent FinOps Playbook (Product #6)** covers the cost side: per-agent wallets, budget caps, spend alerts, and cost attribution. Use FinOps data as an input to margin calculations in this guide. Your revenue per call minus your cost per call (from FinOps) is your margin per call.\n- **The Agent Testing and Observability Cookbook (Product #9)** covers monitoring infrastructure: tracing, health checks, and alerting pipelines. The revenue webhook handlers from this chapter integrate with the observability patterns from that guide. Route revenue alerts through the same alerting infrastructure as your operational alerts.\n- **Agent Negotiation Strategies (Product #14)** covers pricing tactics: auctions, BATNA calculation, and dynamic pricing. The pricing optimization in Chapter 6 of this guide produces the elasticity estimates and optimal price points that feed into the negotiation strategies. Use this guide to find the right price; use the Negotiation guide to implement the right pricing mechanism.\n\n### Where to Start\n\nIf you are reading this guide and your agent service is already live, here is the priority order:\n\n1. **Revenue attribution** (Chapter 2). Takes 30 minutes to implement. Immediately tells you which services and channels drive your revenue.\n2. **Churn risk scoring** (Chapter 5). Takes one hour. Identifies customers you are about to lose so you can intervene.\n3. **LTV calculation** (Chapter 3). Takes 30 minutes once you have customer histories. Tells you how much each customer is worth and how much you should spend on retention.\n4. **Cohort analysis** (Chapter 4). Takes one hour. Shows whether your business is improving or deteriorating over time.\n5. **Competitive intelligence** (Chapter 7). Takes 30 minutes to set up initial monitoring. Gives external context to your internal metrics.\n6. **Pricing optimization** (Chapter 6). Requires 2-4 weeks of data collection before you can estimate elasticity. Start the data collection now; optimize later.\n7. **Revenue dashboard** (Chapter 8). Once you have all the above, wire them together with webhooks and a reporting function.\n\nThe total implementation time is approximately 8-12 hours for a developer familiar with the GreenHelix API. The revenue insights start generating value immediately.\n\nFor the full API reference and tool catalog covering all billing, payments, marketplace, identity, trust, and webhook tools used in this guide, visit the GreenHelix developer documentation at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n---\n\n## GreenHelix Revenue Pipeline — Working Implementation\n\nThe code below uses the actual `greenhelix_trading` library classes. Every method call maps to a real GreenHelix Gateway tool. Copy this module into your project, set `GREENHELIX_API_KEY` and `GREENHELIX_AGENT_ID` in your environment, and run it.\n\n```python\n\"\"\"\nRevenue pipeline using the greenhelix_trading library.\n\nCovers:\n  1. Revenue tracking and service-level attribution\n  2. Cohort analysis with retention curves\n  3. Customer LTV calculation with segmentation\n  4. Multi-touch attribution modeling\n  5. Churn-aware revenue forecasting\n\nRequirements:\n    pip install greenhelix-trading\n\"\"\"\n\nimport os\nimport time\nimport statistics\nfrom datetime import datetime, timedelta\nfrom collections import defaultdict\nfrom typing import Optional\n\nfrom greenhelix_trading import RevenueTracker, CustomerAnalytics\n\n\n# ── Configuration ─────────────────────────────────────────────────────────────\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\nAGENT_ID = os.environ[\"GREENHELIX_AGENT_ID\"]\n\n\n# ── 1. Revenue Tracking Queries ──────────────────────────────────────────────\n\ndef build_revenue_dashboard(period: str = \"30d\") -> dict:\n    \"\"\"Pull billing, usage, and per-service revenue into a single view.\n\n    Uses RevenueTracker.get_revenue_summary for the billing aggregate,\n    RevenueTracker.get_revenue_by_service for category breakdown, and\n    RevenueTracker.get_usage_metrics for call-volume context.\n    \"\"\"\n    tracker = RevenueTracker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    # Billing aggregate for the period\n    billing = tracker.get_revenue_summary(period=period)\n\n    # Per-service breakdown via spending-by-category\n    services = tracker.get_revenue_by_service()\n\n    # Call-volume and usage metrics\n    usage = tracker.get_usage_metrics(period=period)\n\n    # Compute derived KPIs\n    total_revenue = float(billing.get(\"total_revenue\", 0))\n    total_calls = int(usage.get(\"total_calls\", 0))\n    revenue_per_call = total_revenue \u002F max(total_calls, 1)\n\n    categories = services.get(\"categories\", [])\n    top_service = max(\n        categories,\n        key=lambda c: float(c.get(\"total_spent\", 0)),\n        default=None,\n    )\n\n    return {\n        \"period\": period,\n        \"total_revenue\": round(total_revenue, 2),\n        \"total_calls\": total_calls,\n        \"revenue_per_call\": round(revenue_per_call, 6),\n        \"service_count\": len(categories),\n        \"top_service\": top_service,\n        \"billing_raw\": billing,\n        \"usage_raw\": usage,\n    }\n\n\ndef get_transaction_ledger(customer_id: Optional[str] = None) -> list:\n    \"\"\"Retrieve the full invoice ledger, optionally filtered by customer.\n\n    Uses RevenueTracker.get_transaction_history which wraps list_invoices.\n    Returns a list of invoice dicts sorted newest-first.\n    \"\"\"\n    tracker = RevenueTracker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n    raw = tracker.get_transaction_history(customer_id=customer_id)\n    invoices = raw.get(\"invoices\", [])\n    invoices.sort(key=lambda inv: inv.get(\"created_at\", \"\"), reverse=True)\n    return invoices\n\n\n# ── 2. Cohort Analysis ───────────────────────────────────────────────────────\n\ndef build_monthly_cohorts() -> dict:\n    \"\"\"Group customers by first-purchase month and compute retention.\n\n    Pulls all invoices via RevenueTracker.get_transaction_history,\n    assigns each customer to their first-purchase month, and tracks\n    how many remain active (have invoices) in subsequent months.\n    \"\"\"\n    tracker = RevenueTracker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n    analytics = CustomerAnalytics(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    # Fetch the full invoice ledger\n    raw = tracker.get_transaction_history()\n    invoices = raw.get(\"invoices\", [])\n\n    if not invoices:\n        return {\"cohorts\": {}, \"retention_matrix\": {}}\n\n    # Determine each customer's first-purchase month\n    customer_first_month = {}\n    customer_months = defaultdict(set)\n\n    for inv in invoices:\n        customer = inv.get(\"payer_agent_id\", \"unknown\")\n        date_str = inv.get(\"created_at\", \"\")\n        if not date_str:\n            continue\n        month_key = date_str[:7]  # \"YYYY-MM\"\n        if customer not in customer_first_month:\n            customer_first_month[customer] = month_key\n        customer_months[customer].add(month_key)\n\n    # Group customers into cohorts by first-purchase month\n    cohorts = defaultdict(list)\n    for customer, first_month in customer_first_month.items():\n        cohorts[first_month].append(customer)\n\n    # Build retention matrix\n    all_months = sorted({m for months in customer_months.values() for m in months})\n    retention_matrix = {}\n\n    for cohort_month in sorted(cohorts.keys()):\n        cohort_customers = cohorts[cohort_month]\n        initial_size = len(cohort_customers)\n        retention_matrix[cohort_month] = {\n            \"initial_customers\": initial_size,\n            \"periods\": [],\n        }\n        for i, month in enumerate(all_months):\n            if month \u003C cohort_month:\n                continue\n            active = sum(\n                1 for c in cohort_customers if month in customer_months[c]\n            )\n            retention_pct = (active \u002F initial_size * 100) if initial_size > 0 else 0\n            retention_matrix[cohort_month][\"periods\"].append({\n                \"month\": month,\n                \"period_number\": i - all_months.index(cohort_month),\n                \"active_customers\": active,\n                \"retention_pct\": round(retention_pct, 1),\n            })\n\n    # Also get the gateway-side cohort summary for cross-reference\n    gateway_cohort = analytics.build_cohort_summary(period=\"monthly\")\n\n    return {\n        \"cohorts\": {k: len(v) for k, v in cohorts.items()},\n        \"retention_matrix\": retention_matrix,\n        \"gateway_cohort_summary\": gateway_cohort,\n    }\n\n\n# ── 3. Customer LTV Calculation ──────────────────────────────────────────────\n\ndef calculate_customer_ltv(\n    customer_ids: list[str],\n    churn_override: Optional[float] = None,\n) -> dict:\n    \"\"\"Compute LTV for a set of customers using invoice history.\n\n    For each customer, uses CustomerAnalytics.get_customer_history to\n    pull their invoices, then calculates average monthly revenue. Churn\n    rate is estimated from the proportion of customers whose last invoice\n    is more than 30 days old, or can be provided as an override.\n\n    CustomerAnalytics.calculate_ltv returns the simple LTV = ARPU \u002F churn.\n    \"\"\"\n    analytics = CustomerAnalytics(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    histories = []\n    now = datetime.utcnow()\n    active_count = 0\n    churned_count = 0\n\n    for cid in customer_ids:\n        try:\n            history = analytics.get_customer_history(customer_id=cid)\n            invoices = history.get(\"invoices\", [])\n            if not invoices:\n                churned_count += 1\n                continue\n\n            # Sort invoices by date\n            invoices.sort(key=lambda x: x.get(\"created_at\", \"\"))\n            total_revenue = sum(float(inv.get(\"amount\", 0)) for inv in invoices)\n            first_date = invoices[0].get(\"created_at\", \"\")[:10]\n            last_date = invoices[-1].get(\"created_at\", \"\")[:10]\n\n            # Estimate tenure in months\n            try:\n                first_dt = datetime.fromisoformat(first_date)\n                last_dt = datetime.fromisoformat(last_date)\n                tenure_days = max((last_dt - first_dt).days, 1)\n                tenure_months = max(tenure_days \u002F 30.44, 1)\n                days_since_last = (now - last_dt).days\n            except (ValueError, TypeError):\n                tenure_months = 1\n                days_since_last = 0\n\n            avg_monthly = total_revenue \u002F tenure_months\n\n            if days_since_last > 30:\n                churned_count += 1\n            else:\n                active_count += 1\n\n            histories.append({\n                \"customer_id\": cid,\n                \"total_revenue\": round(total_revenue, 2),\n                \"tenure_months\": round(tenure_months, 1),\n                \"avg_monthly_revenue\": round(avg_monthly, 2),\n                \"days_since_last_invoice\": days_since_last,\n            })\n        except Exception:\n            churned_count += 1\n            continue\n\n    # Estimate churn rate\n    total_customers = active_count + churned_count\n    if churn_override is not None:\n        churn_rate = churn_override\n    elif total_customers > 0:\n        churn_rate = churned_count \u002F total_customers\n    else:\n        churn_rate = 0.10  # Default 10% monthly churn\n\n    churn_rate = max(churn_rate, 0.01)  # Floor at 1%\n\n    # Calculate aggregate LTV via the library\n    monthly_revenues = [h[\"avg_monthly_revenue\"] for h in histories if h[\"avg_monthly_revenue\"] > 0]\n    avg_arpu = statistics.mean(monthly_revenues) if monthly_revenues else 0\n\n    ltv_result = analytics.calculate_ltv(\n        avg_revenue_per_month=avg_arpu,\n        monthly_churn_rate=churn_rate,\n    )\n\n    # Segment customers into LTV tiers\n    individual_ltvs = [h[\"avg_monthly_revenue\"] \u002F churn_rate for h in histories if h[\"avg_monthly_revenue\"] > 0]\n    segments = {\"platinum\": [], \"gold\": [], \"silver\": [], \"bronze\": []}\n\n    for i, ltv_val in enumerate(individual_ltvs):\n        cid = histories[i][\"customer_id\"]\n        if ltv_val >= avg_arpu \u002F churn_rate * 2:\n            segments[\"platinum\"].append(cid)\n        elif ltv_val >= avg_arpu \u002F churn_rate:\n            segments[\"gold\"].append(cid)\n        elif ltv_val >= avg_arpu \u002F churn_rate * 0.5:\n            segments[\"silver\"].append(cid)\n        else:\n            segments[\"bronze\"].append(cid)\n\n    return {\n        \"ltv\": ltv_result,\n        \"churn_rate\": round(churn_rate, 4),\n        \"active_customers\": active_count,\n        \"churned_customers\": churned_count,\n        \"avg_monthly_revenue\": round(avg_arpu, 2),\n        \"expected_lifetime_months\": round(1 \u002F churn_rate, 1),\n        \"segments\": {tier: len(ids) for tier, ids in segments.items()},\n        \"segment_details\": segments,\n        \"customer_histories\": histories,\n    }\n\n\n# ── 4. Multi-Touch Attribution Modeling ──────────────────────────────────────\n\ndef build_attribution_model() -> dict:\n    \"\"\"Attribute revenue to acquisition channels using invoice metadata.\n\n    Uses RevenueTracker.get_transaction_history to pull all invoices,\n    then classifies each into marketplace \u002F direct \u002F referral based on\n    the invoice's metadata.source field.  Computes channel-level ARPU\n    and revenue share.\n    \"\"\"\n    tracker = RevenueTracker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    raw = tracker.get_transaction_history()\n    invoices = raw.get(\"invoices\", [])\n\n    channel_revenue = defaultdict(float)\n    channel_customers = defaultdict(set)\n    channel_count = defaultdict(int)\n\n    for inv in invoices:\n        amount = float(inv.get(\"amount\", 0))\n        customer = inv.get(\"payer_agent_id\", \"unknown\")\n        source = inv.get(\"metadata\", {}).get(\"source\", \"direct\")\n\n        # Channel classification\n        if \"marketplace\" in source.lower():\n            channel = \"marketplace\"\n        elif \"referral\" in source.lower() or inv.get(\"metadata\", {}).get(\"referrer\"):\n            channel = \"referral\"\n        else:\n            channel = \"direct\"\n\n        channel_revenue[channel] += amount\n        channel_customers[channel].add(customer)\n        channel_count[channel] += 1\n\n    total_revenue = sum(channel_revenue.values())\n\n    attribution = {}\n    for channel in [\"marketplace\", \"direct\", \"referral\"]:\n        rev = channel_revenue.get(channel, 0)\n        custs = len(channel_customers.get(channel, set()))\n        txns = channel_count.get(channel, 0)\n        attribution[channel] = {\n            \"revenue\": round(rev, 2),\n            \"revenue_share_pct\": round(rev \u002F max(total_revenue, 0.01) * 100, 1),\n            \"unique_customers\": custs,\n            \"transaction_count\": txns,\n            \"arpu\": round(rev \u002F max(custs, 1), 2),\n            \"avg_transaction\": round(rev \u002F max(txns, 1), 4),\n        }\n\n    return {\n        \"total_revenue\": round(total_revenue, 2),\n        \"channels\": attribution,\n        \"concentration_risk\": _assess_concentration_risk(attribution),\n    }\n\n\ndef _assess_concentration_risk(attribution: dict) -> dict:\n    \"\"\"Evaluate revenue concentration across channels.\n\n    A healthy business derives no more than 50% from any single channel.\n    \"\"\"\n    shares = {ch: data[\"revenue_share_pct\"] for ch, data in attribution.items()}\n    max_channel = max(shares, key=shares.get) if shares else \"none\"\n    max_share = shares.get(max_channel, 0)\n\n    if max_share >= 80:\n        risk = \"critical\"\n        recommendation = f\"Dangerously concentrated in {max_channel}. Diversify immediately.\"\n    elif max_share >= 60:\n        risk = \"high\"\n        recommendation = f\"Heavy reliance on {max_channel}. Build alternative channels.\"\n    elif max_share >= 40:\n        risk = \"moderate\"\n        recommendation = \"Reasonable distribution. Continue monitoring.\"\n    else:\n        risk = \"low\"\n        recommendation = \"Well-diversified revenue. Maintain current strategy.\"\n\n    return {\n        \"dominant_channel\": max_channel,\n        \"dominant_share_pct\": max_share,\n        \"risk_level\": risk,\n        \"recommendation\": recommendation,\n    }\n\n\n# ── 5. Churn-Aware Revenue Forecasting ───────────────────────────────────────\n\ndef forecast_revenue(\n    customer_ids: list[str],\n    months_ahead: int = 6,\n) -> dict:\n    \"\"\"Project revenue forward using churn risk and LTV data.\n\n    For each customer, uses CustomerAnalytics.calculate_churn_risk to\n    classify risk as high\u002Fmedium\u002Flow, then applies survival probabilities\n    to their average monthly revenue to build a forward projection.\n    \"\"\"\n    analytics = CustomerAnalytics(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n    tracker = RevenueTracker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    # Survival probability per month by risk tier\n    monthly_survival = {\"low\": 0.95, \"medium\": 0.85, \"high\": 0.65}\n\n    customer_projections = []\n\n    for cid in customer_ids:\n        try:\n            # Get churn risk classification\n            risk_result = analytics.calculate_churn_risk(customer_id=cid)\n            risk_tier = risk_result.get(\"risk\", \"medium\")\n\n            # Get customer invoice history for ARPU\n            history = tracker.get_transaction_history(customer_id=cid)\n            invoices = history.get(\"invoices\", [])\n            if not invoices:\n                continue\n\n            total_rev = sum(float(inv.get(\"amount\", 0)) for inv in invoices)\n            # Estimate months active from first to last invoice\n            dates = sorted(inv.get(\"created_at\", \"\")[:10] for inv in invoices)\n            try:\n                first_dt = datetime.fromisoformat(dates[0])\n                last_dt = datetime.fromisoformat(dates[-1])\n                months_active = max((last_dt - first_dt).days \u002F 30.44, 1)\n            except (ValueError, TypeError, IndexError):\n                months_active = 1\n\n            avg_monthly = total_rev \u002F months_active\n            survival = monthly_survival.get(risk_tier, 0.85)\n\n            # Project forward\n            projections = []\n            for month in range(1, months_ahead + 1):\n                survival_at_month = survival ** month\n                expected_revenue = avg_monthly * survival_at_month\n                projections.append({\n                    \"month\": month,\n                    \"survival_probability\": round(survival_at_month, 4),\n                    \"expected_revenue\": round(expected_revenue, 2),\n                })\n\n            customer_projections.append({\n                \"customer_id\": cid,\n                \"risk_tier\": risk_tier,\n                \"avg_monthly_revenue\": round(avg_monthly, 2),\n                \"projections\": projections,\n            })\n        except Exception:\n            continue\n\n    # Aggregate: sum expected revenue across all customers per month\n    monthly_totals = defaultdict(float)\n    for cp in customer_projections:\n        for proj in cp[\"projections\"]:\n            monthly_totals[proj[\"month\"]] += proj[\"expected_revenue\"]\n\n    forecast = [\n        {\"month\": m, \"expected_revenue\": round(rev, 2)}\n        for m, rev in sorted(monthly_totals.items())\n    ]\n\n    # At-risk revenue: customers flagged as high churn risk\n    at_risk_customers = analytics.get_at_risk_customers(threshold=10)\n\n    return {\n        \"months_ahead\": months_ahead,\n        \"customer_count\": len(customer_projections),\n        \"monthly_forecast\": forecast,\n        \"total_forecast_revenue\": round(sum(f[\"expected_revenue\"] for f in forecast), 2),\n        \"at_risk_summary\": at_risk_customers,\n        \"customer_detail\": customer_projections,\n    }\n\n\n# ── Main: Run the Full Pipeline ──────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n    import json\n\n    print(\"=\" * 72)\n    print(\"GreenHelix Revenue Pipeline\")\n    print(\"=\" * 72)\n\n    # Step 1: Revenue dashboard\n    print(\"\\n[1\u002F5] Building revenue dashboard...\")\n    dashboard = build_revenue_dashboard(period=\"30d\")\n    print(f\"  Total revenue: ${dashboard['total_revenue']}\")\n    print(f\"  Total calls: {dashboard['total_calls']}\")\n    print(f\"  Revenue\u002Fcall: ${dashboard['revenue_per_call']}\")\n\n    # Step 2: Attribution model\n    print(\"\\n[2\u002F5] Building attribution model...\")\n    attribution = build_attribution_model()\n    for ch, data in attribution[\"channels\"].items():\n        print(f\"  {ch}: ${data['revenue']} ({data['revenue_share_pct']}%)\")\n    print(f\"  Concentration risk: {attribution['concentration_risk']['risk_level']}\")\n\n    # Step 3: Cohort analysis\n    print(\"\\n[3\u002F5] Building monthly cohorts...\")\n    cohorts = build_monthly_cohorts()\n    for month, count in sorted(cohorts[\"cohorts\"].items()):\n        print(f\"  {month}: {count} customers\")\n\n    # Step 4: LTV calculation (example customer IDs)\n    print(\"\\n[4\u002F5] Calculating customer LTV...\")\n    # Replace with your actual customer agent IDs\n    sample_customers = [\n        \"customer-agent-001\", \"customer-agent-002\",\n        \"customer-agent-003\", \"customer-agent-004\",\n    ]\n    ltv_report = calculate_customer_ltv(sample_customers)\n    print(f\"  LTV: ${ltv_report['ltv']['ltv']}\")\n    print(f\"  Churn rate: {ltv_report['churn_rate'] * 100:.1f}%\")\n    print(f\"  Expected lifetime: {ltv_report['expected_lifetime_months']} months\")\n    print(f\"  Segments: {ltv_report['segments']}\")\n\n    # Step 5: Revenue forecast\n    print(\"\\n[5\u002F5] Forecasting revenue (6 months)...\")\n    forecast = forecast_revenue(sample_customers, months_ahead=6)\n    for entry in forecast[\"monthly_forecast\"]:\n        print(f\"  Month +{entry['month']}: ${entry['expected_revenue']}\")\n    print(f\"  Total 6-month forecast: ${forecast['total_forecast_revenue']}\")\n\n    print(\"\\n\" + \"=\" * 72)\n    print(\"Pipeline complete.\")\n    print(\"=\" * 72)\n```\n\n","# Agent Revenue Analytics: Attribution, LTV, Cohorts, and Pricing Optimization for AI Agent Services\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\n\nYour agent service is live. The billing is working. Customers are calling your tools, money is flowing through the gateway, and your cost management is solid -- you followed the FinOps Playbook and every agent has its own wallet with budget caps. But here is the problem: you have no idea if you are growing. You know what you spend. You do not know what you earn. You cannot answer the five questions that determine whether your agent service is a business or a hobby: Which services generate the most revenue? Who are your best customers and what are they worth over their lifetime? When do customers churn and why? What price maximizes your revenue? And how do you compare to competitors in the marketplace?\nThis is the revenue gap. Cost management tells you how efficiently you operate. Revenue analytics tells you whether the operation is worth running. The FinOps Playbook (Product #6) gave you the cost layer. The Negotiation Strategies guide (Product #14) gave you pricing tactics. This guide gives you the measurement layer that sits between them: the data infrastructure to track revenue attribution, calculate customer lifetime value, build cohort retention curves, predict churn before it happens, optimize pricing from historical data, and monitor competitors -- all from the billing, payments, marketplace, and identity data already flowing through the GreenHelix gateway.\nRevenueCat's 2026 State of Subscription Apps report found that AI-powered applications earn 41% more revenue per user than traditional apps but churn 30% faster. That asymmetry is the central challenge of agent commerce economics. Your agent service likely follows the same pattern: high initial monetization as customers integrate your tools into their workflows, followed by rapid attrition as they find alternatives, build in-house replacements, or simply stop needing the service. Without revenue analytics, you experience this as a mysterious plateau in monthly income. With revenue analytics, you see the cohort curves, identify the churn inflection point, calculate the price that maximizes lifetime revenue, and intervene before customers leave.\n\n## What You'll Learn\n- Chapter 1: The Revenue Gap in Agent Commerce\n- Chapter 2: Revenue Attribution\n- Chapter 3: Customer Lifetime Value\n- Chapter 4: Cohort Analysis\n- Chapter 5: Churn Prediction\n- Chapter 6: Pricing Optimization\n- Chapter 7: Competitive Intelligence\n- Chapter 8: Revenue Dashboard and Alerts\n- GreenHelix Revenue Pipeline — Working Implementation\n\n## Full Guide\n\n# Agent Revenue Analytics: Attribution, LTV, Cohorts, and Pricing Optimization for AI Agent Services\n\nYour agent service is live. The billing is working. Customers are calling your tools, money is flowing through the gateway, and your cost management is solid -- you followed the FinOps Playbook and every agent has its own wallet with budget caps. But here is the problem: you have no idea if you are growing. You know what you spend. You do not know what you earn. You cannot answer the five questions that determine whether your agent service is a business or a hobby: Which services generate the most revenue? Who are your best customers and what are they worth over their lifetime? When do customers churn and why? What price maximizes your revenue? And how do you compare to competitors in the marketplace?\n\nThis is the revenue gap. Cost management tells you how efficiently you operate. Revenue analytics tells you whether the operation is worth running. The FinOps Playbook (Product #6) gave you the cost layer. The Negotiation Strategies guide (Product #14) gave you pricing tactics. This guide gives you the measurement layer that sits between them: the data infrastructure to track revenue attribution, calculate customer lifetime value, build cohort retention curves, predict churn before it happens, optimize pricing from historical data, and monitor competitors -- all from the billing, payments, marketplace, and identity data already flowing through the GreenHelix gateway.\n\nRevenueCat's 2026 State of Subscription Apps report found that AI-powered applications earn 41% more revenue per user than traditional apps but churn 30% faster. That asymmetry is the central challenge of agent commerce economics. Your agent service likely follows the same pattern: high initial monetization as customers integrate your tools into their workflows, followed by rapid attrition as they find alternatives, build in-house replacements, or simply stop needing the service. Without revenue analytics, you experience this as a mysterious plateau in monthly income. With revenue analytics, you see the cohort curves, identify the churn inflection point, calculate the price that maximizes lifetime revenue, and intervene before customers leave.\n\nEvery code example in this guide calls the GreenHelix A2A Commerce Gateway via the REST API (`POST \u002Fv1\u002F{tool}`) with a JSON body of `{\"tool\": \"tool_name\", \"input\": {...}}`. Authentication is via Bearer token. Every class and function is production-ready Python using the `requests` library. Define the core `RevenueAnalytics` class once and reference it throughout.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [The Revenue Gap in Agent Commerce](#chapter-1-the-revenue-gap-in-agent-commerce)\n2. [Revenue Attribution](#chapter-2-revenue-attribution)\n3. [Customer Lifetime Value](#chapter-3-customer-lifetime-value)\n4. [Cohort Analysis](#chapter-4-cohort-analysis)\n5. [Churn Prediction](#chapter-5-churn-prediction)\n6. [Pricing Optimization](#chapter-6-pricing-optimization)\n7. [Competitive Intelligence](#chapter-7-competitive-intelligence)\n8. [Revenue Dashboard and Alerts](#chapter-8-revenue-dashboard-and-alerts)\n\n---\n\n## Chapter 1: The Revenue Gap in Agent Commerce\n\n### Cost Management Is Not Revenue Management\n\nThe FinOps movement has trained the industry to obsess over cost. Every agent framework tutorial covers budget caps. Every infrastructure guide explains how to set spend alerts. Cloud providers publish cost optimization whitepapers quarterly. This emphasis is correct -- uncontrolled agent costs can destroy margins overnight -- but it creates a dangerous blind spot. Teams that can tell you their cost per tool call to four decimal places often cannot answer \"what is our revenue per customer this month?\" to the nearest dollar.\n\nCost management and revenue management are fundamentally different disciplines. Cost management is about efficiency: reducing the denominator. Revenue management is about growth: increasing the numerator. You can optimize costs to zero and still fail because revenue went to zero first. The companies that win in agent commerce are the ones that measure both sides of the equation.\n\nConsider a concrete example. You operate a data enrichment agent service. Your FinOps dashboard shows that your cost per enrichment call is $0.003, down from $0.005 last quarter -- a 40% efficiency improvement. You celebrate. But what you do not see is that your revenue per enrichment call dropped from $0.015 to $0.008 because a competitor entered the marketplace at $0.009 and your highest-volume customer switched to them. Your margin per call actually shrank from $0.010 to $0.005. The cost optimization masked a revenue crisis.\n\n### AI Apps: High Revenue, Higher Churn\n\nRevenueCat's 2026 analysis of 30,000 subscription apps revealed a striking pattern in AI-powered applications. Compared to traditional SaaS:\n\n- **Revenue per user is 41% higher.** AI apps command premium pricing because they deliver immediate, measurable value. An agent that saves four hours of manual data processing per week justifies a higher price than a traditional tool that merely organizes a workflow.\n- **Churn is 30% faster.** AI apps lose subscribers more quickly because (a) the novelty effect is stronger -- users try the AI tool, get excited, then normalize it, (b) switching costs are lower -- if the value comes from the model, any wrapper around a comparable model is substitutable, and (c) expectations are higher -- a traditional app that works adequately retains users; an AI app that is merely adequate gets replaced by one that is impressive.\n- **Net revenue per user over 12 months is only 8% higher** when you account for the elevated churn. The revenue advantage nearly evaporates.\n\nFor agent-to-agent commerce, the pattern intensifies. When your customers are themselves AI agents, the switching decision is not emotional -- it is algorithmic. An orchestrator agent evaluating your enrichment service against a competitor will switch the moment the competitor's price-adjusted quality score exceeds yours. There is no loyalty, no switching friction from muscle memory, no reluctance to learn a new interface. The agent's code changes one URL and one API key.\n\nThis means revenue analytics for agent services is not optional -- it is survival. You need to see the churn coming before it happens, understand which cohorts retain and which do not, and continuously optimize the price point that maximizes lifetime revenue rather than per-transaction revenue.\n\n### Why Traditional SaaS Metrics Need Adaptation\n\nStandard SaaS metrics -- MRR, ARR, churn rate, LTV, CAC -- were designed for subscription products with human customers. Agent commerce has three structural differences that require adaptation.\n\n**First, usage is bursty and non-uniform.** A human user of a SaaS product logs in roughly daily with similar session patterns. An agent customer might call your service 10,000 times on Monday and zero times on Tuesday because its orchestrator only triggers your tool when a specific condition is met. Monthly Recurring Revenue (MRR) is still meaningful, but you need to complement it with usage-weighted metrics.\n\n**Second, customers are identified by agent IDs, not email addresses.** You cannot send a churn-risk customer a winback email. You can adjust pricing, improve response times, or register a webhook to detect the moment their usage drops. Your retention interventions are programmatic, not personal.\n\n**Third, pricing is often per-call rather than per-seat.** The LTV calculation changes when revenue is proportional to usage rather than a fixed monthly fee. An agent customer using your service 50,000 times per month at $0.001 per call is worth $50\u002Fmonth -- the same as a subscription customer paying $50\u002Fmonth -- but the revenue dynamics are entirely different. Usage-based revenue can grow without the customer explicitly upgrading, but it can also drop to zero without the customer explicitly canceling.\n\nThis guide adapts every traditional SaaS metric to the realities of agent commerce, using the data already available through GreenHelix billing, payments, and marketplace APIs.\n\n---\n\n## Chapter 2: Revenue Attribution\n\n### Knowing Where Your Revenue Comes From\n\nRevenue attribution answers a deceptively simple question: which of your agent services generated which revenue, and through which channel? When you operate multiple agent services -- a data enrichment tool, a translation tool, and a sentiment analysis tool -- and revenue arrives as aggregated billing summaries, you need to decompose that revenue by service, by customer, and by acquisition channel.\n\nIn agent commerce, there are three primary revenue channels:\n\n- **Marketplace**: Customers discover your service through `search_services` on the GreenHelix marketplace. These are organic, low-acquisition-cost customers.\n- **Direct**: Customers integrate your service directly via API key sharing, documentation, or partner integrations. These often have higher acquisition costs but stronger retention.\n- **Referral**: Customers arrive because another agent in their workflow recommended or required your service as a dependency. These are the highest-value customers because the switching cost is embedded in their workflow architecture.\n\nThe challenge is that GreenHelix billing data does not natively tag revenue by channel. You need to infer it from the combination of billing summaries, invoice metadata, and marketplace activity. The `RevenueTracker` class below builds this attribution layer.\n\n### The RevenueTracker Class\n\nThis is the core class for this guide. It wraps every GreenHelix tool used across all eight chapters. Define it once and extend it with methods as we progress.\n\n```python\nimport requests\nimport json\nimport time\nimport math\nimport statistics\nfrom datetime import datetime, timedelta\nfrom typing import Optional\nfrom collections import defaultdict\n\n\nclass RevenueTracker:\n    \"\"\"Revenue analytics client for the GreenHelix A2A Commerce Gateway.\n\n    Wraps billing, payments, marketplace, identity, trust, and webhook\n    tools into a revenue measurement and optimization interface.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Revenue Data Retrieval ----------------------------------------\n\n    def get_billing_summary(self, period: str = \"monthly\") -> dict:\n        \"\"\"Get billing summary for the agent's services.\"\"\"\n        return self._execute(\"get_billing_summary\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n        })\n\n    def get_usage_analytics(\n        self,\n        start_date: str,\n        end_date: str,\n    ) -> dict:\n        \"\"\"Get usage analytics over a date range.\"\"\"\n        return self._execute(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"start_date\": start_date,\n            \"end_date\": end_date,\n        })\n\n    def get_spending_by_category(\n        self,\n        start_date: Optional[str] = None,\n        end_date: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Get spending broken down by category.\"\"\"\n        payload = {\"agent_id\": self.agent_id}\n        if start_date:\n            payload[\"start_date\"] = start_date\n        if end_date:\n            payload[\"end_date\"] = end_date\n        return self._execute(\"get_spending_by_category\", payload)\n\n    def list_invoices(\n        self,\n        status: Optional[str] = None,\n        limit: int = 100,\n    ) -> dict:\n        \"\"\"List invoices with optional status filter.\"\"\"\n        payload = {\"agent_id\": self.agent_id, \"limit\": limit}\n        if status:\n            payload[\"status\"] = status\n        return self._execute(\"list_invoices\", payload)\n\n    def get_payment_intent(self, payment_id: str) -> dict:\n        \"\"\"Get details of a specific payment intent.\"\"\"\n        return self._execute(\"get_payment_intent\", {\n            \"payment_id\": payment_id,\n        })\n\n    # -- Marketplace Data ----------------------------------------------\n\n    def search_services(\n        self,\n        query: str,\n        category: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Search the marketplace for services.\"\"\"\n        payload = {\"query\": query}\n        if category:\n            payload[\"category\"] = category\n        return self._execute(\"search_services\", payload)\n\n    def get_service_ratings(self, service_id: str) -> dict:\n        \"\"\"Get ratings for a specific service.\"\"\"\n        return self._execute(\"get_service_ratings\", {\n            \"service_id\": service_id,\n        })\n\n    # -- Identity and Trust --------------------------------------------\n\n    def get_agent_leaderboard(\n        self,\n        metric: str = \"revenue\",\n    ) -> dict:\n        \"\"\"Get agent leaderboard by metric.\"\"\"\n        return self._execute(\"get_agent_leaderboard\", {\n            \"metric\": metric,\n        })\n\n    def search_agents_by_metrics(\n        self,\n        metric: str,\n        min_value: Optional[float] = None,\n        max_value: Optional[float] = None,\n    ) -> dict:\n        \"\"\"Search agents filtered by metric thresholds.\"\"\"\n        payload = {\"metric\": metric}\n        if min_value is not None:\n            payload[\"min_value\"] = str(min_value)\n        if max_value is not None:\n            payload[\"max_value\"] = str(max_value)\n        return self._execute(\"search_agents_by_metrics\", payload)\n\n    def get_agent_reputation(self, target_agent_id: str) -> dict:\n        \"\"\"Get reputation data for an agent.\"\"\"\n        return self._execute(\"get_agent_reputation\", {\n            \"agent_id\": target_agent_id,\n        })\n\n    # -- Webhooks ------------------------------------------------------\n\n    def register_webhook(\n        self,\n        url: str,\n        events: list[str],\n        config: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Register a webhook for real-time events.\"\"\"\n        payload = {\n            \"url\": url,\n            \"events\": events,\n        }\n        if config:\n            payload[\"config\"] = config\n        return self._execute(\"register_webhook\", payload)\n```\n\n### Building Revenue Attribution\n\nWith the core class defined, here is the revenue attribution logic. The method pulls invoice data, categorizes each transaction by source channel, and aggregates revenue by service and channel.\n\n```python\n    # -- Revenue Attribution -------------------------------------------\n\n    def get_revenue_summary(\n        self,\n        start_date: str,\n        end_date: str,\n    ) -> dict:\n        \"\"\"Build a revenue summary with attribution by service and channel.\n\n        Combines billing summaries, invoice data, and usage analytics\n        to attribute revenue to specific services and acquisition channels.\n        \"\"\"\n        # Pull the raw data\n        billing = self.get_billing_summary(period=\"monthly\")\n        usage = self.get_usage_analytics(start_date, end_date)\n        invoices = self.list_invoices(status=\"paid\")\n\n        # Aggregate revenue by service\n        revenue_by_service = defaultdict(float)\n        revenue_by_channel = defaultdict(float)\n        transactions = []\n\n        for invoice in invoices.get(\"invoices\", []):\n            amount = float(invoice.get(\"amount\", 0))\n            service = invoice.get(\"service_id\", \"unknown\")\n            source = invoice.get(\"metadata\", {}).get(\"source\", \"direct\")\n\n            # Classify the acquisition channel\n            channel = self._classify_channel(source, invoice)\n\n            revenue_by_service[service] += amount\n            revenue_by_channel[channel] += amount\n            transactions.append({\n                \"invoice_id\": invoice.get(\"id\"),\n                \"amount\": amount,\n                \"service\": service,\n                \"channel\": channel,\n                \"date\": invoice.get(\"created_at\"),\n            })\n\n        total_revenue = sum(revenue_by_service.values())\n\n        return {\n            \"period\": {\"start\": start_date, \"end\": end_date},\n            \"total_revenue\": round(total_revenue, 2),\n            \"revenue_by_service\": {\n                k: round(v, 2) for k, v in revenue_by_service.items()\n            },\n            \"revenue_by_channel\": {\n                k: round(v, 2) for k, v in revenue_by_channel.items()\n            },\n            \"transaction_count\": len(transactions),\n            \"billing_summary\": billing,\n            \"usage_summary\": usage,\n        }\n\n    def _classify_channel(self, source: str, invoice: dict) -> str:\n        \"\"\"Classify an invoice into an acquisition channel.\n\n        Uses heuristics based on invoice metadata and source field:\n        - 'marketplace' if discovered via search_services\n        - 'referral' if another agent's workflow triggered it\n        - 'direct' for API key integrations and manual setups\n        \"\"\"\n        if source == \"marketplace\" or \"marketplace\" in source:\n            return \"marketplace\"\n        if source == \"referral\" or invoice.get(\"metadata\", {}).get(\"referrer\"):\n            return \"referral\"\n        return \"direct\"\n\n    def get_revenue_by_service(self) -> dict:\n        \"\"\"Get current-period revenue broken down by service.\n\n        Uses spending-by-category as a proxy: your customers' spending\n        on your services is your revenue.\n        \"\"\"\n        categories = self.get_spending_by_category()\n        services = {}\n\n        for category in categories.get(\"categories\", []):\n            services[category[\"name\"]] = {\n                \"revenue\": float(category.get(\"total_spent\", 0)),\n                \"call_count\": int(category.get(\"call_count\", 0)),\n                \"avg_revenue_per_call\": round(\n                    float(category.get(\"total_spent\", 0))\n                    \u002F max(int(category.get(\"call_count\", 0)), 1),\n                    6,\n                ),\n            }\n\n        return services\n```\n\n### Interpreting Attribution Data\n\nRevenue attribution reveals three patterns that are invisible in aggregate billing data.\n\n**Service concentration risk.** If 80% of your revenue comes from one service, you have a single point of failure. A competitor undercutting that service or a platform change that degrades its performance will crater your revenue. Diversification across services is as important for agent operators as portfolio diversification is for investors.\n\n**Channel dependency.** Marketplace-sourced revenue is low-cost but volatile -- you are at the mercy of search algorithm changes and competitor listings. Direct revenue is higher-cost to acquire but stickier. Referral revenue is the gold standard: it means your service is embedded in another agent's workflow, making switching costly. A healthy agent business derives no more than 50% of revenue from any single channel.\n\n**Revenue-per-call divergence.** When your average revenue per call differs significantly across services, it signals either a pricing opportunity (raise the price on the high-demand service) or a cost problem (the low-revenue service may not be worth maintaining). The `avg_revenue_per_call` metric in the code above makes this divergence visible.\n\n---\n\n## Chapter 3: Customer Lifetime Value\n\n### LTV for Agent-to-Agent Services\n\nCustomer Lifetime Value (LTV) is the total revenue you expect from a customer over their entire relationship with your service. In traditional SaaS, LTV is the primary metric for deciding how much to spend on acquisition, which segments to prioritize, and whether the business model is sustainable. The rule of thumb: LTV should be at least 3x the Customer Acquisition Cost (CAC). If it costs you $10 to acquire a customer through marketplace advertising, that customer should generate at least $30 in lifetime revenue.\n\nFor agent-to-agent commerce, LTV has a structural difference. Your customers are agents, and agents have two lifetime horizons:\n\n- **Agent lifetime**: How long the customer agent itself exists. If the customer is a research agent spun up for a three-month project, your maximum relationship duration is three months regardless of satisfaction.\n- **Operator lifetime**: How long the human or organization behind the customer agent continues to use agent services. An operator who shuts down one agent might launch a successor that uses your service again.\n\nThe practical implication is that LTV in agent commerce often has a shorter but more predictable horizon than in human SaaS. Agents do not have emotional loyalty, but they also do not have emotional whims. An agent that finds value in your service at day 30 will still find value at day 90 unless the external context changes. This makes LTV estimation more reliable once you have enough cohort data.\n\n### Simple LTV Calculation\n\nThe simplest LTV formula is:\n\n```\nLTV = Average Revenue Per Period \u002F Churn Rate\n```\n\nIf your average customer generates $45\u002Fmonth in revenue and your monthly churn rate is 15%, then:\n\n```\nLTV = $45 \u002F 0.15 = $300\n```\n\nThis formula assumes constant revenue per period and constant churn rate, which are obviously simplifications. But it gives you a useful baseline. Here is the implementation using GreenHelix billing data.\n\n```python\n    # -- Customer Lifetime Value ---------------------------------------\n\n    def get_customer_history(\n        self,\n        customer_agent_id: str,\n    ) -> dict:\n        \"\"\"Build a complete revenue history for a specific customer agent.\n\n        Pulls all invoices from a customer and computes per-period\n        revenue, tenure, and activity patterns.\n        \"\"\"\n        invoices = self.list_invoices()\n        customer_invoices = [\n            inv for inv in invoices.get(\"invoices\", [])\n            if inv.get(\"payer_agent_id\") == customer_agent_id\n        ]\n\n        if not customer_invoices:\n            return {\n                \"customer_agent_id\": customer_agent_id,\n                \"total_revenue\": 0,\n                \"tenure_days\": 0,\n                \"invoice_count\": 0,\n                \"monthly_revenue\": [],\n            }\n\n        # Sort by date\n        customer_invoices.sort(key=lambda x: x.get(\"created_at\", \"\"))\n\n        first_date = datetime.fromisoformat(\n            customer_invoices[0][\"created_at\"].replace(\"Z\", \"+00:00\")\n        )\n        last_date = datetime.fromisoformat(\n            customer_invoices[-1][\"created_at\"].replace(\"Z\", \"+00:00\")\n        )\n        tenure_days = max((last_date - first_date).days, 1)\n\n        # Aggregate by month\n        monthly = defaultdict(float)\n        total = 0.0\n        for inv in customer_invoices:\n            amount = float(inv.get(\"amount\", 0))\n            total += amount\n            month_key = inv[\"created_at\"][:7]  # YYYY-MM\n            monthly[month_key] += amount\n\n        monthly_revenue = [\n            {\"month\": k, \"revenue\": round(v, 2)}\n            for k, v in sorted(monthly.items())\n        ]\n\n        return {\n            \"customer_agent_id\": customer_agent_id,\n            \"total_revenue\": round(total, 2),\n            \"tenure_days\": tenure_days,\n            \"tenure_months\": round(tenure_days \u002F 30.44, 1),\n            \"invoice_count\": len(customer_invoices),\n            \"first_invoice\": customer_invoices[0][\"created_at\"],\n            \"last_invoice\": customer_invoices[-1][\"created_at\"],\n            \"avg_monthly_revenue\": round(\n                total \u002F max(len(monthly), 1), 2\n            ),\n            \"monthly_revenue\": monthly_revenue,\n        }\n\n    def calculate_ltv(\n        self,\n        customer_histories: list[dict],\n        churn_rate: Optional[float] = None,\n    ) -> dict:\n        \"\"\"Calculate customer lifetime value from a set of customer histories.\n\n        If churn_rate is not provided, estimates it from the data by\n        looking at the proportion of customers whose last invoice is\n        more than 30 days old (presumed churned).\n        \"\"\"\n        if not customer_histories:\n            return {\"ltv\": 0, \"avg_revenue_per_month\": 0, \"churn_rate\": 0}\n\n        # Calculate average monthly revenue across all customers\n        monthly_revenues = []\n        active_count = 0\n        churned_count = 0\n        now = datetime.utcnow()\n        churn_threshold_days = 30\n\n        for history in customer_histories:\n            avg_monthly = history.get(\"avg_monthly_revenue\", 0)\n            if avg_monthly > 0:\n                monthly_revenues.append(avg_monthly)\n\n            # Estimate churn if not provided\n            if churn_rate is None:\n                last_invoice = history.get(\"last_invoice\", \"\")\n                if last_invoice:\n                    last_date = datetime.fromisoformat(\n                        last_invoice.replace(\"Z\", \"+00:00\")\n                    ).replace(tzinfo=None)\n                    days_since_last = (now - last_date).days\n                    if days_since_last > churn_threshold_days:\n                        churned_count += 1\n                    else:\n                        active_count += 1\n\n        avg_revenue_per_month = (\n            statistics.mean(monthly_revenues) if monthly_revenues else 0\n        )\n\n        # Estimate churn rate if not provided\n        if churn_rate is None:\n            total_customers = active_count + churned_count\n            if total_customers > 0:\n                churn_rate = churned_count \u002F total_customers\n            else:\n                churn_rate = 0.10  # Default assumption: 10% monthly churn\n\n        # Guard against division by zero\n        if churn_rate \u003C= 0:\n            churn_rate = 0.01  # Assume 1% minimum churn\n\n        ltv = avg_revenue_per_month \u002F churn_rate\n\n        # Also calculate median and percentile LTVs\n        individual_ltvs = [\n            rev \u002F churn_rate for rev in monthly_revenues\n        ]\n\n        return {\n            \"ltv\": round(ltv, 2),\n            \"avg_revenue_per_month\": round(avg_revenue_per_month, 2),\n            \"churn_rate\": round(churn_rate, 4),\n            \"expected_lifetime_months\": round(1 \u002F churn_rate, 1),\n            \"customer_count\": len(customer_histories),\n            \"active_count\": active_count,\n            \"churned_count\": churned_count,\n            \"ltv_median\": round(\n                statistics.median(individual_ltvs), 2\n            ) if individual_ltvs else 0,\n            \"ltv_p25\": round(\n                sorted(individual_ltvs)[len(individual_ltvs) \u002F\u002F 4], 2\n            ) if len(individual_ltvs) >= 4 else 0,\n            \"ltv_p75\": round(\n                sorted(individual_ltvs)[3 * len(individual_ltvs) \u002F\u002F 4], 2\n            ) if len(individual_ltvs) >= 4 else 0,\n        }\n```\n\n### Using LTV to Drive Decisions\n\nLTV is not a vanity metric. It directly informs three operational decisions:\n\n**Acquisition spending.** If your LTV is $300 and your target LTV\u002FCAC ratio is 3:1, you can spend up to $100 to acquire a customer. In agent commerce, acquisition cost might be the marketplace listing fee, the cost of a free trial, or the engineering time to build an integration. If your LTV is $50, spending $100 on an integration is irrational.\n\n**Tier prioritization.** Segment your customers by LTV. High-LTV customers get faster response times, priority support, and custom pricing. Low-LTV customers get standard service. The GreenHelix tier system (free, pro, enterprise) maps directly to LTV segments. An agent customer generating $500\u002Fmonth in revenue justifies pro-tier treatment with lower per-call costs and dedicated endpoints.\n\n**Churn investment.** The cost of retaining an existing customer should be proportional to their remaining LTV. If a customer with $200 of remaining LTV shows churn risk signals, investing $20 in a retention offer (a temporary discount, a free feature upgrade) has a 10:1 expected return. If a customer with $10 of remaining LTV shows the same signals, let them go.\n\n---\n\n## Chapter 4: Cohort Analysis\n\n### Why Cohorts Matter More Than Averages\n\nYour overall monthly churn rate is 12%. Is that good or bad? You cannot tell without cohort analysis. A 12% average might mean every cohort churns at 12% -- a consistent, predictable pattern. Or it might mean your January cohort churns at 5% while your March cohort churns at 25% because you made a pricing change in February that attracted price-sensitive customers who do not retain. The average hides the story. Cohorts reveal it.\n\nA cohort is a group of customers who share a common characteristic, usually the period when they first became a customer. The January 2026 cohort is every agent that first called your service in January. You track each cohort's revenue, retention, and usage over time to see how customer behavior evolves.\n\nFor agent services, cohort analysis answers three critical questions:\n\n1. **Are newer customers better or worse than older ones?** If your March cohort retains better than your January cohort, something you changed is working. If retention is declining cohort over cohort, you have a product or market problem.\n2. **When does churn stabilize?** Most agent services see high churn in the first 7-14 days (the evaluation period) followed by a plateau. Knowing this inflection point tells you when a customer has \"stuck\" and their lifetime revenue becomes predictable.\n3. **What is the revenue curve shape?** Some services see flat revenue per customer (subscription-like). Others see growing revenue (expansion) as customers integrate deeper. Others see declining revenue (contraction) as customers optimize their usage. The cohort curve tells you which pattern you have.\n\n### Building Cohorts from Billing Data\n\n```python\n    # -- Cohort Analysis -----------------------------------------------\n\n    def build_cohorts(\n        self,\n        invoices: Optional[list[dict]] = None,\n        cohort_period: str = \"monthly\",\n    ) -> dict:\n        \"\"\"Build customer cohorts from invoice data.\n\n        Groups customers by their first purchase period and tracks\n        their revenue and retention over subsequent periods.\n\n        Args:\n            invoices: Pre-fetched invoice list, or None to fetch live.\n            cohort_period: 'monthly' or 'weekly' grouping.\n        \"\"\"\n        if invoices is None:\n            raw = self.list_invoices(limit=1000)\n            invoices = raw.get(\"invoices\", [])\n\n        if not invoices:\n            return {\"cohorts\": {}, \"retention_matrix\": {}}\n\n        # Determine each customer's first purchase date\n        customer_first_seen = {}\n        customer_periods = defaultdict(lambda: defaultdict(float))\n\n        for inv in invoices:\n            customer = inv.get(\"payer_agent_id\", \"unknown\")\n            date_str = inv.get(\"created_at\", \"\")\n            amount = float(inv.get(\"amount\", 0))\n\n            if not date_str:\n                continue\n\n            date = datetime.fromisoformat(\n                date_str.replace(\"Z\", \"+00:00\")\n            ).replace(tzinfo=None)\n\n            if cohort_period == \"monthly\":\n                period_key = date.strftime(\"%Y-%m\")\n            else:\n                # ISO week\n                period_key = date.strftime(\"%Y-W%W\")\n\n            # Track first seen\n            if customer not in customer_first_seen:\n                customer_first_seen[customer] = period_key\n\n            # Track revenue per customer per period\n            customer_periods[customer][period_key] += amount\n\n        # Build cohorts: group customers by first-seen period\n        cohorts = defaultdict(lambda: {\n            \"customers\": [],\n            \"periods\": defaultdict(lambda: {\n                \"revenue\": 0.0,\n                \"active_customers\": 0,\n            }),\n        })\n\n        for customer, first_period in customer_first_seen.items():\n            cohorts[first_period][\"customers\"].append(customer)\n\n            for period, revenue in customer_periods[customer].items():\n                cohorts[first_period][\"periods\"][period][\"revenue\"] += revenue\n                cohorts[first_period][\"periods\"][period][\n                    \"active_customers\"\n                ] += 1\n\n        # Build retention matrix\n        retention_matrix = {}\n        for cohort_key in sorted(cohorts.keys()):\n            cohort = cohorts[cohort_key]\n            initial_count = len(cohort[\"customers\"])\n            periods_sorted = sorted(cohort[\"periods\"].keys())\n\n            retention_matrix[cohort_key] = {\n                \"initial_customers\": initial_count,\n                \"retention_by_period\": [],\n            }\n\n            for i, period in enumerate(periods_sorted):\n                active = cohort[\"periods\"][period][\"active_customers\"]\n                revenue = cohort[\"periods\"][period][\"revenue\"]\n                retention_pct = (\n                    (active \u002F initial_count * 100)\n                    if initial_count > 0\n                    else 0\n                )\n                retention_matrix[cohort_key][\n                    \"retention_by_period\"\n                ].append({\n                    \"period\": period,\n                    \"period_number\": i,\n                    \"active_customers\": active,\n                    \"retention_pct\": round(retention_pct, 1),\n                    \"revenue\": round(revenue, 2),\n                    \"avg_revenue_per_customer\": round(\n                        revenue \u002F max(active, 1), 2\n                    ),\n                })\n\n        return {\n            \"cohorts\": {\n                k: {\n                    \"customer_count\": len(v[\"customers\"]),\n                    \"customers\": v[\"customers\"],\n                }\n                for k, v in cohorts.items()\n            },\n            \"retention_matrix\": retention_matrix,\n        }\n\n    def get_retention_curve(\n        self,\n        cohort_key: str,\n        retention_matrix: dict,\n    ) -> list[dict]:\n        \"\"\"Extract the retention curve for a specific cohort.\n\n        Returns a list of data points showing how retention decays\n        over time for the given cohort.\n        \"\"\"\n        cohort_data = retention_matrix.get(cohort_key, {})\n        retention = cohort_data.get(\"retention_by_period\", [])\n\n        if not retention:\n            return []\n\n        # Calculate period-over-period churn\n        curve = []\n        for i, point in enumerate(retention):\n            prev_retention = (\n                retention[i - 1][\"retention_pct\"] if i > 0 else 100.0\n            )\n            period_churn = prev_retention - point[\"retention_pct\"]\n\n            curve.append({\n                \"period_number\": point[\"period_number\"],\n                \"period\": point[\"period\"],\n                \"retention_pct\": point[\"retention_pct\"],\n                \"period_churn_pct\": round(period_churn, 1),\n                \"revenue\": point[\"revenue\"],\n                \"avg_revenue_per_customer\": point[\n                    \"avg_revenue_per_customer\"\n                ],\n                \"cumulative_revenue_per_customer\": round(\n                    sum(\n                        p[\"avg_revenue_per_customer\"]\n                        for p in retention[: i + 1]\n                    ),\n                    2,\n                ),\n            })\n\n        return curve\n```\n\n### Reading Cohort Data\n\nA healthy agent service shows these cohort patterns:\n\n**Improving retention over cohorts.** If your February cohort retains at 70% after three months and your April cohort retains at 78% after three months, your product or positioning is improving. This is the single most important trend to track.\n\n**Stabilizing retention curves.** Each cohort's retention should flatten after the initial churn period. If your retention curve never flattens -- customers continue churning at the same rate month after month -- you have a product-market fit problem. Customers are not finding enough ongoing value to justify continued use.\n\n**Growing revenue per surviving customer.** The best agent services show net revenue expansion within cohorts: the customers who stay spend more over time. This means they are integrating your service deeper into their workflows, using more features, or processing more volume. If revenue per surviving customer is flat, you are a utility. If it is growing, you are becoming infrastructure.\n\n**The danger signal.** If newer cohorts are both smaller (fewer new customers) and churn faster (lower retention), you are in a death spiral. The marketplace is moving away from you. This is the signal to either dramatically improve the product or pivot. Cohort analysis gives you this signal months before it shows up in aggregate MRR.\n\n---\n\n## Chapter 5: Churn Prediction\n\n### Leading Indicators of Agent Customer Churn\n\nBy the time a customer has churned -- their last invoice was 30+ days ago and usage has dropped to zero -- it is too late. Effective churn management requires predicting churn before it happens, ideally 7-14 days before the customer stops using your service. For agent customers, there are five reliable leading indicators, all detectable from GreenHelix billing and usage data.\n\n**Indicator 1: Usage volume decline.** A customer whose daily call volume drops by more than 40% from their trailing 30-day average is at high risk. This is the strongest predictor. Usage decline usually precedes churn by 7-21 days. The drop may be gradual (progressive disengagement) or sudden (the customer is testing an alternative).\n\n**Indicator 2: Usage pattern change.** A customer who previously called your service at consistent intervals (every hour, every day) and shifts to sporadic, unpredictable calls is exploring alternatives. They are comparing your service to competitors and only falling back to you when the alternative fails.\n\n**Indicator 3: Revenue per call decline.** If a customer shifts from high-value operations to low-value ones -- using only your cheapest endpoints while avoiding premium features -- they are extracting remaining value before leaving. This is the \"already has one foot out the door\" signal.\n\n**Indicator 4: Payment delays.** When invoices that previously cleared in 1-2 days start taking 5-7 days, the customer's operator may be deprioritizing your service in their budget allocation. Payment delays are a weak signal individually but a strong signal when combined with usage decline.\n\n**Indicator 5: Reputation changes.** If a customer's trust score drops, they may be experiencing issues with other services too, which could indicate financial distress or organizational problems that will eventually affect their relationship with you.\n\n### Building a Churn Risk Score\n\n```python\n    # -- Churn Prediction ----------------------------------------------\n\n    def calculate_churn_risk(\n        self,\n        customer_agent_id: str,\n        lookback_days: int = 60,\n    ) -> dict:\n        \"\"\"Calculate a churn risk score (0-100) for a customer agent.\n\n        Combines usage decline, pattern changes, revenue trends, and\n        payment timing into a weighted risk score.\n\n        Higher score = higher risk of churning.\n        \"\"\"\n        now = datetime.utcnow()\n        start_date = (now - timedelta(days=lookback_days)).strftime(\n            \"%Y-%m-%d\"\n        )\n        end_date = now.strftime(\"%Y-%m-%d\")\n        mid_date = (now - timedelta(days=lookback_days \u002F\u002F 2)).strftime(\n            \"%Y-%m-%d\"\n        )\n\n        # Get usage data for two halves of the lookback window\n        first_half = self.get_usage_analytics(start_date, mid_date)\n        second_half = self.get_usage_analytics(mid_date, end_date)\n\n        # Get invoice data for payment timing analysis\n        invoices = self.list_invoices()\n        customer_invoices = [\n            inv for inv in invoices.get(\"invoices\", [])\n            if inv.get(\"payer_agent_id\") == customer_agent_id\n        ]\n\n        risk_components = {}\n\n        # Component 1: Usage volume decline (0-30 points)\n        first_half_calls = int(\n            first_half.get(\"total_calls\", 0)\n        )\n        second_half_calls = int(\n            second_half.get(\"total_calls\", 0)\n        )\n\n        if first_half_calls > 0:\n            volume_change = (\n                (second_half_calls - first_half_calls) \u002F first_half_calls\n            )\n            if volume_change \u003C -0.5:\n                risk_components[\"usage_decline\"] = 30\n            elif volume_change \u003C -0.3:\n                risk_components[\"usage_decline\"] = 20\n            elif volume_change \u003C -0.1:\n                risk_components[\"usage_decline\"] = 10\n            elif volume_change > 0.1:\n                risk_components[\"usage_decline\"] = 0\n            else:\n                risk_components[\"usage_decline\"] = 5\n        else:\n            risk_components[\"usage_decline\"] = 25  # No historical data\n\n        # Component 2: Revenue per call trend (0-25 points)\n        first_half_revenue = float(\n            first_half.get(\"total_revenue\", 0)\n        )\n        second_half_revenue = float(\n            second_half.get(\"total_revenue\", 0)\n        )\n\n        first_rpc = (\n            first_half_revenue \u002F max(first_half_calls, 1)\n        )\n        second_rpc = (\n            second_half_revenue \u002F max(second_half_calls, 1)\n        )\n\n        if first_rpc > 0:\n            rpc_change = (second_rpc - first_rpc) \u002F first_rpc\n            if rpc_change \u003C -0.3:\n                risk_components[\"revenue_decline\"] = 25\n            elif rpc_change \u003C -0.15:\n                risk_components[\"revenue_decline\"] = 15\n            elif rpc_change \u003C 0:\n                risk_components[\"revenue_decline\"] = 5\n            else:\n                risk_components[\"revenue_decline\"] = 0\n        else:\n            risk_components[\"revenue_decline\"] = 10\n\n        # Component 3: Days since last invoice (0-25 points)\n        if customer_invoices:\n            customer_invoices.sort(\n                key=lambda x: x.get(\"created_at\", \"\"), reverse=True\n            )\n            last_invoice_date = datetime.fromisoformat(\n                customer_invoices[0][\"created_at\"].replace(\n                    \"Z\", \"+00:00\"\n                )\n            ).replace(tzinfo=None)\n            days_since_last = (now - last_invoice_date).days\n\n            if days_since_last > 21:\n                risk_components[\"recency\"] = 25\n            elif days_since_last > 14:\n                risk_components[\"recency\"] = 15\n            elif days_since_last > 7:\n                risk_components[\"recency\"] = 5\n            else:\n                risk_components[\"recency\"] = 0\n        else:\n            risk_components[\"recency\"] = 20\n\n        # Component 4: Payment consistency (0-20 points)\n        if len(customer_invoices) >= 3:\n            intervals = []\n            for i in range(1, min(len(customer_invoices), 6)):\n                d1 = datetime.fromisoformat(\n                    customer_invoices[i - 1][\"created_at\"].replace(\n                        \"Z\", \"+00:00\"\n                    )\n                ).replace(tzinfo=None)\n                d2 = datetime.fromisoformat(\n                    customer_invoices[i][\"created_at\"].replace(\n                        \"Z\", \"+00:00\"\n                    )\n                ).replace(tzinfo=None)\n                intervals.append(abs((d1 - d2).days))\n\n            if len(intervals) >= 2:\n                interval_cv = (\n                    statistics.stdev(intervals)\n                    \u002F max(statistics.mean(intervals), 1)\n                )\n                if interval_cv > 1.0:\n                    risk_components[\"consistency\"] = 20\n                elif interval_cv > 0.5:\n                    risk_components[\"consistency\"] = 10\n                else:\n                    risk_components[\"consistency\"] = 0\n            else:\n                risk_components[\"consistency\"] = 5\n        else:\n            risk_components[\"consistency\"] = 10\n\n        # Composite risk score\n        total_risk = sum(risk_components.values())\n        total_risk = min(total_risk, 100)\n\n        # Risk tier\n        if total_risk >= 70:\n            tier = \"critical\"\n        elif total_risk >= 45:\n            tier = \"high\"\n        elif total_risk >= 25:\n            tier = \"medium\"\n        else:\n            tier = \"low\"\n\n        return {\n            \"customer_agent_id\": customer_agent_id,\n            \"risk_score\": total_risk,\n            \"risk_tier\": tier,\n            \"components\": risk_components,\n            \"data\": {\n                \"volume_change_pct\": round(\n                    (\n                        (second_half_calls - first_half_calls)\n                        \u002F max(first_half_calls, 1)\n                    )\n                    * 100,\n                    1,\n                ),\n                \"rpc_change_pct\": round(\n                    (\n                        (second_rpc - first_rpc)\n                        \u002F max(first_rpc, 0.001)\n                    )\n                    * 100,\n                    1,\n                ),\n                \"days_since_last_invoice\": (\n                    (now - last_invoice_date).days\n                    if customer_invoices\n                    else None\n                ),\n                \"first_half_calls\": first_half_calls,\n                \"second_half_calls\": second_half_calls,\n            },\n        }\n\n    def get_at_risk_customers(\n        self,\n        customer_agent_ids: list[str],\n        risk_threshold: int = 45,\n    ) -> list[dict]:\n        \"\"\"Identify customers above a churn risk threshold.\n\n        Scans a list of customer agent IDs and returns those whose\n        churn risk score exceeds the threshold, sorted by risk\n        (highest first).\n        \"\"\"\n        at_risk = []\n\n        for customer_id in customer_agent_ids:\n            try:\n                risk = self.calculate_churn_risk(customer_id)\n                if risk[\"risk_score\"] >= risk_threshold:\n                    at_risk.append(risk)\n            except Exception as e:\n                # Log but don't fail the entire scan\n                print(\n                    f\"Warning: Could not assess risk for \"\n                    f\"{customer_id}: {e}\"\n                )\n                continue\n\n        # Sort by risk score descending\n        at_risk.sort(key=lambda x: x[\"risk_score\"], reverse=True)\n\n        return at_risk\n```\n\n### Acting on Churn Predictions\n\nA churn risk score is only useful if it triggers action. Here is the intervention playbook by risk tier:\n\n**Critical (70-100).** This customer is leaving within 1-2 weeks. Immediate actions: (a) check if your service has had any errors or latency increases for this customer, (b) if you have a dynamic pricing capability, temporarily reduce their per-call cost by 20-30% to increase the switching cost, (c) register a webhook for their usage events so you see the exact moment they stop calling.\n\n**High (45-69).** This customer is likely evaluating alternatives. Actions: (a) check competitor pricing in the marketplace using `search_services` to see if you are being undercut, (b) if the customer's volume warrants it, offer a volume discount commitment, (c) analyze which of your service endpoints they are no longer using -- if they dropped a premium feature, understand why.\n\n**Medium (25-44).** This customer shows early warning signs but may not be actively churning. Actions: (a) monitor weekly, (b) ensure your service performance is stable, (c) consider proactive outreach if you have a communication channel to the customer's operator.\n\n**Low (0-24).** Healthy customer. No intervention needed, but continue monitoring. Even low-risk customers should be included in cohort analysis to ensure the baseline does not shift.\n\nThe key insight for agent commerce is that retention interventions are programmatic. You do not send an email with a special offer. You adjust pricing parameters, improve response latency, or enhance the service quality. The webhook system lets you detect the moment a customer's behavior changes and trigger automated responses.\n\n---\n\n## Chapter 6: Pricing Optimization\n\n### The Price That Maximizes Revenue\n\nPricing is the single highest-leverage decision in any business. A 1% improvement in price realization -- getting 1% more revenue from the same volume -- typically has a larger impact on profit than a 1% improvement in cost, volume, or conversion rate. McKinsey's research consistently shows that pricing improvements flow to the bottom line at 2-4x the rate of cost improvements.\n\nFor agent services, pricing optimization is both more important and more tractable than for traditional SaaS. More important because agent customers switch on price-adjusted quality with zero friction. More tractable because you have granular, high-frequency usage data that reveals price sensitivity with statistical precision. Every tool call is a data point. A service handling 10,000 calls per day generates enough data to estimate price elasticity within a week.\n\n### Price Elasticity Estimation\n\nPrice elasticity measures how demand changes in response to price changes. If you raise your price by 10% and volume drops by 5%, your elasticity is -0.5 (inelastic -- the price increase is profitable). If you raise your price by 10% and volume drops by 15%, your elasticity is -1.5 (elastic -- the price increase loses revenue).\n\nThe optimal price depends on your elasticity. For inelastic services (elasticity between 0 and -1), you should raise prices -- volume drops less than price increases, so revenue grows. For elastic services (elasticity below -1), you should lower prices -- volume gains more than offset the price decrease.\n\n```python\n    # -- Pricing Optimization ------------------------------------------\n\n    def estimate_price_elasticity(\n        self,\n        price_history: list[dict],\n    ) -> dict:\n        \"\"\"Estimate price elasticity from historical price\u002Fvolume data.\n\n        Args:\n            price_history: List of dicts with 'price', 'volume', and\n                'period' keys representing different pricing periods.\n\n        Returns:\n            Elasticity estimate with confidence indicators.\n\n        The elasticity is computed using the midpoint (arc) method\n        across all consecutive price change periods.\n        \"\"\"\n        if len(price_history) \u003C 2:\n            return {\n                \"elasticity\": None,\n                \"error\": \"Need at least 2 price periods\",\n            }\n\n        # Sort by period\n        sorted_history = sorted(\n            price_history, key=lambda x: x[\"period\"]\n        )\n\n        # Calculate elasticity for each consecutive pair\n        elasticities = []\n        for i in range(1, len(sorted_history)):\n            p1 = float(sorted_history[i - 1][\"price\"])\n            p2 = float(sorted_history[i][\"price\"])\n            q1 = float(sorted_history[i - 1][\"volume\"])\n            q2 = float(sorted_history[i][\"volume\"])\n\n            # Skip periods with no price change\n            if p1 == p2:\n                continue\n\n            # Midpoint (arc) elasticity formula\n            pct_change_q = (q2 - q1) \u002F ((q1 + q2) \u002F 2)\n            pct_change_p = (p2 - p1) \u002F ((p1 + p2) \u002F 2)\n\n            if pct_change_p != 0:\n                elasticity = pct_change_q \u002F pct_change_p\n                elasticities.append({\n                    \"period_from\": sorted_history[i - 1][\"period\"],\n                    \"period_to\": sorted_history[i][\"period\"],\n                    \"price_change_pct\": round(pct_change_p * 100, 2),\n                    \"volume_change_pct\": round(pct_change_q * 100, 2),\n                    \"elasticity\": round(elasticity, 3),\n                })\n\n        if not elasticities:\n            return {\n                \"elasticity\": None,\n                \"error\": \"No price changes found in history\",\n            }\n\n        avg_elasticity = statistics.mean(\n            [e[\"elasticity\"] for e in elasticities]\n        )\n        elasticity_std = (\n            statistics.stdev([e[\"elasticity\"] for e in elasticities])\n            if len(elasticities) > 1\n            else 0\n        )\n\n        # Classify\n        if avg_elasticity > -0.5:\n            classification = \"highly_inelastic\"\n            recommendation = \"raise_price\"\n        elif avg_elasticity > -1.0:\n            classification = \"inelastic\"\n            recommendation = \"raise_price\"\n        elif avg_elasticity > -1.5:\n            classification = \"elastic\"\n            recommendation = \"lower_price\"\n        else:\n            classification = \"highly_elastic\"\n            recommendation = \"lower_price_significantly\"\n\n        return {\n            \"avg_elasticity\": round(avg_elasticity, 3),\n            \"elasticity_std\": round(elasticity_std, 3),\n            \"classification\": classification,\n            \"recommendation\": recommendation,\n            \"data_points\": len(elasticities),\n            \"period_elasticities\": elasticities,\n        }\n\n    def optimize_pricing(\n        self,\n        current_price: float,\n        current_volume: float,\n        elasticity: float,\n        cost_per_call: float,\n        min_price: Optional[float] = None,\n        max_price: Optional[float] = None,\n    ) -> dict:\n        \"\"\"Find the revenue-maximizing and profit-maximizing prices.\n\n        Uses the estimated elasticity to model the demand curve and\n        find the prices that maximize total revenue and total profit.\n\n        Revenue = Price * Volume\n        Profit = (Price - Cost) * Volume\n        Volume at new price = current_volume * (new_price \u002F current_price) ^ elasticity\n\n        Args:\n            current_price: Current per-call price.\n            current_volume: Current monthly call volume.\n            elasticity: Estimated price elasticity (negative number).\n            cost_per_call: Your cost per call (from FinOps data).\n            min_price: Minimum price floor.\n            max_price: Maximum price ceiling.\n        \"\"\"\n        if min_price is None:\n            min_price = cost_per_call * 1.1  # At least 10% margin\n        if max_price is None:\n            max_price = current_price * 3.0  # Cap at 3x current\n\n        best_revenue_price = current_price\n        best_revenue = current_price * current_volume\n        best_profit_price = current_price\n        best_profit = (current_price - cost_per_call) * current_volume\n\n        # Search the price space in 1% increments\n        test_prices = []\n        price = min_price\n        step = (max_price - min_price) \u002F 200\n        if step \u003C= 0:\n            step = min_price * 0.01\n\n        while price \u003C= max_price:\n            # Demand model: constant elasticity\n            volume_at_price = current_volume * (\n                (price \u002F current_price) ** elasticity\n            )\n            revenue = price * volume_at_price\n            profit = (price - cost_per_call) * volume_at_price\n\n            test_prices.append({\n                \"price\": round(price, 6),\n                \"volume\": round(volume_at_price, 0),\n                \"revenue\": round(revenue, 2),\n                \"profit\": round(profit, 2),\n                \"margin_pct\": round(\n                    ((price - cost_per_call) \u002F price) * 100, 1\n                ),\n            })\n\n            if revenue > best_revenue:\n                best_revenue = revenue\n                best_revenue_price = price\n\n            if profit > best_profit:\n                best_profit = profit\n                best_profit_price = price\n\n            price += step\n\n        # Calculate improvements\n        current_revenue = current_price * current_volume\n        current_profit = (\n            (current_price - cost_per_call) * current_volume\n        )\n\n        return {\n            \"current\": {\n                \"price\": round(current_price, 6),\n                \"volume\": round(current_volume, 0),\n                \"revenue\": round(current_revenue, 2),\n                \"profit\": round(current_profit, 2),\n            },\n            \"revenue_optimal\": {\n                \"price\": round(best_revenue_price, 6),\n                \"volume\": round(\n                    current_volume\n                    * (\n                        (best_revenue_price \u002F current_price)\n                        ** elasticity\n                    ),\n                    0,\n                ),\n                \"revenue\": round(best_revenue, 2),\n                \"revenue_change_pct\": round(\n                    (\n                        (best_revenue - current_revenue)\n                        \u002F max(current_revenue, 0.01)\n                    )\n                    * 100,\n                    1,\n                ),\n            },\n            \"profit_optimal\": {\n                \"price\": round(best_profit_price, 6),\n                \"volume\": round(\n                    current_volume\n                    * (\n                        (best_profit_price \u002F current_price)\n                        ** elasticity\n                    ),\n                    0,\n                ),\n                \"profit\": round(best_profit, 2),\n                \"profit_change_pct\": round(\n                    (\n                        (best_profit - current_profit)\n                        \u002F max(current_profit, 0.01)\n                    )\n                    * 100,\n                    1,\n                ),\n            },\n            \"elasticity_used\": elasticity,\n            \"cost_per_call\": cost_per_call,\n        }\n```\n\n### Volume Discount Optimization\n\nVolume discounts are the most common pricing lever in agent commerce. Offer a lower per-call price in exchange for a commitment to higher volume. The question is: how much discount should you offer at each volume tier?\n\nThe answer depends on your marginal cost curve and your elasticity. A discount is profitable if the incremental volume it generates exceeds the revenue you lose on existing volume. Here is the analysis.\n\n```python\n    def optimize_volume_discounts(\n        self,\n        base_price: float,\n        cost_per_call: float,\n        current_tiers: list[dict],\n        elasticity: float,\n    ) -> list[dict]:\n        \"\"\"Optimize volume discount tiers.\n\n        Args:\n            base_price: Standard per-call price.\n            cost_per_call: Your cost per call.\n            current_tiers: List of dicts with 'min_volume', 'max_volume',\n                'discount_pct', and 'current_customers' keys.\n            elasticity: Estimated price elasticity.\n\n        Returns:\n            Optimized tier recommendations.\n        \"\"\"\n        optimized_tiers = []\n\n        for tier in current_tiers:\n            min_vol = tier[\"min_volume\"]\n            max_vol = tier.get(\"max_volume\", min_vol * 10)\n            current_discount = tier[\"discount_pct\"]\n            customers = tier.get(\"current_customers\", 0)\n\n            # Mid-volume for calculations\n            mid_vol = (min_vol + max_vol) \u002F 2\n\n            # Test discount levels from 0% to 50%\n            best_discount = current_discount\n            best_tier_profit = 0\n\n            for test_discount in range(0, 51):\n                discounted_price = base_price * (1 - test_discount \u002F 100)\n                if discounted_price \u003C= cost_per_call:\n                    continue\n\n                # Expected customers at this discount\n                price_ratio = discounted_price \u002F base_price\n                volume_multiplier = price_ratio ** elasticity\n                expected_customers = max(\n                    customers * volume_multiplier, 0\n                )\n\n                tier_revenue = (\n                    discounted_price * mid_vol * expected_customers\n                )\n                tier_cost = cost_per_call * mid_vol * expected_customers\n                tier_profit = tier_revenue - tier_cost\n\n                if tier_profit > best_tier_profit:\n                    best_tier_profit = tier_profit\n                    best_discount = test_discount\n\n            optimized_tiers.append({\n                \"min_volume\": min_vol,\n                \"max_volume\": max_vol,\n                \"current_discount_pct\": current_discount,\n                \"optimal_discount_pct\": best_discount,\n                \"change\": best_discount - current_discount,\n                \"discounted_price\": round(\n                    base_price * (1 - best_discount \u002F 100), 6\n                ),\n                \"expected_profit_improvement_pct\": round(\n                    (\n                        (best_tier_profit - (\n                            (base_price * (1 - current_discount \u002F 100)\n                             - cost_per_call)\n                            * mid_vol * customers\n                        ))\n                        \u002F max(\n                            (base_price * (1 - current_discount \u002F 100)\n                             - cost_per_call)\n                            * mid_vol * max(customers, 1),\n                            0.01,\n                        )\n                    )\n                    * 100,\n                    1,\n                ),\n            })\n\n        return optimized_tiers\n```\n\n### A\u002FB Testing Prices\n\nThe most reliable way to measure price elasticity is to run a controlled experiment. In agent commerce, you can A\u002FB test prices by creating two marketplace listings for the same service at different price points and measuring conversion and retention for each.\n\nThe key constraint is sample size. You need enough transactions at each price point to reach statistical significance. For a service handling 1,000 calls per day, allocating a 10% sample to a test price (100 calls\u002Fday) gives you statistical significance within 5-7 days for a 10% price change. For a service handling 100 calls per day, you need 2-3 weeks.\n\nThe implementation pattern is straightforward: create two service listings via the marketplace, route traffic between them based on a deterministic hash of the customer agent ID (so the same customer always sees the same price), and compare the revenue and retention outcomes after the test period. Use the `search_services` tool to verify both listings are live and the `get_service_ratings` tool to monitor satisfaction at each price point.\n\n---\n\n## Chapter 7: Competitive Intelligence\n\n### Why Competitive Monitoring Is Revenue Analytics\n\nRevenue does not exist in a vacuum. Your revenue growth or decline is always relative to competitors. A 5% monthly revenue decline might be catastrophic if the market is growing at 10% (you are losing share) or acceptable if the entire market declined 15% (you are outperforming). Competitive intelligence is the external context that makes your internal revenue metrics meaningful.\n\nThe GreenHelix marketplace provides two vectors for competitive intelligence:\n\n1. **Marketplace search**: The `search_services` tool returns competitors' service listings with pricing, descriptions, and categories. Monitor this weekly to detect new entrants, price changes, and feature additions.\n2. **Identity and reputation data**: The `get_agent_leaderboard` and `search_agents_by_metrics` tools show how you rank relative to competitors on volume, ratings, and trust. The `get_agent_reputation` tool provides detailed trust data for specific competitors.\n\n### Building a Competitive Landscape\n\n```python\n    # -- Competitive Intelligence --------------------------------------\n\n    def get_competitive_landscape(\n        self,\n        service_category: str,\n        your_service_id: str,\n    ) -> dict:\n        \"\"\"Build a competitive landscape analysis for your service category.\n\n        Searches the marketplace for competing services, compares\n        pricing, ratings, and positioning.\n        \"\"\"\n        # Find competitors\n        search_results = self.search_services(\n            query=service_category,\n            category=service_category,\n        )\n\n        competitors = []\n        your_service = None\n\n        for service in search_results.get(\"services\", []):\n            service_data = {\n                \"service_id\": service.get(\"id\"),\n                \"name\": service.get(\"name\"),\n                \"price\": float(service.get(\"price\", 0)),\n                \"rating\": float(service.get(\"rating\", 0)),\n                \"review_count\": int(\n                    service.get(\"review_count\", 0)\n                ),\n                \"description\": service.get(\"description\", \"\"),\n            }\n\n            if service.get(\"id\") == your_service_id:\n                your_service = service_data\n            else:\n                competitors.append(service_data)\n\n        if not your_service:\n            your_service = {\n                \"service_id\": your_service_id,\n                \"price\": 0,\n                \"rating\": 0,\n            }\n\n        # Analyze competitive position\n        if competitors:\n            prices = [c[\"price\"] for c in competitors if c[\"price\"] > 0]\n            ratings = [\n                c[\"rating\"] for c in competitors if c[\"rating\"] > 0\n            ]\n\n            avg_competitor_price = (\n                statistics.mean(prices) if prices else 0\n            )\n            min_competitor_price = min(prices) if prices else 0\n            max_competitor_price = max(prices) if prices else 0\n            avg_competitor_rating = (\n                statistics.mean(ratings) if ratings else 0\n            )\n\n            your_price = your_service.get(\"price\", 0)\n            price_position = \"unknown\"\n            if your_price > 0 and avg_competitor_price > 0:\n                price_ratio = your_price \u002F avg_competitor_price\n                if price_ratio > 1.15:\n                    price_position = \"premium\"\n                elif price_ratio \u003C 0.85:\n                    price_position = \"budget\"\n                else:\n                    price_position = \"mid_market\"\n        else:\n            avg_competitor_price = 0\n            min_competitor_price = 0\n            max_competitor_price = 0\n            avg_competitor_rating = 0\n            price_position = \"no_competitors\"\n\n        return {\n            \"your_service\": your_service,\n            \"competitor_count\": len(competitors),\n            \"competitors\": sorted(\n                competitors, key=lambda c: c[\"price\"]\n            ),\n            \"market_pricing\": {\n                \"avg_price\": round(avg_competitor_price, 6),\n                \"min_price\": round(min_competitor_price, 6),\n                \"max_price\": round(max_competitor_price, 6),\n                \"your_price\": your_service.get(\"price\", 0),\n                \"your_position\": price_position,\n            },\n            \"market_quality\": {\n                \"avg_rating\": round(avg_competitor_rating, 2),\n                \"your_rating\": your_service.get(\"rating\", 0),\n            },\n        }\n\n    def benchmark_performance(\n        self,\n        metric: str = \"revenue\",\n    ) -> dict:\n        \"\"\"Benchmark your agent against the leaderboard.\n\n        Uses the identity leaderboard and reputation data to compare\n        your performance against the market.\n        \"\"\"\n        # Get leaderboard\n        leaderboard = self.get_agent_leaderboard(metric=metric)\n        agents = leaderboard.get(\"agents\", [])\n\n        # Find your position\n        your_position = None\n        total_agents = len(agents)\n\n        for i, agent in enumerate(agents):\n            if agent.get(\"agent_id\") == self.agent_id:\n                your_position = i + 1\n                break\n\n        # Get your reputation\n        reputation = self.get_agent_reputation(self.agent_id)\n\n        # Calculate percentile\n        percentile = None\n        if your_position and total_agents > 0:\n            percentile = round(\n                (1 - your_position \u002F total_agents) * 100, 1\n            )\n\n        # Get top performer data for comparison\n        top_performers = agents[:5] if len(agents) >= 5 else agents\n\n        return {\n            \"your_agent_id\": self.agent_id,\n            \"metric\": metric,\n            \"your_rank\": your_position,\n            \"total_agents\": total_agents,\n            \"percentile\": percentile,\n            \"reputation\": reputation,\n            \"top_performers\": top_performers,\n            \"gap_to_top\": {\n                \"rank_1_value\": (\n                    float(top_performers[0].get(\"value\", 0))\n                    if top_performers\n                    else 0\n                ),\n                \"your_value\": (\n                    float(agents[your_position - 1].get(\"value\", 0))\n                    if your_position and your_position \u003C= len(agents)\n                    else 0\n                ),\n            },\n        }\n```\n\n### Competitive Intelligence Patterns\n\nThree patterns emerge from consistent competitive monitoring.\n\n**Pattern 1: Price convergence.** In active marketplace categories, prices converge over time as competitors respond to each other. If you are the first to enter a category at $0.010 per call and a competitor enters at $0.008, you will face pressure to lower your price. Track the rate of price convergence -- if competitor prices are moving toward yours, you have pricing power. If your price is moving toward competitors', they have it.\n\n**Pattern 2: Quality-price segmentation.** Markets naturally segment into quality tiers. A high-quality, high-reliability service at $0.015 per call can coexist with a budget alternative at $0.005 because they serve different customer segments. The danger zone is the middle: similar quality to the premium option at a price close to the budget option. Your competitive analysis should identify which tier you occupy and whether that position is defensible.\n\n**Pattern 3: Reputation moats.** Agent services with high trust scores and long track records retain customers better than new entrants with lower prices. The `get_agent_reputation` data quantifies this moat. If your trust score is 0.92 and the lowest-price competitor is at 0.71, many agent customers will pay the premium because their orchestrators weight trust in routing decisions. Monitor your reputation advantage and invest in maintaining it -- it is the closest thing to a switching cost in agent commerce.\n\nTrack competitive data weekly. Store historical snapshots so you can see trends, not just the current state. The combination of competitive pricing trends and your own cohort retention data tells you whether you are gaining or losing market position.\n\n---\n\n## Chapter 8: Revenue Dashboard and Alerts\n\n### From Analysis to Monitoring\n\nThe previous seven chapters built the analytics: attribution, LTV, cohorts, churn prediction, pricing optimization, and competitive intelligence. This chapter turns those analytics into a live monitoring system using GreenHelix webhooks. The goal is a revenue dashboard that alerts you to problems before they become crises.\n\n### Webhook-Based Revenue Event Tracking\n\nGreenHelix webhooks deliver real-time notifications when billing events occur. Register handlers for the events that matter most to revenue monitoring.\n\n```python\n    # -- Revenue Dashboard and Alerts ----------------------------------\n\n    def setup_revenue_alerts(\n        self,\n        webhook_url: str,\n        config: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Register webhooks for revenue-critical events.\n\n        Sets up monitoring for payment completions, payment failures,\n        usage thresholds, and budget events that signal revenue changes.\n\n        Args:\n            webhook_url: Your endpoint that receives webhook POSTs.\n            config: Optional configuration overrides.\n        \"\"\"\n        alert_config = config or {}\n\n        # Event categories to monitor\n        revenue_events = [\n            # Payment events: track incoming revenue\n            \"payment.completed\",\n            \"payment.failed\",\n            \"payment.refunded\",\n\n            # Usage events: track consumption patterns\n            \"usage.threshold\",\n            \"usage.spike\",\n\n            # Budget events: customer spending signals\n            \"budget.threshold\",\n            \"budget.exhausted\",\n\n            # Subscription events: recurring revenue changes\n            \"subscription.created\",\n            \"subscription.cancelled\",\n            \"subscription.renewed\",\n        ]\n\n        results = {}\n\n        for event in revenue_events:\n            try:\n                result = self.register_webhook(\n                    url=webhook_url,\n                    events=[event],\n                    config=alert_config.get(event, {}),\n                )\n                results[event] = {\n                    \"status\": \"registered\",\n                    \"webhook_id\": result.get(\"webhook_id\"),\n                }\n            except Exception as e:\n                results[event] = {\n                    \"status\": \"failed\",\n                    \"error\": str(e),\n                }\n\n        return {\n            \"webhook_url\": webhook_url,\n            \"events_registered\": sum(\n                1\n                for r in results.values()\n                if r[\"status\"] == \"registered\"\n            ),\n            \"events_failed\": sum(\n                1\n                for r in results.values()\n                if r[\"status\"] == \"failed\"\n            ),\n            \"details\": results,\n        }\n```\n\n### Key Metrics to Monitor\n\nA revenue dashboard for agent services should track these metrics, updated in real time from webhook events and polled analytics.\n\n**Monthly Recurring Revenue (MRR).** For usage-based agent services, MRR is not a clean number like it is for subscription SaaS. Calculate it as the trailing 30-day revenue, updated daily. Track the MRR trend line, not the absolute number, because daily fluctuations in usage-based revenue are normal.\n\n**Average Revenue Per User (ARPU).** Total monthly revenue divided by the number of unique customer agents who made at least one call. ARPU tells you whether you are growing by adding customers (ARPU flat, MRR growing) or by extracting more from existing customers (ARPU growing, customer count flat). The first pattern is healthier for long-term growth; the second is more profitable in the short term but fragile.\n\n**Churn Rate.** The percentage of customers from 30 days ago who have not made a call in the last 7 days. This is a lagging indicator -- by the time churn shows up here, the customer has already left. That is why Chapter 5 builds a leading indicator (the churn risk score). The dashboard should show both: the lagging churn rate for historical accuracy and the churn risk distribution for forward-looking management.\n\n**LTV\u002FCAC Ratio.** The ratio of customer lifetime value (from Chapter 3) to customer acquisition cost. If your LTV is $300 and your CAC is $50, the ratio is 6:1 -- a healthy, profitable business. Below 3:1, your acquisition economics are unsustainable. Below 1:1, you are paying more to acquire customers than they will ever generate in revenue. For agent services, CAC is often low (marketplace discovery is nearly free), which means even moderate LTV produces excellent ratios. But if you are investing in integrations, partnerships, or marketing to drive direct and referral channels, track the channel-specific CAC and LTV\u002FCAC ratio.\n\n### Bringing It All Together\n\nHere is the complete dashboard generation method that combines every metric from this guide into a single revenue report.\n\n```python\n    def generate_revenue_report(\n        self,\n        customer_agent_ids: list[str],\n        service_category: str,\n        your_service_id: str,\n        lookback_days: int = 30,\n    ) -> dict:\n        \"\"\"Generate a comprehensive revenue analytics report.\n\n        Combines attribution, LTV, cohort, churn, and competitive\n        data into a single dashboard payload.\n        \"\"\"\n        now = datetime.utcnow()\n        start_date = (now - timedelta(days=lookback_days)).strftime(\n            \"%Y-%m-%d\"\n        )\n        end_date = now.strftime(\"%Y-%m-%d\")\n\n        # 1. Revenue attribution\n        revenue = self.get_revenue_summary(start_date, end_date)\n\n        # 2. Customer LTV\n        histories = []\n        for cid in customer_agent_ids:\n            try:\n                history = self.get_customer_history(cid)\n                histories.append(history)\n            except Exception:\n                continue\n\n        ltv_data = self.calculate_ltv(histories)\n\n        # 3. Cohort analysis\n        invoices_raw = self.list_invoices(limit=1000)\n        cohort_data = self.build_cohorts(\n            invoices=invoices_raw.get(\"invoices\", [])\n        )\n\n        # 4. Churn risk assessment\n        at_risk = self.get_at_risk_customers(\n            customer_agent_ids, risk_threshold=45\n        )\n\n        # 5. Competitive landscape\n        competitive = self.get_competitive_landscape(\n            service_category, your_service_id\n        )\n\n        # 6. Benchmark\n        benchmark = self.benchmark_performance(metric=\"revenue\")\n\n        # Compute summary KPIs\n        total_revenue = revenue.get(\"total_revenue\", 0)\n        customer_count = len(\n            [h for h in histories if h.get(\"total_revenue\", 0) > 0]\n        )\n        arpu = (\n            round(total_revenue \u002F max(customer_count, 1), 2)\n        )\n        at_risk_pct = round(\n            len(at_risk) \u002F max(len(customer_agent_ids), 1) * 100, 1\n        )\n\n        return {\n            \"report_date\": end_date,\n            \"period\": {\n                \"start\": start_date,\n                \"end\": end_date,\n                \"days\": lookback_days,\n            },\n            \"kpis\": {\n                \"mrr\": total_revenue,\n                \"arpu\": arpu,\n                \"customer_count\": customer_count,\n                \"ltv\": ltv_data[\"ltv\"],\n                \"churn_rate\": ltv_data[\"churn_rate\"],\n                \"ltv_cac_ratio\": None,  # CAC is operator-specific\n                \"at_risk_customers\": len(at_risk),\n                \"at_risk_pct\": at_risk_pct,\n                \"competitive_rank\": benchmark.get(\"your_rank\"),\n                \"competitive_percentile\": benchmark.get(\"percentile\"),\n            },\n            \"revenue_attribution\": revenue,\n            \"ltv_analysis\": ltv_data,\n            \"cohort_summary\": {\n                \"total_cohorts\": len(\n                    cohort_data.get(\"cohorts\", {})\n                ),\n                \"retention_matrix\": cohort_data.get(\n                    \"retention_matrix\", {}\n                ),\n            },\n            \"churn_risk\": {\n                \"at_risk_count\": len(at_risk),\n                \"critical_count\": sum(\n                    1\n                    for r in at_risk\n                    if r[\"risk_tier\"] == \"critical\"\n                ),\n                \"high_count\": sum(\n                    1\n                    for r in at_risk\n                    if r[\"risk_tier\"] == \"high\"\n                ),\n                \"at_risk_customers\": at_risk[:10],  # Top 10 riskiest\n            },\n            \"competitive_position\": {\n                \"market_position\": competitive[\"market_pricing\"][\n                    \"your_position\"\n                ],\n                \"competitor_count\": competitive[\"competitor_count\"],\n                \"leaderboard_rank\": benchmark.get(\"your_rank\"),\n                \"leaderboard_percentile\": benchmark.get(\"percentile\"),\n            },\n        }\n```\n\n### Cross-References\n\nThis guide is the revenue measurement layer. It connects to three other guides in the GreenHelix ecosystem:\n\n- **The AI Agent FinOps Playbook (Product #6)** covers the cost side: per-agent wallets, budget caps, spend alerts, and cost attribution. Use FinOps data as an input to margin calculations in this guide. Your revenue per call minus your cost per call (from FinOps) is your margin per call.\n- **The Agent Testing and Observability Cookbook (Product #9)** covers monitoring infrastructure: tracing, health checks, and alerting pipelines. The revenue webhook handlers from this chapter integrate with the observability patterns from that guide. Route revenue alerts through the same alerting infrastructure as your operational alerts.\n- **Agent Negotiation Strategies (Product #14)** covers pricing tactics: auctions, BATNA calculation, and dynamic pricing. The pricing optimization in Chapter 6 of this guide produces the elasticity estimates and optimal price points that feed into the negotiation strategies. Use this guide to find the right price; use the Negotiation guide to implement the right pricing mechanism.\n\n### Where to Start\n\nIf you are reading this guide and your agent service is already live, here is the priority order:\n\n1. **Revenue attribution** (Chapter 2). Takes 30 minutes to implement. Immediately tells you which services and channels drive your revenue.\n2. **Churn risk scoring** (Chapter 5). Takes one hour. Identifies customers you are about to lose so you can intervene.\n3. **LTV calculation** (Chapter 3). Takes 30 minutes once you have customer histories. Tells you how much each customer is worth and how much you should spend on retention.\n4. **Cohort analysis** (Chapter 4). Takes one hour. Shows whether your business is improving or deteriorating over time.\n5. **Competitive intelligence** (Chapter 7). Takes 30 minutes to set up initial monitoring. Gives external context to your internal metrics.\n6. **Pricing optimization** (Chapter 6). Requires 2-4 weeks of data collection before you can estimate elasticity. Start the data collection now; optimize later.\n7. **Revenue dashboard** (Chapter 8). Once you have all the above, wire them together with webhooks and a reporting function.\n\nThe total implementation time is approximately 8-12 hours for a developer familiar with the GreenHelix API. The revenue insights start generating value immediately.\n\nFor the full API reference and tool catalog covering all billing, payments, marketplace, identity, trust, and webhook tools used in this guide, visit the GreenHelix developer documentation at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n---\n\n## GreenHelix Revenue Pipeline — Working Implementation\n\nThe code below uses the actual `greenhelix_trading` library classes. Every method call maps to a real GreenHelix Gateway tool. Copy this module into your project, set `GREENHELIX_API_KEY` and `GREENHELIX_AGENT_ID` in your environment, and run it.\n\n```python\n\"\"\"\nRevenue pipeline using the greenhelix_trading library.\n\nCovers:\n  1. Revenue tracking and service-level attribution\n  2. Cohort analysis with retention curves\n  3. Customer LTV calculation with segmentation\n  4. Multi-touch attribution modeling\n  5. Churn-aware revenue forecasting\n\nRequirements:\n    pip install greenhelix-trading\n\"\"\"\n\nimport os\nimport time\nimport statistics\nfrom datetime import datetime, timedelta\nfrom collections import defaultdict\nfrom typing import Optional\n\nfrom greenhelix_trading import RevenueTracker, CustomerAnalytics\n\n\n# ── Configuration ─────────────────────────────────────────────────────────────\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\nAGENT_ID = os.environ[\"GREENHELIX_AGENT_ID\"]\n\n\n# ── 1. Revenue Tracking Queries ──────────────────────────────────────────────\n\ndef build_revenue_dashboard(period: str = \"30d\") -> dict:\n    \"\"\"Pull billing, usage, and per-service revenue into a single view.\n\n    Uses RevenueTracker.get_revenue_summary for the billing aggregate,\n    RevenueTracker.get_revenue_by_service for category breakdown, and\n    RevenueTracker.get_usage_metrics for call-volume context.\n    \"\"\"\n    tracker = RevenueTracker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    # Billing aggregate for the period\n    billing = tracker.get_revenue_summary(period=period)\n\n    # Per-service breakdown via spending-by-category\n    services = tracker.get_revenue_by_service()\n\n    # Call-volume and usage metrics\n    usage = tracker.get_usage_metrics(period=period)\n\n    # Compute derived KPIs\n    total_revenue = float(billing.get(\"total_revenue\", 0))\n    total_calls = int(usage.get(\"total_calls\", 0))\n    revenue_per_call = total_revenue \u002F max(total_calls, 1)\n\n    categories = services.get(\"categories\", [])\n    top_service = max(\n        categories,\n        key=lambda c: float(c.get(\"total_spent\", 0)),\n        default=None,\n    )\n\n    return {\n        \"period\": period,\n        \"total_revenue\": round(total_revenue, 2),\n        \"total_calls\": total_calls,\n        \"revenue_per_call\": round(revenue_per_call, 6),\n        \"service_count\": len(categories),\n        \"top_service\": top_service,\n        \"billing_raw\": billing,\n        \"usage_raw\": usage,\n    }\n\n\ndef get_transaction_ledger(customer_id: Optional[str] = None) -> list:\n    \"\"\"Retrieve the full invoice ledger, optionally filtered by customer.\n\n    Uses RevenueTracker.get_transaction_history which wraps list_invoices.\n    Returns a list of invoice dicts sorted newest-first.\n    \"\"\"\n    tracker = RevenueTracker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n    raw = tracker.get_transaction_history(customer_id=customer_id)\n    invoices = raw.get(\"invoices\", [])\n    invoices.sort(key=lambda inv: inv.get(\"created_at\", \"\"), reverse=True)\n    return invoices\n\n\n# ── 2. Cohort Analysis ───────────────────────────────────────────────────────\n\ndef build_monthly_cohorts() -> dict:\n    \"\"\"Group customers by first-purchase month and compute retention.\n\n    Pulls all invoices via RevenueTracker.get_transaction_history,\n    assigns each customer to their first-purchase month, and tracks\n    how many remain active (have invoices) in subsequent months.\n    \"\"\"\n    tracker = RevenueTracker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n    analytics = CustomerAnalytics(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    # Fetch the full invoice ledger\n    raw = tracker.get_transaction_history()\n    invoices = raw.get(\"invoices\", [])\n\n    if not invoices:\n        return {\"cohorts\": {}, \"retention_matrix\": {}}\n\n    # Determine each customer's first-purchase month\n    customer_first_month = {}\n    customer_months = defaultdict(set)\n\n    for inv in invoices:\n        customer = inv.get(\"payer_agent_id\", \"unknown\")\n        date_str = inv.get(\"created_at\", \"\")\n        if not date_str:\n            continue\n        month_key = date_str[:7]  # \"YYYY-MM\"\n        if customer not in customer_first_month:\n            customer_first_month[customer] = month_key\n        customer_months[customer].add(month_key)\n\n    # Group customers into cohorts by first-purchase month\n    cohorts = defaultdict(list)\n    for customer, first_month in customer_first_month.items():\n        cohorts[first_month].append(customer)\n\n    # Build retention matrix\n    all_months = sorted({m for months in customer_months.values() for m in months})\n    retention_matrix = {}\n\n    for cohort_month in sorted(cohorts.keys()):\n        cohort_customers = cohorts[cohort_month]\n        initial_size = len(cohort_customers)\n        retention_matrix[cohort_month] = {\n            \"initial_customers\": initial_size,\n            \"periods\": [],\n        }\n        for i, month in enumerate(all_months):\n            if month \u003C cohort_month:\n                continue\n            active = sum(\n                1 for c in cohort_customers if month in customer_months[c]\n            )\n            retention_pct = (active \u002F initial_size * 100) if initial_size > 0 else 0\n            retention_matrix[cohort_month][\"periods\"].append({\n                \"month\": month,\n                \"period_number\": i - all_months.index(cohort_month),\n                \"active_customers\": active,\n                \"retention_pct\": round(retention_pct, 1),\n            })\n\n    # Also get the gateway-side cohort summary for cross-reference\n    gateway_cohort = analytics.build_cohort_summary(period=\"monthly\")\n\n    return {\n        \"cohorts\": {k: len(v) for k, v in cohorts.items()},\n        \"retention_matrix\": retention_matrix,\n        \"gateway_cohort_summary\": gateway_cohort,\n    }\n\n\n# ── 3. Customer LTV Calculation ──────────────────────────────────────────────\n\ndef calculate_customer_ltv(\n    customer_ids: list[str],\n    churn_override: Optional[float] = None,\n) -> dict:\n    \"\"\"Compute LTV for a set of customers using invoice history.\n\n    For each customer, uses CustomerAnalytics.get_customer_history to\n    pull their invoices, then calculates average monthly revenue. Churn\n    rate is estimated from the proportion of customers whose last invoice\n    is more than 30 days old, or can be provided as an override.\n\n    CustomerAnalytics.calculate_ltv returns the simple LTV = ARPU \u002F churn.\n    \"\"\"\n    analytics = CustomerAnalytics(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    histories = []\n    now = datetime.utcnow()\n    active_count = 0\n    churned_count = 0\n\n    for cid in customer_ids:\n        try:\n            history = analytics.get_customer_history(customer_id=cid)\n            invoices = history.get(\"invoices\", [])\n            if not invoices:\n                churned_count += 1\n                continue\n\n            # Sort invoices by date\n            invoices.sort(key=lambda x: x.get(\"created_at\", \"\"))\n            total_revenue = sum(float(inv.get(\"amount\", 0)) for inv in invoices)\n            first_date = invoices[0].get(\"created_at\", \"\")[:10]\n            last_date = invoices[-1].get(\"created_at\", \"\")[:10]\n\n            # Estimate tenure in months\n            try:\n                first_dt = datetime.fromisoformat(first_date)\n                last_dt = datetime.fromisoformat(last_date)\n                tenure_days = max((last_dt - first_dt).days, 1)\n                tenure_months = max(tenure_days \u002F 30.44, 1)\n                days_since_last = (now - last_dt).days\n            except (ValueError, TypeError):\n                tenure_months = 1\n                days_since_last = 0\n\n            avg_monthly = total_revenue \u002F tenure_months\n\n            if days_since_last > 30:\n                churned_count += 1\n            else:\n                active_count += 1\n\n            histories.append({\n                \"customer_id\": cid,\n                \"total_revenue\": round(total_revenue, 2),\n                \"tenure_months\": round(tenure_months, 1),\n                \"avg_monthly_revenue\": round(avg_monthly, 2),\n                \"days_since_last_invoice\": days_since_last,\n            })\n        except Exception:\n            churned_count += 1\n            continue\n\n    # Estimate churn rate\n    total_customers = active_count + churned_count\n    if churn_override is not None:\n        churn_rate = churn_override\n    elif total_customers > 0:\n        churn_rate = churned_count \u002F total_customers\n    else:\n        churn_rate = 0.10  # Default 10% monthly churn\n\n    churn_rate = max(churn_rate, 0.01)  # Floor at 1%\n\n    # Calculate aggregate LTV via the library\n    monthly_revenues = [h[\"avg_monthly_revenue\"] for h in histories if h[\"avg_monthly_revenue\"] > 0]\n    avg_arpu = statistics.mean(monthly_revenues) if monthly_revenues else 0\n\n    ltv_result = analytics.calculate_ltv(\n        avg_revenue_per_month=avg_arpu,\n        monthly_churn_rate=churn_rate,\n    )\n\n    # Segment customers into LTV tiers\n    individual_ltvs = [h[\"avg_monthly_revenue\"] \u002F churn_rate for h in histories if h[\"avg_monthly_revenue\"] > 0]\n    segments = {\"platinum\": [], \"gold\": [], \"silver\": [], \"bronze\": []}\n\n    for i, ltv_val in enumerate(individual_ltvs):\n        cid = histories[i][\"customer_id\"]\n        if ltv_val >= avg_arpu \u002F churn_rate * 2:\n            segments[\"platinum\"].append(cid)\n        elif ltv_val >= avg_arpu \u002F churn_rate:\n            segments[\"gold\"].append(cid)\n        elif ltv_val >= avg_arpu \u002F churn_rate * 0.5:\n            segments[\"silver\"].append(cid)\n        else:\n            segments[\"bronze\"].append(cid)\n\n    return {\n        \"ltv\": ltv_result,\n        \"churn_rate\": round(churn_rate, 4),\n        \"active_customers\": active_count,\n        \"churned_customers\": churned_count,\n        \"avg_monthly_revenue\": round(avg_arpu, 2),\n        \"expected_lifetime_months\": round(1 \u002F churn_rate, 1),\n        \"segments\": {tier: len(ids) for tier, ids in segments.items()},\n        \"segment_details\": segments,\n        \"customer_histories\": histories,\n    }\n\n\n# ── 4. Multi-Touch Attribution Modeling ──────────────────────────────────────\n\ndef build_attribution_model() -> dict:\n    \"\"\"Attribute revenue to acquisition channels using invoice metadata.\n\n    Uses RevenueTracker.get_transaction_history to pull all invoices,\n    then classifies each into marketplace \u002F direct \u002F referral based on\n    the invoice's metadata.source field.  Computes channel-level ARPU\n    and revenue share.\n    \"\"\"\n    tracker = RevenueTracker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    raw = tracker.get_transaction_history()\n    invoices = raw.get(\"invoices\", [])\n\n    channel_revenue = defaultdict(float)\n    channel_customers = defaultdict(set)\n    channel_count = defaultdict(int)\n\n    for inv in invoices:\n        amount = float(inv.get(\"amount\", 0))\n        customer = inv.get(\"payer_agent_id\", \"unknown\")\n        source = inv.get(\"metadata\", {}).get(\"source\", \"direct\")\n\n        # Channel classification\n        if \"marketplace\" in source.lower():\n            channel = \"marketplace\"\n        elif \"referral\" in source.lower() or inv.get(\"metadata\", {}).get(\"referrer\"):\n            channel = \"referral\"\n        else:\n            channel = \"direct\"\n\n        channel_revenue[channel] += amount\n        channel_customers[channel].add(customer)\n        channel_count[channel] += 1\n\n    total_revenue = sum(channel_revenue.values())\n\n    attribution = {}\n    for channel in [\"marketplace\", \"direct\", \"referral\"]:\n        rev = channel_revenue.get(channel, 0)\n        custs = len(channel_customers.get(channel, set()))\n        txns = channel_count.get(channel, 0)\n        attribution[channel] = {\n            \"revenue\": round(rev, 2),\n            \"revenue_share_pct\": round(rev \u002F max(total_revenue, 0.01) * 100, 1),\n            \"unique_customers\": custs,\n            \"transaction_count\": txns,\n            \"arpu\": round(rev \u002F max(custs, 1), 2),\n            \"avg_transaction\": round(rev \u002F max(txns, 1), 4),\n        }\n\n    return {\n        \"total_revenue\": round(total_revenue, 2),\n        \"channels\": attribution,\n        \"concentration_risk\": _assess_concentration_risk(attribution),\n    }\n\n\ndef _assess_concentration_risk(attribution: dict) -> dict:\n    \"\"\"Evaluate revenue concentration across channels.\n\n    A healthy business derives no more than 50% from any single channel.\n    \"\"\"\n    shares = {ch: data[\"revenue_share_pct\"] for ch, data in attribution.items()}\n    max_channel = max(shares, key=shares.get) if shares else \"none\"\n    max_share = shares.get(max_channel, 0)\n\n    if max_share >= 80:\n        risk = \"critical\"\n        recommendation = f\"Dangerously concentrated in {max_channel}. Diversify immediately.\"\n    elif max_share >= 60:\n        risk = \"high\"\n        recommendation = f\"Heavy reliance on {max_channel}. Build alternative channels.\"\n    elif max_share >= 40:\n        risk = \"moderate\"\n        recommendation = \"Reasonable distribution. Continue monitoring.\"\n    else:\n        risk = \"low\"\n        recommendation = \"Well-diversified revenue. Maintain current strategy.\"\n\n    return {\n        \"dominant_channel\": max_channel,\n        \"dominant_share_pct\": max_share,\n        \"risk_level\": risk,\n        \"recommendation\": recommendation,\n    }\n\n\n# ── 5. Churn-Aware Revenue Forecasting ───────────────────────────────────────\n\ndef forecast_revenue(\n    customer_ids: list[str],\n    months_ahead: int = 6,\n) -> dict:\n    \"\"\"Project revenue forward using churn risk and LTV data.\n\n    For each customer, uses CustomerAnalytics.calculate_churn_risk to\n    classify risk as high\u002Fmedium\u002Flow, then applies survival probabilities\n    to their average monthly revenue to build a forward projection.\n    \"\"\"\n    analytics = CustomerAnalytics(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n    tracker = RevenueTracker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    # Survival probability per month by risk tier\n    monthly_survival = {\"low\": 0.95, \"medium\": 0.85, \"high\": 0.65}\n\n    customer_projections = []\n\n    for cid in customer_ids:\n        try:\n            # Get churn risk classification\n            risk_result = analytics.calculate_churn_risk(customer_id=cid)\n            risk_tier = risk_result.get(\"risk\", \"medium\")\n\n            # Get customer invoice history for ARPU\n            history = tracker.get_transaction_history(customer_id=cid)\n            invoices = history.get(\"invoices\", [])\n            if not invoices:\n                continue\n\n            total_rev = sum(float(inv.get(\"amount\", 0)) for inv in invoices)\n            # Estimate months active from first to last invoice\n            dates = sorted(inv.get(\"created_at\", \"\")[:10] for inv in invoices)\n            try:\n                first_dt = datetime.fromisoformat(dates[0])\n                last_dt = datetime.fromisoformat(dates[-1])\n                months_active = max((last_dt - first_dt).days \u002F 30.44, 1)\n            except (ValueError, TypeError, IndexError):\n                months_active = 1\n\n            avg_monthly = total_rev \u002F months_active\n            survival = monthly_survival.get(risk_tier, 0.85)\n\n            # Project forward\n            projections = []\n            for month in range(1, months_ahead + 1):\n                survival_at_month = survival ** month\n                expected_revenue = avg_monthly * survival_at_month\n                projections.append({\n                    \"month\": month,\n                    \"survival_probability\": round(survival_at_month, 4),\n                    \"expected_revenue\": round(expected_revenue, 2),\n                })\n\n            customer_projections.append({\n                \"customer_id\": cid,\n                \"risk_tier\": risk_tier,\n                \"avg_monthly_revenue\": round(avg_monthly, 2),\n                \"projections\": projections,\n            })\n        except Exception:\n            continue\n\n    # Aggregate: sum expected revenue across all customers per month\n    monthly_totals = defaultdict(float)\n    for cp in customer_projections:\n        for proj in cp[\"projections\"]:\n            monthly_totals[proj[\"month\"]] += proj[\"expected_revenue\"]\n\n    forecast = [\n        {\"month\": m, \"expected_revenue\": round(rev, 2)}\n        for m, rev in sorted(monthly_totals.items())\n    ]\n\n    # At-risk revenue: customers flagged as high churn risk\n    at_risk_customers = analytics.get_at_risk_customers(threshold=10)\n\n    return {\n        \"months_ahead\": months_ahead,\n        \"customer_count\": len(customer_projections),\n        \"monthly_forecast\": forecast,\n        \"total_forecast_revenue\": round(sum(f[\"expected_revenue\"] for f in forecast), 2),\n        \"at_risk_summary\": at_risk_customers,\n        \"customer_detail\": customer_projections,\n    }\n\n\n# ── Main: Run the Full Pipeline ──────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n    import json\n\n    print(\"=\" * 72)\n    print(\"GreenHelix Revenue Pipeline\")\n    print(\"=\" * 72)\n\n    # Step 1: Revenue dashboard\n    print(\"\\n[1\u002F5] Building revenue dashboard...\")\n    dashboard = build_revenue_dashboard(period=\"30d\")\n    print(f\"  Total revenue: ${dashboard['total_revenue']}\")\n    print(f\"  Total calls: {dashboard['total_calls']}\")\n    print(f\"  Revenue\u002Fcall: ${dashboard['revenue_per_call']}\")\n\n    # Step 2: Attribution model\n    print(\"\\n[2\u002F5] Building attribution model...\")\n    attribution = build_attribution_model()\n    for ch, data in attribution[\"channels\"].items():\n        print(f\"  {ch}: ${data['revenue']} ({data['revenue_share_pct']}%)\")\n    print(f\"  Concentration risk: {attribution['concentration_risk']['risk_level']}\")\n\n    # Step 3: Cohort analysis\n    print(\"\\n[3\u002F5] Building monthly cohorts...\")\n    cohorts = build_monthly_cohorts()\n    for month, count in sorted(cohorts[\"cohorts\"].items()):\n        print(f\"  {month}: {count} customers\")\n\n    # Step 4: LTV calculation (example customer IDs)\n    print(\"\\n[4\u002F5] Calculating customer LTV...\")\n    # Replace with your actual customer agent IDs\n    sample_customers = [\n        \"customer-agent-001\", \"customer-agent-002\",\n        \"customer-agent-003\", \"customer-agent-004\",\n    ]\n    ltv_report = calculate_customer_ltv(sample_customers)\n    print(f\"  LTV: ${ltv_report['ltv']['ltv']}\")\n    print(f\"  Churn rate: {ltv_report['churn_rate'] * 100:.1f}%\")\n    print(f\"  Expected lifetime: {ltv_report['expected_lifetime_months']} months\")\n    print(f\"  Segments: {ltv_report['segments']}\")\n\n    # Step 5: Revenue forecast\n    print(\"\\n[5\u002F5] Forecasting revenue (6 months)...\")\n    forecast = forecast_revenue(sample_customers, months_ahead=6)\n    for entry in forecast[\"monthly_forecast\"]:\n        print(f\"  Month +{entry['month']}: ${entry['expected_revenue']}\")\n    print(f\"  Total 6-month forecast: ${forecast['total_forecast_revenue']}\")\n\n    print(\"\\n\" + \"=\" * 72)\n    print(\"Pipeline complete.\")\n    print(\"=\" * 72)\n```\n\n",{"name":5,"tags":24,"type":32,"author":36,"install":37,"license":15,"version":38,"metadata":39,"price_usd":44,"executable":20,"credentials":45,"description":7,"content_type":46,"compatibility":47},[25,26,27,28,29,30,31,32,33,34,35],"revenue","analytics","ltv","cohorts","churn","pricing","attribution","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":40},{"requires":41,"primaryEnv":43},{"env":42},[43],"GREENHELIX_API_KEY",39,[43],"markdown",[34],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-revenue-analytics",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":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-revenue-analytics",{"tool":63,"command":64},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-revenue-analytics",{"tool":66,"command":67},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-revenue-analytics","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-revenue-analytics\u002FSKILL.md",true,[],[72,79,86,93,100,107],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"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":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"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":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"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":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"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":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"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":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"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",[],[]]