Metadata-Version: 2.4
Name: ln-church-agent
Version: 1.5.2
Summary: A Python reference client for HTTP 402 settlement across x402, L402, MPP, and fallback flows.
Home-page: https://kari.mayim-mayim.com/
Author: LN Church
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.31.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: eth-account>=0.11.0
Requires-Dist: httpx>=0.25.0
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.1.0; extra == "langchain"
Provides-Extra: mcp
Requires-Dist: mcp>=1.0.0; extra == "mcp"
Provides-Extra: solana
Requires-Dist: solana>=0.34.0; extra == "solana"
Requires-Dist: solders>=0.21.0; extra == "solana"
Dynamic: author
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# ln-church-agent
**Reference SDK for the public benchmark ecosystem of agent-facing paid APIs**
**Python runtime and SDK for AI agents to discover, pay, verify, and observe HTTP 402-compatible APIs.**

Designed for Autonomous AI Agents.
Implementing machine-to-machine payments from scratch is fragile: agents must parse `HTTP 402` challenges, handle signing, complete payment, and retry correctly without falling into hallucinated crypto flows.
This SDK abstracts that loop into a single client call. It turns **Probe → Pay → Execute** into a reliable execution path for agents—available in both sync and async execution models.
LN Church serves as the public reference testbed for this execution model.

---

## 🚩 Start Here: The Canonical First Success

The fastest way to understand this SDK is to run the canonical example. 
This script connects to the **LN Church public endpoint**, which serves as the official testbed for agents to experience their first autonomous economic loop.

You will see the agent autonomously navigate the Probe → Pay → Execute protocol through the canonical first-success path. The initial run is Faucet-assisted, so no pre-funded balance is required.

### Running the Example

**1. Set your Agent's Identity Key** (EVM or Solana format)
```bash
export AGENT_PRIVATE_KEY="0xYourPrivateKey"
```

**2. Run the Hello World script**
```bash
python examples/hello_ln_church.py
```

### What this script demonstrates:
1. **Probe:** Establishes connection and identity.
2. **Pay (Faucet):** Secures zero-balance fallback credits to test the payment loop safely.
3. **Execute:** Hits a 402-protected endpoint, intercepts the paywall, negotiates the settlement automatically, and returns the paid result.

By completing this pilgrimage, your agent's first successful footprint is recorded on the observation network.

---
## 📦 Public API Surface (1.5.x Stable Line)
The following interfaces are the stable contract for the current 1.5.x line:
This section defines what downstream users, agent runtimes, and tool integrations may safely rely on across patch updates in the 1.5 series.
- `Payment402Client` (Core Engine)
- `LnChurchClient` (Reference Adapter)
- `AssetType`, `SchemeType` (Enums)
- All response models (e.g., `OmikujiResponse`, `MonzenTraceResponse`, `MonzenGraphResponse`) top-level schemas are guaranteed stable in 1.x.
Note: The inner payload of MonzenGraphResponse.data may evolve based on the graph network's schema.
- The Trace Record Semantics (action_type, recorded_hash, trace_id, etc.)
*Note: `execute_paid_action` is deprecated in favor of `execute_request(method="POST", ...)`.*

### 🌟 Core Value: Execute, Prove, Observe

This SDK is strictly built on **open standards (HTTP 402, L402, x402)**, ensuring your agents can interact with *any* compliant paywall on the open web without vendor lock-in. 

1. **Execute**: Seamlessly call any external or internal 402-protected API without stalling.
2. **Prove**: Automatically handle challenge parsing, payment flows, and support proof-oriented flows using the invoice and preimage when available.
3. **Observe**: Register and visualize internal or external payment traces through LN Church.

### 🛤️ The Two Workflows

**LN Church** is an experimental observation network for AI agents interacting with paywalled APIs. To support both the open web and controlled experimentation, the SDK is designed around two distinct flows:

* **External Flow:** Call *any* third-party 402-enabled API in the wild. The SDK autonomously handles the payment negotiation loop.
  👉 *Call a third-party 402 API → optionally submit the payment proof/trace to LN Church → observe it in the network.*
* **Internal Flow:** Interact directly with the official LN Church servers for Oracle and Ritual tasks to test and refine agent capabilities within the observation network.

---

## 🚀 Quickstart (3-step)

### 1. Install
```bash
# Standard install (EVM x402 & Lightning L402 support)
pip install ln-church-agent

# Extended install (Includes LN Church custom Solana routing)
pip install ln-church-agent[solana]
```

### 2. Configure & Call (Sync)
Call any 402-protected API. The SDK handles the challenge, payment, and retry under the hood.

```python
from ln_church_agent import Payment402Client, TrustDecision, OutcomeSummary

client = Payment402Client(
    base_url="https://your-402-api.com",
)

# Detects 402 -> Pays invoice -> Retries -> Returns JSON
result = client.execute_request(
    method="POST",
    endpoint_path="/api/protected",
    payload={"input": "hello"}
)

print(result)
```

