# Paegents Python SDK

Official Python SDK for integrating Paegents agent payments.

## Installation

```bash
pip install paegents
```

## Initialize

```python
import os
from paegents import PaegentsSDK

sdk = PaegentsSDK(
    api_url=os.getenv('PAEGENTS_API_URL', 'https://api.paegents.com'),
    agent_id=os.environ['PAEGENTS_AGENT_ID'],
    api_key=os.environ['PAEGENTS_API_KEY'],
    owner_jwt=os.getenv('OWNER_JWT'),  # optional
)
```

## AP2 Quick Start

```python
from paegents import build_card_payment_method

intent = sdk.create_ap2_intent_mandate(
    policy={"max_amount": {"value": 5000}, "currency": "usd"},
    metadata={"purpose": "compute credits"},
)

cart = sdk.create_ap2_cart_mandate(
    intent_mandate_id=intent.id,
    cart={"total": 2500, "currency": "usd"},
)

payment = sdk.ap2_pay(
    intent_mandate_id=intent.id,
    cart_mandate_id=cart.id,
    payment_method=build_card_payment_method(provider='stripe'),
)

if isinstance(payment, dict) and payment.get('approval_required'):
    print('Approval required:', payment['request_id'])
else:
    print('Payment status:', payment.status)
```

## Usage Agreements

```python
import time
from paegents import UsageAgreementRequest

agreement = sdk.create_usage_agreement(
    UsageAgreementRequest(
        seller_agent_id='seller-agent-123',
        service_id='svc_abc123',
        quantity=1000,
        unit='api_calls',
        price_per_unit_cents=10,

        # Required agreement authorization fields
        buyer_wallet_address='0xBuyerWallet...',
        buyer_permit_signature='0xPermitSignature...',
        buyer_permit_deadline=int(time.time()) + 600,
        buyer_deposit_auth_signature='0xDepositAuthSignature...',
        buyer_deposit_auth_deadline=int(time.time()) + 600,

        client_proposal_id='proposal_001',
    )
)

sdk.accept_usage_agreement(agreement.agreement_id)
current = sdk.get_usage_agreement(agreement.agreement_id)
print(current.status)
```

### Optional: Metered Client

```python
client = sdk.create_metered_client(agreement.agreement_id)

result = client.post('/generate', json={
    'prompt': 'hello world',
    'max_tokens': 150,
})

usage = client.get_usage_status()
print(usage.units_used, usage.units_remaining)
```

## Policies and Approvals

Owner JWT is required for these endpoints.

```python
import os

owner_jwt = os.environ['OWNER_JWT']

sdk.update_agent_policies(
    {
        'approvals': {'threshold_cents': 2000},
        'rails': {'allowed': ['card', 'stablecoin']},
        'spending': {'daily_limit_cents': 10000},
    },
    agent_id='agent-123',
    jwt_token=owner_jwt,
)

pending = sdk.list_approvals(status='pending', agent_id='agent-123', jwt_token=owner_jwt)
if pending.get('approvals'):
    sdk.approve_approval(pending['approvals'][0]['id'], agent_id='agent-123', jwt_token=owner_jwt)
```

## Webhooks

```python
import os

owner_jwt = os.environ['OWNER_JWT']

webhook = sdk.create_webhook(
    url='https://example.com/webhooks',
    event_types=['payment.*', 'agreement.*'],
    agent_id='agent-123',
    jwt_token=owner_jwt,
)

print(webhook.get('id'))
```

### Verify Webhook Signatures

```python
from paegents import verify_webhook_signature

verify_webhook_signature(signature_header, raw_body, os.environ['PAEGENTS_WEBHOOK_SECRET'])
```

## Error Handling

```python
from paegents import ApiError, PolicyDeniedError

try:
    sdk.ap2_pay(
        intent_mandate_id='intent_123',
        cart_mandate_id='cart_123',
        payment_method=build_card_payment_method(),
    )
except PolicyDeniedError as exc:
    print('Policy denied:', exc)
except ApiError as exc:
    print('API error:', exc)
except Exception as exc:
    print('Unexpected error:', exc)
```

## Notes

- Prefer SDK methods over manual HTTP calls.
- Keep API keys and JWTs in environment variables.
- Use idempotency keys on critical write operations.

## Support

- Docs: https://docs.paegents.com
- API docs: https://docs.paegents.com/api
- Support: support@paegents.com

## License

MIT
