spendpol 0.2.0
Spendpol — AI Spend Protocol. Delegated spending governance for autonomous AI agents.
License: MIT
Requires Python: >=3.10
Keywords: ai, agents, spending, governance, protocol, fintech, llm, multi-agent

# 🔐 Spendpol

**AI Spend Protocol — Governance for autonomous agent spending.**

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![Tests](https://img.shields.io/badge/tests-112%20passed-brightgreen.svg)]()

Spendpol is an open protocol that sits between AI agents and payment systems. It answers one question:

> **"Should this agent be allowed to make this expenditure?"**

Spendpol does not move money. It governs whether money should move.

---

## Why Spendpol?

AI agents are calling APIs, purchasing compute, and consuming paid services. But spending controls are stuck in the human era: hardcoded API keys, manual approval, cloud budget alerts.

As agents scale from 1 to 1,000 and delegate tasks to sub-agents, the uncontrolled spending surface grows exponentially. Spendpol provides the governance layer.

```
Agent Logic → [Spendpol] → Payment Execution
                 │
                 ├── Is this agent authorized?
                 ├── Within spending limits?
                 ├── Anomaly detected?
                 └── Audit logged ✓
```

## Install

```bash
pip install spendpol
```

## Quick Start

```python
from spendpol import SpendpolClient

client = SpendpolClient()

# Human grants spending authority to an agent
client.grant(
    delegator="user:john@acme.com",
    delegatee="agent-research",
    max_per_transaction=1.00,
    max_daily=10.00,
    max_monthly=200.00,
    allowed_vendors=["openai", "anthropic"],
    allowed_actions=["api_call"],
)

# Agent requests permission to spend
verdict = client.check_intent(
    agent_id="agent-research",
    vendor="openai",
    action="api_call",
    amount=0.03,
    purpose="Generate embeddings for ticket #4521",
)

if verdict.allowed:
    result = call_openai_api()  # Your payment execution
    client.log_receipt(verdict, actual_amount=0.028)
elif verdict.denied:
    print(f"Blocked: {verdict.evaluations[-1].detail}")
```

## CrewAI Integration

```python
from spendpol.crewai import SpendpolCrewMiddleware

asp = SpendpolCrewMiddleware(
    delegator="user:john@acme.com",
    default_daily_limit=10.00,
    allowed_vendors=["openai", "anthropic"],
)

# Decorator: one line to control any tool's spending
@asp.controlled(vendor="openai", action="api_call", cost_per_call=0.03)
def embedding_tool(text: str) -> list[float]:
    return openai.embeddings.create(input=text)

# Automatically: checks policy → executes → logs receipt
result = embedding_tool("Hello world")
```

## Core Concepts

| Concept | What it does |
|---|---|
| **SpendIntent** | Agent declares "I want to spend $X on Y" |
| **PolicyVerdict** | Engine responds: allow / deny / escalate |
| **SpendReceipt** | Records what actually happened |
| **AuditQuery** | Anyone can inspect spending history |
| **DelegationGrant** | Human gives agent permission with limits |
| **Attenuation** | Sub-agents can only have *fewer* permissions, never more |

## What Spendpol Is NOT

- **Not a wallet** — holds no funds
- **Not a payment processor** — moves no money
- **Not a blockchain** — no consensus, no tokens
- **Not KYC/AML** — no identity verification
- **Not a legal entity** — agents have no personhood

Spendpol's regulatory surface is equivalent to a logging tool, not a financial service.

## Architecture

```
spendpol/
├── schemas.py             # Protocol message types
├── delegation.py          # Delegation chains + attenuation
├── wallet.py              # Non-custodial spending tracker
├── policy.py              # Deterministic policy engine
├── audit.py               # Append-only audit log
├── validator.py           # Message validation + verification
├── service.py             # Agent-to-agent commerce registry
├── client.py              # High-level SDK
├── crewai.py              # CrewAI middleware
├── langgraph.py           # LangGraph middleware
├── autogen.py             # AutoGen middleware
├── schemas/               # JSON Schema definitions (Draft 2020-12)
│   ├── spend-intent.schema.json
│   ├── policy-verdict.schema.json
│   ├── spend-receipt.schema.json
│   ├── delegation-grant.schema.json
│   ├── audit-query.schema.json
│   ├── cost-estimate.schema.json
│   ├── service-offer.schema.json
│   ├── service-quote.schema.json
│   └── service-result.schema.json
├── examples/              # Test vector payloads
│   ├── spend-intent.json
│   ├── policy-verdict-allow.json
│   ├── policy-verdict-deny.json
│   ├── spend-receipt.json
│   ├── delegation-grant.json
│   ├── audit-query.json
│   ├── service-offer.json
│   ├── service-quote.json
│   └── service-result.json
├── test_core.py           # 67 core tests
├── test_langgraph.py      # 22 LangGraph tests
├── test_autogen.py        # 23 AutoGen tests
└── WHITEPAPER.md          # Full protocol specification
```

## Run Tests

```bash
pip install pytest
python -m pytest test_core.py test_langgraph.py test_autogen.py -v
```

## Protocol Specification

Read the full [WHITEPAPER.md](WHITEPAPER.md) for:
- Complete message schemas with JSON examples
- Delegation model and attenuation principle
- Policy engine evaluation order
- Anomaly detection specification
- Trust and liability model
- Audit role taxonomy

## Roadmap

- [x] Core protocol (4 message types)
- [x] Delegation chains with attenuation
- [x] Deterministic policy engine
- [x] Anomaly detection (confidence-aware)
- [x] Audit log with role-based access
- [x] CrewAI integration
- [x] LangGraph integration
- [x] AutoGen integration
- [x] REST API server ([spendpol-cloud](https://github.com/spendpol/spendpol-cloud))
- [x] Dashboard (spend analytics)
- [x] PyPI publish
- [x] Agent-to-agent commerce (Phase 1)

## Contributing

Spendpol is an open protocol. Contributions welcome.

1. Fork the repo
2. Create your feature branch (`git checkout -b feature/my-feature`)
3. Run tests (`python -m pytest test_core.py test_langgraph.py test_autogen.py -v`)
4. Submit a PR

## License

- **Python code** (reference implementation): [MIT](LICENSE)
- **Protocol specification** (WHITEPAPER.md, JSON Schemas): [CC-BY-4.0](LICENSE-SPEC)

See [DISCLAIMER.md](DISCLAIMER.md) for important legal notices.

---

*Cloud computing gave machines compute. Spendpol gives machines governance.*