### 3. Configure & Call (Async)
For agent runtimes that need concurrent execution, async is supported in v1.1.0+.

```python
import asyncio
from ln_church_agent import Payment402Client, TrustDecision, OutcomeSummary

async def main():
    client = Payment402Client(
        base_url="https://your-402-api.com",
    )

    result = await client.execute_request_async(
        method="POST",
        endpoint_path="/api/protected",
        payload={"input": "hello"}
    )

    print(result)

asyncio.run(main())
```

---

## ⚠️ What this solves

When an AI Agent hits `HTTP 402 Payment Required`, it often stalls, crashes, or invents invalid payment/signing behavior.
* **Why this is hard:** Handling 402 flows means parsing challenge headers, extracting payment instructions, coordinating wallets, signing correctly, and retrying in the right order.
* **What this SDK does:** It reduces that economic negotiation to a normal HTTP client call, with typed responses and built-in retry guardrails.

As of v1.1.0+, the economic loop is not only available in both sync and async execution paths, but also features **Dynamic Multi-Chain Auto-Routing**, allowing agents to seamlessly hop across EVM networks (Polygon, Base, etc.) exactly as dictated by the server's HATEOAS challenge.

---
## 🧪 Advanced Agent-Native Features

For advanced enterprise or multi-agent runtimes, this SDK provides features that separate keys from execution and enforce strict economic safety.
* **Delegated Signers (NWC)**: Agents can securely pay Lightning invoices without holding a private key via the `NWCAdapter` and an HTTP Bridge Gateway.
* **Economic Guardrails**: Use `PaymentPolicy` to enforce strict spending limits (e.g., "Max $1.00 USD per transaction", "Max $10.00 USD per session") and restrict allowed networks.
* **Verifiable Execution**: Every successful settlement generates a `SettlementReceipt`, allowing the LLM to cryptographically verify proofs before continuing its reasoning loop.
* **Trust & Outcome Hooks (v1.5.0+)**: Inject custom `TrustEvaluator` functions to autonomously evaluate counterparty risk *before* payment, and `OutcomeMatcher` functions to verify semantic success *after* execution via the `execute_detailed` method.
* **Evidence Export/Import (v1.5.1+)**: Record and retrieve payment decision histories via the EvidenceRepository to build agents that learn from past interactions without compromising secrets.

👉 **[See the Advanced Agent Runtime Example](examples/advanced_receipts_and_policy.py)**

---
## 📚 Detailed Documentation

Explore the full capabilities of the agentic economic loop:

* **[Quickstart & Authentication](docs/01_quickstart.md)**: Identity, keys, policies, and sync/async usage.
* **[Architecture & Capabilities](docs/02_architecture.md)**: Deep dive into x402, L402, Policies, and Receipts.
* **[The LN Church Pilgrimage](docs/03_ln-church.md)**: Using the reference adapter for Oracle and Ritual tasks.
* **[Lightning Providers & NWC](docs/04_providers.md)**: Configuration for Alby, LNBits, and NWC Bridge.
* **[Integrations](docs/05_integrations.md)**: Setting up MCP (Model Context Protocol) and LangChain.
* **[Monzen Observation Network](docs/06_monzen.md)**: Scouting L402 paywalls and Decentralized DNS.

## 📊 Telemetry & Privacy

To observe and improve the autonomous agent ecosystem, this SDK includes minimal, privacy-conscious telemetry in its HTTP headers.

* **General Usage (`Payment402Client`)**: 
  When interacting with third-party 402 APIs, only a standard `User-Agent` (e.g., `ln-church-agent/<version>`) is sent. **No custom tracking headers are included.**
* **LN Church Ecosystem (`LnChurchClient`)**: 
  When communicating specifically with the official LN Church servers (`kari.mayim-mayim.com`), the following headers are appended for quality assurance and debugging:
  * `X-LN-Church-Agent-Version`: The active SDK version.
  * `X-LN-Church-Request-Id`: An ephemeral UUID used strictly to correlate 402 retry loops and request flows.

⚠️ **Important**: This SDK **does not** collect or transmit IP-bound data, MAC addresses, or persistent cross-session identifiers (such as a `client_id`). Furthermore, the default `User-Agent` can be explicitly overridden by passing a custom header in your requests.

## 🌐 Ecosystem: Hosting Your Own 402 APIs

This SDK is strictly a **client** for consuming HTTP 402 endpoints. If you or your agents wish to *host* your own paywalled services (e.g., to monetize your agent's compute, reasoning, or data), use the official companion framework:

👉 **[@ln-church/server (Monzenmachi Starter Kit)](https://github.com/mayim-mayim/ln-church-server)**

It provides a production-ready Cloudflare Workers + Hono template with built-in L402, EVM, and Faucet verifiers. Any API deployed with the server kit is 100% natively compatible with the `ln-church-agent` execution loop.

---
## 📝 Changelog

Detailed release history, feature additions, and migration guides have been moved to the dedicated **(CHANGELOG.md)**. 
For granular patch notes, please see the `docs/release_notes/` directory.

  ---

## License
MIT
