# AGENTS.md — Buddo API

**Version:** SDK v0.2 | **API Base:** `https://api.buddo.xyz` | **Spec:** v4.0.0 (91 paths, 107 operations) | **Date:** 2026-11-18 | **Updated:** S468

> An LLM agent reading only this file can authenticate and call the Buddo platform API.
> All examples are verified against the live API OpenAPI spec (spec v4.0.0, 91 paths, regenerated S468).

---

## Table of Contents

1. [Platform Overview](#1-platform-overview)
2. [Quick Start](#2-quick-start)
3. [Authentication](#3-authentication)
4. [OAuth Scopes](#4-oauth-scopes)
5. [Core Endpoints (Bot-Critical)](#5-core-endpoints-bot-critical)
6. [Endpoint Reference — User & Points](#6-endpoint-reference--user--points)
7. [Endpoint Reference — Ads](#7-endpoint-reference--ads)
8. [Endpoint Reference — Business & Campaigns](#8-endpoint-reference--business--campaigns)
9. [Endpoint Reference — Deploy](#9-endpoint-reference--deploy)
10. [Endpoint Reference — Social](#10-endpoint-reference--social)
11. [Pagination](#11-pagination)
12. [Rate Limits](#12-rate-limits)
13. [Idempotency](#13-idempotency)
14. [Error Codes and Exception Handling](#14-error-codes-and-exception-handling)
15. [Response Schemas](#15-response-schemas)
16. [Common Agent Workflows](#16-common-agent-workflows)
17. [Troubleshooting / Common Failure Modes](#17-troubleshooting--common-failure-modes)

---

## 1. Platform Overview

Buddo is a loyalty and ad platform for businesses (games, apps, websites).

- **Businesses** register apps and integrate Buddo points into their products.
- **Users** earn Buddo points through ad views (serve + event flow).
- **Campaign escrow** pays both users and businesses: each ad payout is a transfer out of the campaign's up-front-funded escrow, not newly issued points.
- **No Bitcoin payouts** to users — Buddo points are loyalty tokens only.
- Businesses never fund ad payouts from their own balance; the campaign escrow pays both sides, and the main operating treasury is never debited by a payout.
- **No static API keys on `api.buddo.xyz`** — authentication there is always OAuth 2.0 PKCE (the separate `deploy.buddocloud.com` static-site front-door uses business-scoped `fd_` keys; see the routing note in section 3).

**Base URL:** `https://api.buddo.xyz`
All SDK paths are relative to this base. Full endpoint URLs: `https://api.buddo.xyz/api/...`

**OpenAPI Spec:** `https://api.buddo.xyz/.well-known/openapi.json`
**Buddo Business Dashboard:** `https://api.buddo.xyz/dashboard`
**Health:** `GET /health` → `{"status": "ok", "version": "..."}`

---

## 2. Quick Start

### Installation

```bash
pip install buddo-py
```

Requires Python 3.9+.

### Get Your Credentials

1. Register at the dashboard or via `POST /api/operators/register`
2. Login via `POST /api/auth/login` to get a JWT
3. Verify email via `POST /api/auth/self-verify-email` (no inbox needed)
4. Create OAuth app via `POST /api/oauth/apps` — get `client_id` and `client_secret`
5. **Save `client_secret` immediately** — it is shown only once

> **CRITICAL:** There are no static API keys. The live API exclusively uses OAuth 2.0 PKCE for authentication. The `bdk_live_*` format is not a valid credential on the live API.

### Minimal Working Example — PKCE Flow

```python
import asyncio
import base64
import hashlib
import httpx
import secrets

BASE = "https://api.buddo.xyz"

async def main():
    async with httpx.AsyncClient(timeout=30) as http:
        # Step 1: Login to get JWT
        r = await http.post(f"{BASE}/api/auth/login", json={
            "email": "your@email.com",
            "password": "your-password"
        })
        jwt = r.json()["token"]

        # Step 2: PKCE setup
        verifier = secrets.token_urlsafe(43)
        challenge = base64.urlsafe_b64encode(
            hashlib.sha256(verifier.encode()).digest()
        ).rstrip(b"=").decode()

        # Step 3: Get authorization code
        r = await http.get(f"{BASE}/api/oauth/authorize", params={
            "client_id": "YOUR_CLIENT_ID",
            "response_type": "code",
            "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
            "code_challenge": challenge,
            "code_challenge_method": "S256",
            "scope": "profile:read points:read analytics:read campaign:read",
        }, headers={"Authorization": f"Bearer {jwt}"})
        code = r.json()["code"]

        # Step 4: Exchange code for access token
        r = await http.post(f"{BASE}/api/oauth/token", json={
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
            "client_id": "YOUR_CLIENT_ID",
            "code_verifier": verifier,
        })
        access_token = r.json()["access_token"]
        print(f"Access token: {access_token[:20]}...")

asyncio.run(main())
```

### Agent Decision Tree

```
What are you trying to do?
├── Check user's balance           → GET /api/external/points         (user OAuth token)
├── Serve an ad to a user          → GET /api/external/ads/serve      (user OAuth token)
├── Record ad impression           → POST /api/external/ads/event     (user OAuth token + impression_token)
├── Get user profile               → GET /api/auth/me                 (user OAuth token)
├── List ad campaigns              → GET /api/v1/ads/campaigns        (business OAuth token)
├── Get one campaign               → GET /api/v1/ads/campaigns/{id}   (business OAuth token; token-only read)
├── Get campaign stats             → GET /api/v1/ads/analytics/campaign/{id}  (business token)
├── Manage deployments             → GET/POST /api/deploy/apps        (deploy:manage scope)
├── List friends                   → GET /api/social/friends          (user OAuth token)
└── Points history                 → GET /api/external/points         + GET /api/auth/me for full user
```

---

## 3. Authentication

The live Buddo API uses **OAuth 2.0 Authorization Code with PKCE** exclusively. There are no static API keys.

> Routing: `api.buddo.xyz` is the user/platform API using OAuth 2.0 PKCE; `deploy.buddocloud.com` is a separate static-site front-door using business-scoped `fd_` keys. Static-site hosting is a distinct product from the container-deploy API.

### The Two Token Contexts

| Token Type | Obtained By | Used For | Endpoints |
|-----------|-------------|----------|-----------|
| **JWT** (short-lived) | `POST /api/auth/login` | **PKCE authorize step only** | `GET /api/oauth/authorize` header |
| **Business token** | PKCE flow as the business user | Campaign management, analytics, deploy | `/api/operator/*`, `/api/v1/ads/*`, `/api/deploy/*` |
| **User token** | PKCE flow as the end user | Balance, ad serve/event, profile | `/api/external/*`, `/api/auth/me`, `/api/social/*` |

> **IMPORTANT:** The JWT from `POST /api/auth/login` is NOT an API token. It is used only as the `Bearer` header when calling `GET /api/oauth/authorize`. All other API calls require the OAuth `access_token` from `POST /api/oauth/token`.

### Full PKCE Authentication Flow

```python
import base64
import hashlib
import secrets
import httpx

BASE = "https://api.buddo.xyz"

async def get_access_token(
    email: str,
    password: str,
    client_id: str,
    scope: str,
    redirect_uri: str = "urn:ietf:wg:oauth:2.0:oob",
) -> str:
    """Full PKCE flow: returns access_token."""
    verifier = secrets.token_urlsafe(43)
    challenge = base64.urlsafe_b64encode(
        hashlib.sha256(verifier.encode()).digest()
    ).rstrip(b"=").decode()

    async with httpx.AsyncClient(timeout=30) as http:
        # Step 1: Login to get JWT (used only for authorize step)
        r = await http.post(f"{BASE}/api/auth/login",
            json={"email": email, "password": password})
        jwt = r.json()["token"]

        # Step 2: Get authorization code (pass JWT as Bearer)
        r = await http.get(f"{BASE}/api/oauth/authorize", params={
            "client_id": client_id,
            "response_type": "code",
            "redirect_uri": redirect_uri,
            "code_challenge": challenge,
            "code_challenge_method": "S256",
            "scope": scope,
        }, headers={"Authorization": f"Bearer {jwt}"})
        code = r.json()["code"]

        # Step 3: Exchange code for access token (no auth header needed)
        r = await http.post(f"{BASE}/api/oauth/token", json={
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri,
            "client_id": client_id,
            "code_verifier": verifier,
        })
        return r.json()["access_token"]
```

**PKCE requirements:**
- `code_challenge_method`: must be `"S256"` — plain text challenges not accepted
- `code_verifier`: 43-128 chars, unreserved URL chars (`secrets.token_urlsafe(43)` works)
- `redirect_uri`: `"urn:ietf:wg:oauth:2.0:oob"` for CLI/bot flows (out-of-band)

**Token TTL:**
- `access_token`: 1 hour (`expires_in: 3600`)
- On expiry: run PKCE flow again to get a fresh token

### New Business Registration

```python
async def register_business(email: str, password: str, business_name: str):
    async with httpx.AsyncClient() as http:
        # Step 1: Register
        r = await http.post(f"{BASE}/api/operators/register", json={
            "email": email,
            "business_name": business_name,
            "contact_name": "Automated Setup",
            "password": password,
        })
        r.raise_for_status()

        # Step 2: Login to get JWT
        r = await http.post(f"{BASE}/api/auth/login",
            json={"email": email, "password": password})
        jwt = r.json()["token"]

        # Step 3: Instant email verification
        await http.post(
            f"{BASE}/api/auth/self-verify-email",
            headers={"Authorization": f"Bearer {jwt}"},
        )

        # Step 4: Create OAuth app to get client_id + client_secret
        r = await http.post(f"{BASE}/api/oauth/apps", json={
            "name": business_name,
            "redirectUris": ["urn:ietf:wg:oauth:2.0:oob"],
            "scopes": ["profile:read", "points:read", "analytics:read", "campaign:read"],
        }, headers={"Authorization": f"Bearer {jwt}"})
        creds = r.json()
        print(f"client_id: {creds['client_id']}")
        print(f"client_secret: {creds['client_secret']}")  # SAVE NOW — shown only once
```

> **Note:** `POST /api/oauth/apps` uses camelCase body fields: `name` (not `app_name`), `redirectUris` (not `redirect_uris`), `scopes` (not `allowed_scopes`).

### Token Introspection

```bash
curl -X POST https://api.buddo.xyz/api/oauth/token/verify \
  -H "Content-Type: application/json" \
  -d '{"token": "YOUR_ACCESS_TOKEN"}'
```

Response (`TokenIntrospection`):
```json
{
  "active": true,
  "user_id": "uuid",
  "app_id": "uuid",
  "scopes": ["profile:read", "points:read"],
  "expires_at": "2026-06-16T16:00:00Z"
}
```

> **Note:** The introspection response uses `user_id` (not `sub`), `scopes` as an array (not `scope` as string), and `expires_at` (not `exp`).

---

## 4. OAuth Scopes

| Scope | Description | Required For |
|-------|-------------|--------------|
| `profile:read` | User profile, session info | `/api/auth/me`, `/api/external/user` |
| `points:read` | User point balance | `/api/external/points` |
| `analytics:read` | Business analytics (DAU, retention, earnings) | `/api/operator/analytics` |
| `app:balance:read` | Business app billing history and balance | `/api/operator/billing/history`, `/api/external/app/balance` |
| `campaign:read` | Granular (optional): read campaigns and analytics. Also satisfied by `campaigns:manage` | `/api/v1/ads/*` |
| `campaign:write` | Granular (optional): create/update/delete campaigns, set targeting. Also satisfied by `campaigns:manage` | `POST/PUT/DELETE /api/v1/ads/campaigns`, `/api/external/campaigns` |
| `campaign:manage` | Granular (optional, singular): pause, resume and cancel campaigns. Also satisfied by `campaigns:manage` | `/api/v1/ads/campaigns/{id}/pause`, `/api/v1/ads/campaigns/{id}/resume`, `/api/external/campaigns/{id}/pause`, `/api/external/campaigns/{id}/resume`, `DELETE /api/external/campaigns/{id}` |
| `campaigns:manage` | **Canonical campaign scope** — full campaign lifecycle management. Satisfies every granular `campaign:read` / `campaign:write` / `campaign:manage` requirement | All campaign CRUD + pause/resume/targeting |
| `deploy:manage` | Full deploy lifecycle management | `/api/deploy/*` (ALL endpoints) |
| ~~`points:award`~~ | **PERMANENTLY REMOVED** | N/A — use ad serve+event flow |
| ~~`operator:read`~~ | **PHANTOM — does not exist in backend** | N/A — use `analytics:read` + `app:balance:read` |
| ~~`operator:write`~~ | **PHANTOM — does not exist in backend** | N/A — `POST /api/oauth/apps` requires only a JWT, not this scope |

### Granular scopes (optional)

The canonical campaign scope is `campaigns:manage`. Apps that prefer narrower tokens can request `campaign:read`, `campaign:write`, or `campaign:manage` (singular — granular) individually; the authorization server accepts either the canonical `campaigns:manage` superset OR the specific granular scope at every campaign route. `campaign:read` covers reads, `campaign:write` covers create, update, delete, targeting and bulk purchase, and `campaign:manage` covers pause, resume and cancel. Read-only `/api/v1/ads/*` routes (including `GET /api/v1/ads/campaigns/{id}`) currently require a valid OAuth token but enforce no specific scope, so `campaign:read` is optional least-privilege for those reads.

Aliasing is one-way (superset only). A token holding `campaigns:manage` satisfies any granular requirement. A token holding only granular scopes never satisfies a `campaigns:manage` requirement, and one granular scope does not imply another or confer any additional privilege.

**Scope bundles for common integrations:**

| Use Case | Request These Scopes |
|----------|---------------------|
| Read user balance + profile | `profile:read`, `points:read` |
| Ad serving (user-facing) | `profile:read`, `points:read` |
| Business dashboard | `analytics:read`, `app:balance:read`, `campaign:read` |
| Full business bot | `profile:read`, `points:read`, `analytics:read`, `app:balance:read`, `campaign:read` |
| Deploy management | `deploy:manage` |
| Full business access | `analytics:read`, `app:balance:read`, `campaigns:manage`, `campaign:read`, `deploy:manage` |

> **CRITICAL:** `deploy:manage` is required for ALL `/api/deploy/*` endpoints. Requests without this scope return 403 `insufficient_scope`. Add it to your PKCE scope parameter when using the Deploy API.

---

## 5. Core Endpoints (Bot-Critical)

These endpoints cover the primary bot use cases — all verified live:

| Priority | Method | Path | Auth | Description |
|----------|--------|------|------|-------------|
| 1 | GET | `/api/external/points` | User OAuth token | User's Buddo points balance |
| 2 | GET | `/api/external/ads/serve` | User OAuth token | Get an ad to show (returns impression_token) |
| 3 | POST | `/api/external/ads/event` | User OAuth token | Record ad impression (single-use impression_token) |
| 4 | GET | `/api/auth/me` | User OAuth token | Full user profile (id, username, email, points, stats) |
| 5 | GET | `/api/v1/ads/campaigns` | Business OAuth token | List business's ad campaigns |
| 6 | GET | `/api/v1/ads/analytics/campaign/{id}` | Business OAuth token | Campaign stats |
| 7 | GET | `/api/deploy/apps` | `deploy:manage` scope | List deployed applications |
| 8 | POST | `/api/deploy/apps` | `deploy:manage` scope | Create deployment |

> **Note:** There is no direct points-award endpoint. Points are credited automatically by the treasury when `POST /api/external/ads/event` is accepted.

---

## 6. Endpoint Reference — User & Points

### GET /api/external/points

Returns the authenticated user's Buddo points balance.

```bash
curl -X GET https://api.buddo.xyz/api/external/points \
  -H "Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN"
```

**Response:**
```json
{"points": 1250}
```

### GET /api/auth/me

Returns the authenticated user's full profile including points, tier, and stats.

```bash
curl -X GET https://api.buddo.xyz/api/auth/me \
  -H "Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN"
```

**Response (MeResponse):**
```json
{
  "user": {
    "id": "uuid",
    "email": "alice@example.com",
    "username": "alice",
    "tier": "Demon",
    "tier_emoji": "😈",
    "points": 1250,
    "referral_code": "ALICE42",
    "signup_multiplier": 1,
    "email_verified": true,
    "totp_enabled": false,
    "stats": {
      "direct_referrals": 3,
      "connected_apps": 2,
      "total_earned": 5000,
      "total_spent": 3750
    }
  }
}
```

> **Note:** `/api/auth/me` returns a `{user: {...}}` wrapper. The `user` object includes `points` and `stats` — this is richer than the balance-only `GET /api/external/points`.

### GET /api/external/user

Returns a simplified user profile for external business use.

```bash
curl -X GET https://api.buddo.xyz/api/external/user \
  -H "Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN"
```

### GET /api/users/me/points (Points History)

```bash
curl -X GET "https://api.buddo.xyz/api/users/me/points?limit=20" \
  -H "Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN"
```

**Response (cursor-paginated):**
```json
{
  "data": [
    {
      "id": "txn_xyz789",
      "user_id": "uuid",
      "amount": 50,
      "balance_after": 1300,
      "reason": "ad_view",
      "inserted_at": "2026-06-16T10:30:00Z"
    }
  ],
  "cursor": "cursor_next",
  "total": 50
}
```

### POST /api/external/points/spend

Spend user points, crediting the business account.

```bash
curl -X POST https://api.buddo.xyz/api/external/points/spend \
  -H "Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"amount": 100}'
```

### POST /api/external/points/transfer

Transfer points from authenticated user to another user.

```bash
curl -X POST https://api.buddo.xyz/api/external/points/transfer \
  -H "Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"recipient_id": "uuid", "amount": 50}'
```

### GET /api/user/connected-apps

List all OAuth apps the authenticated user has authorized.

### DELETE /api/user/connected-apps/{app_id}

Revoke an OAuth app authorization for the authenticated user.

---

## 7. Endpoint Reference — Ads

### GET /api/external/ads/serve

Request an ad to serve to the user. Returns an `impression_token` required for recording the view.

```bash
curl -X GET "https://api.buddo.xyz/api/external/ads/serve?surface_type=banner" \
  -H "Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN"
```

**Query parameters:**
- `surface_type` — `"banner"` | `"video"` | `"interstitial"` (required)

**Response:**
```json
{
  "campaign": {
    "id": "4dbea4d9-eac0-490a-8dc7-6e2ccf86d34d",
    "payout_rate": 50
  },
  "impression_token": "eyJ..."
}
```

- `impression_token` is a single-use JWT — store it immediately
- Must call `POST /api/external/ads/event` within a reasonable time window

### GET /api/external/ads/serve/v2

Placement-aware ad serving (v2). Same interface as v1 but uses placement-level targeting.

```bash
curl -X GET "https://api.buddo.xyz/api/external/ads/serve/v2?surface_type=banner" \
  -H "Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN"
```

### POST /api/external/ads/event

Record that the user viewed the ad. Triggers treasury payout to user. Single-use impression_token.

```bash
curl -X POST https://api.buddo.xyz/api/external/ads/event \
  -H "Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "campaign_id": "4dbea4d9-eac0-490a-8dc7-6e2ccf86d34d",
    "event_type": "impression",
    "impression_token": "eyJ...",
    "surface_type": "banner"
  }'
```

**Response (200 or 201):**
```json
{
  "event": {
    "id": "uuid",
    "campaign_id": "uuid",
    "event_type": "impression",
    "surface_type": "banner",
    "payout_rate_snapshot": 50,
    "inserted_at": "2026-06-16T10:30:00Z"
  }
}
```

**Idempotency:** Replaying with the same `impression_token` returns **HTTP 422** `impression_token_replay`.

**Python SDK (2-step flow):**
```python
# Step 1: Serve ad to user
serve_result = await client.ads.serve_ad(surface_type="banner")
impression_token = serve_result.impression_token
campaign_id = serve_result.campaign.id

# Step 2: Record impression (after user views ad)
event = await client.ads.record_ad_event(
    campaign_id=campaign_id,
    impression_token=impression_token,
    surface_type="banner",
    event_type="impression",
)
```

### GET /api/external/app/balance

Get the business app's accumulated earned-point balance.

```bash
curl -X GET https://api.buddo.xyz/api/external/app/balance \
  -H "Authorization: Bearer YOUR_BUSINESS_OAUTH_TOKEN"
```

### Business Ad Campaigns (v1)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/ads/campaigns` | List campaigns, optional `?status=active` filter |
| POST | `/api/v1/ads/campaigns` | Create campaign |
| GET | `/api/v1/ads/campaigns/{id}` | Get one campaign with its audience targeting. Token-only read (no scope required); `404 campaign_not_found` if it does not exist, `403 forbidden` if another app owns it |
| PUT | `/api/v1/ads/campaigns/{id}` | Update campaign |
| DELETE | `/api/v1/ads/campaigns/{id}` | Delete campaign |
| POST | `/api/v1/ads/campaigns/{id}/pause` | Pause campaign |
| POST | `/api/v1/ads/campaigns/{id}/resume` | Resume campaign |
| GET | `/api/v1/ads/campaigns/{id}/targeting` | Get targeting config |
| POST | `/api/v1/ads/campaigns/{id}/targeting` | Set targeting config |
| GET | `/api/v1/ads/analytics/campaign/{id}` | Campaign analytics |
| GET | `/api/v1/ads/analytics/overview` | Analytics overview |
| GET | `/api/v1/ads/analytics/placement/{id}` | Placement analytics |
| GET | `/api/v1/ads/pricing/rates` | List pricing rates |
| GET | `/api/v1/ads/pricing/rates/{placement_id}` | Rate for placement |
| POST | `/api/v1/ads/pricing/bulk-quote` | Bulk pricing quote |
| GET | `/api/v1/ads/segments` | List audience segments |
| POST | `/api/v1/ads/purchases/bulk` | Execute bulk purchase |

```bash
# List active campaigns
curl -X GET "https://api.buddo.xyz/api/v1/ads/campaigns?status=active" \
  -H "Authorization: Bearer YOUR_BUSINESS_OAUTH_TOKEN"
```

**Campaign status values:** `draft` | `active` | `paused` | `completed` | `exhausted` | `cancelled`

### External Campaigns (business managing campaigns via external API)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/external/campaigns` | List business's campaigns |
| POST | `/api/external/campaigns` | Create campaign |
| GET | `/api/external/campaigns/{id}` | Get campaign |
| PUT | `/api/external/campaigns/{id}` | Update campaign |
| DELETE | `/api/external/campaigns/{id}` | Cancel campaign |

---

## 8. Endpoint Reference — Business & Campaigns

### GET /api/operator/analytics

Business dashboard analytics with DAU, retention, and earnings.

```bash
curl -X GET https://api.buddo.xyz/api/operator/analytics \
  -H "Authorization: Bearer YOUR_BUSINESS_OAUTH_TOKEN"
```

**Response (BusinessAnalytics):**
```json
{
  "earnings": {
    "total": 15000,
    "by_campaign": [{"campaign_id": "uuid", "name": "Summer", "total": 8000}],
    "by_period": [{"date": "2026-06-16", "total": 500}],
    "by_tier": {"bitcoin": 5000, "buddo": 10000},
    "by_surface": [{"surface": "banner", "total": 9000}]
  },
  "dau": {
    "last_30_days": [{"date": "2026-06-16", "active_users": 142}],
    "retention": {"day_1": 0.65, "day_7": 0.32, "day_30": 0.18}
  }
}
```

### GET /api/operator/billing/history

Fetch paginated billing history.

```bash
curl -X GET https://api.buddo.xyz/api/operator/billing/history \
  -H "Authorization: Bearer YOUR_BUSINESS_OAUTH_TOKEN"
```

### GET /api/operator/app

Get the business's own app profile and settings.

```bash
curl -X GET https://api.buddo.xyz/api/operator/app \
  -H "Authorization: Bearer YOUR_BUSINESS_OAUTH_TOKEN"
```

### PUT /api/operator/app

Update business app settings (description, logo, website URL, etc.).

### OAuth App Management

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/oauth/apps` | Register new OAuth app |
| GET | `/api/oauth/my-apps` | List owned OAuth apps |
| PUT | `/api/oauth/my-apps/{id}` | Update owned OAuth app |
| POST | `/api/oauth/my-apps/{id}/scope-request` | Request additional scopes |

> **Note:** `POST /api/oauth/apps` body uses camelCase: `{"name": "...", "redirectUris": [...], "scopes": [...]}`. The `client_secret` is returned only on creation — save it immediately.

---

## 9. Endpoint Reference — Deploy

The Deploy API enables programmatic management of container deployments. All endpoints require `deploy:manage` scope.

### GET /api/deploy/tiers

List available deployment tiers.

```bash
curl -X GET https://api.buddo.xyz/api/deploy/tiers \
  -H "Authorization: Bearer YOUR_BUSINESS_OAUTH_TOKEN"
```

**Response (DeployTier[]):**
```json
[
  {
    "id": "uuid",
    "name": "Starter",
    "slug": "starter",
    "payment_method": "buddo_points",
    "memory_limit_mb": 256,
    "cpu_limit_millicores": 500,
    "custom_domain_allowed": false,
    "monthly_stipend_points": 1000,
    "ad_reach_multiplier": "1.0",
    "monthly_cost_points": 500
  }
]
```

_The `slug`, `name` and limit values above are illustrative. The live `deploy_tiers` table is the only source of truth; always use a `slug` returned by this endpoint._

### GET /api/deploy/sandbox-status

Check if the sandbox environment is accepting deployments.

### POST /api/deploy/apps

Create a new deployment.

```bash
curl -X POST https://api.buddo.xyz/api/deploy/apps \
  -H "Authorization: Bearer YOUR_BUSINESS_OAUTH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-web-app",
    "image": "docker.io/library/nginx:latest",
    "port": 80,
    "env_vars": {"NODE_ENV": "production"},
    "custom_domain": "app.example.com"
  }'
```

**Required fields:**
- `name` — 1-32 chars, lowercase alphanumeric and hyphens (`^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`)
- `image` — must start with `harbor.buddo.xyz:4443/`, `docker.io/library/`, or `ghcr.io/`

**Optional:** `port` (default 3000), `env_vars` (max 50 keys), `custom_domain`

**Response (Deployment):**
```json
{
  "id": "uuid",
  "app_id": "uuid",
  "deploy_tier_id": "uuid",
  "container_name": "my-web-app",
  "container_image": "docker.io/library/nginx:latest",
  "subdomain": "my-web-app.buddo.app",
  "status": "deploying",
  "memory_limit_mb": 256,
  "cpu_limit_millicores": 500,
  "inserted_at": "2026-06-16T12:00:00Z"
}
```

**Status values:** `pending` | `deploying` | `running` | `stopped` | `destroyed`

### GET /api/deploy/apps

List all deployments. Optional `?status=running` filter.

### GET /api/deploy/apps/{id}

Get a single deployment by ID.

### GET /api/deploy/apps/{id}/status

Lightweight status check (poll this instead of full `/api/deploy/apps/{id}` during deployment).

```json
{"id": "uuid", "status": "running", "health_status": "healthy"}
```

### POST /api/deploy/apps/{id}/stop

Stop a running deployment.

### POST /api/deploy/apps/{id}/restart

Restart a stopped or running deployment.

### DELETE /api/deploy/apps/{id}

Permanently destroy a deployment. **Irreversible.**

### GET /api/deploy/apps/{id}/logs

Get action history logs (not application stdout). Returns `DeployLog[]`.

```json
[
  {
    "id": "uuid",
    "action": "deploy",
    "status": "completed",
    "inserted_at": "2026-06-16T12:02:30Z"
  }
]
```

**Action values:** `create` | `deploy` | `stop` | `restart` | `destroy` | `suspend` | `reactivate`

**Python SDK — Deploy + Poll Until Running:**
```python
import asyncio
from buddo import BuddoClient

async def deploy_and_wait(client, name: str, image: str):
    # Deploy
    app = await client.deploy.create_app(name=name, tier_id="tier_starter", env={})
    print(f"Deploying {app.id}: status={app.status}")

    # Poll until running
    while True:
        status = await client.deploy.get_app_status(app.id)
        if status.is_running:
            print(f"Live at: {app.id}.buddo.app")
            break
        await asyncio.sleep(5)

    # Fetch action logs
    logs = await client.deploy.get_app_logs(app.id, lines=50)
    print(logs.joined)
```

**Deploy Error Codes:**

| HTTP | Code | Description |
|------|------|-------------|
| 403 | `insufficient_scope` | Missing `deploy:manage` scope |
| 404 | `deployment_not_found` | App ID not found |
| 409 | `deployment_already_exists` | Name already in use |
| 422 | `insufficient_deploy_balance` | Not enough points/sats for tier |
| 422 | `sandbox_unavailable` | All sandbox slots in use |
| 422 | `invalid_image_url` | Image doesn't match allowed registries |
| 422 | `name_format_invalid` | Name doesn't match pattern |

---

## 10. Endpoint Reference — Social

All social endpoints require a user OAuth token.

### Friends

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/social/friends` | List confirmed friends → `Friend[]` |
| POST | `/api/social/friends` | Send friend request, body `{"user_id": "uuid"}` → `FriendshipResponse` |
| GET | `/api/social/friends/{id}` | Get friend by ID → `Friend` |
| PUT | `/api/social/friends/{id}` | Accept/reject request, body `{"status": "accepted"\|"rejected"}` |
| DELETE | `/api/social/friends/{id}` | Remove friendship |
| GET | `/api/social/friends/pending` | List pending requests → `Friend[]` |

```bash
# Send friend request
curl -X POST https://api.buddo.xyz/api/social/friends \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"user_id": "uuid-of-user"}'

# Accept incoming request
curl -X PUT https://api.buddo.xyz/api/social/friends/FRIENDSHIP_ID \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"status": "accepted"}'
```

**Friend schema:** `{id: uuid, username: string, email: string}`
**FriendshipResponse schema:** `{friendship_id: uuid, status: pending|accepted|rejected|removed}`

### Presence

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/social/presence` | Get friends' presence → `TablePresenceEntry[]` |
| POST | `/api/social/presence` | Update own presence, body `{"status": "online"\|"offline", "game_id"?: "uuid"}` |
| DELETE | `/api/social/presence` | Untrack own presence |
| GET | `/api/social/presence/table` | Get presence for a game table |

**TablePresenceEntry:** `{user_id, status: online|offline, last_seen}`

### Social Search & Block

```bash
# Search users
curl "https://api.buddo.xyz/api/social/users/search?q=alice" \
  -H "Authorization: Bearer YOUR_TOKEN"

# Block user
curl -X POST https://api.buddo.xyz/api/social/block \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"user_id": "uuid"}'

# Unblock
curl -X DELETE https://api.buddo.xyz/api/social/block/USER_ID \
  -H "Authorization: Bearer YOUR_TOKEN"
```

### Chat

```bash
# Create or get lobby channel
curl -X POST https://api.buddo.xyz/api/social/chat/channels \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"type": "lobby"}'

# Get message history
curl "https://api.buddo.xyz/api/social/chat/CHANNEL_ID/messages?limit=20" \
  -H "Authorization: Bearer YOUR_TOKEN"

# Send message
curl -X POST https://api.buddo.xyz/api/social/chat/CHANNEL_ID/messages \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"content": "Hello lobby!"}'
```

**ChatMessage schema:** `{id, sender_id, filtered_body, sent_at, sender_username?}`

> **Note:** Messages are returned newest-first. Use cursor pagination for history. Channel IDs come from `POST /api/social/chat/channels`.

### Avatar & Cosmetics

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/social/avatar` | Get own avatar |
| PUT | `/api/social/avatar` | Update appearance/display_name |
| GET | `/api/social/avatar/{user_id}` | Get any user's public avatar |
| PUT | `/api/social/avatar/equip` | Equip/unequip cosmetic, body `{"cosmetic_id": "uuid", "action": "equip"\|"unequip"}` |
| GET | `/api/social/cosmetics` | Browse cosmetic catalogue (public) |
| POST | `/api/social/cosmetics/{id}/purchase` | Purchase cosmetic |
| GET | `/api/social/cosmetics/inventory` | Own cosmetic inventory |

---

## 11. Pagination

### Cursor-Based Pagination (Standard)

```python
cursor = None
all_items = []

while True:
    page = await client.users.get_points_history(limit=50, cursor=cursor)
    all_items.extend(page.data)

    if not page.has_next:
        break
    cursor = page.cursor
```

**Query parameters:**
- `limit` — records per page (1-100, default 50)
- `cursor` — opaque string from previous response (omit for first page)

Chat history: pass `cursor` query param (timestamp-based for chat).

---

## 12. Rate Limits

| Endpoint | Limit | Window |
|----------|-------|--------|
| `POST /api/auth/login` | 5 requests | per minute per IP |
| `GET /api/external/*` reads | 60 requests | per minute per IP |
| `POST /api/external/*` writes | 30 requests | per minute per IP |
| `POST /api/external/ads/event` | 100 requests | per hour per IP (anti-fraud) |

**Rate limit response:** HTTP 429 with `Retry-After` header.

The `Retry-After` header may be in seconds (integer) or RFC-1123 date format — parse both.

**SDK auto-retry:** The SDK honors `Retry-After` with exponential backoff (3 retries default). `BuddoRateLimitError` raised only after all retries exhausted.

```python
except BuddoRateLimitError as e:
    await asyncio.sleep(e.retry_after)  # seconds until retry is safe
```

---

## 13. Idempotency

### Ad Impression Flow (impression_token)

| Scenario | Result |
|----------|--------|
| First `POST /api/external/ads/event` with token | Records event, credits user |
| Replay with **same impression_token** | **HTTP 422** `impression_token_replay` |

Each token is single-use. Call `GET /api/external/ads/serve` again for each impression.

### Points Spend / Transfer (body idempotency_key)

```json
{"amount": 100, "idempotency_key": "spend_event_001_usr_abc123"}
```

---

## 14. Error Codes and Exception Handling

### Error Response Format

```json
{
  "error": {
    "code": "snake_case_code",
    "message": "Human readable description",
    "details": {}
  }
}
```

Or flat format (some endpoints): `{"message": "Unauthorized"}`

### HTTP Status → SDK Exception → Error Codes

| HTTP | SDK Exception | Common Error Codes | Retryable |
|------|---------------|---------------------|-----------|
| 400 | `BuddoError` | `missing_required_fields`, `invalid_token`, `token_expired` | No |
| 401 | `BuddoAuthError` | `invalid_credentials` | No |
| 403 | `BuddoForbiddenError` | `app_not_approved`, `forbidden`, `insufficient_scope` | No |
| 404 | `BuddoNotFoundError` | `app_not_found`, `user_not_found`, `campaign_not_found`, `deployment_not_found`, `channel_not_found` | No |
| 409 | `BuddoConflictError` | `duplicate_idempotency_key`, `friendship_already_exists`, `app_name_taken`, `deployment_already_exists` | No |
| 422 | `BuddoValidationError` | `validation_failed`, `insufficient_balance`, `impression_token_replay`, `insufficient_deploy_balance`, `invalid_image_url`, `name_format_invalid`, `sandbox_unavailable` | No |
| 429 | `BuddoRateLimitError` | `rate_limit_exceeded` | Yes (auto-retried) |
| 500 | `BuddoServerError` | `internal_error` | No |
| 502/503/504 | `BuddoServerError` | — | Yes (auto-retried) |
| timeout | `BuddoTimeoutError` | `timeout` | Yes |
| connection | `BuddoConnectionError` | `connection_error` | Yes |

### Key Error Codes

| Code | HTTP | Meaning |
|------|------|---------|
| `invalid_credentials` | 401 | Wrong credentials or wrong token type (JWT used where OAuth token needed) |
| `insufficient_scope` | 403 | Token lacks required scope (check scope table in Section 4) |
| `app_not_found` | 404 | Unknown client_id |
| `deployment_not_found` | 404 | Deploy app ID not found |
| `impression_token_replay` | 422 | impression_token already used — get new from /ads/serve |
| `validation_failed` | 422 | Field validation errors — check `details` |
| `insufficient_balance` | 422 | User lacks enough points |
| `insufficient_deploy_balance` | 422 | Business lacks enough points/sats for tier |

### Exception Handling

```python
from buddo.exceptions import (
    BuddoAuthError,
    BuddoValidationError,
    BuddoRateLimitError,
    BuddoNotFoundError,
    BuddoForbiddenError,
)

try:
    event = await client.ads.record_ad_event(
        campaign_id=campaign_id,
        impression_token=token,
    )
except BuddoAuthError:
    # Token expired or wrong type — re-authenticate
    raise
except BuddoValidationError as e:
    if "impression_token_replay" in str(e):
        # Token already used — call serve_ad() again to get a fresh one
        pass
    raise
except BuddoForbiddenError as e:
    if "insufficient_scope" in str(e):
        # Re-authenticate with the correct scopes
        pass
    raise
except BuddoRateLimitError as e:
    # SDK auto-retried; wait before trying again
    await asyncio.sleep(e.retry_after)
    raise
```

---

## 15. Response Schemas

### UserBalance (`GET /api/external/points`)

```json
{"points": 1250}
```

**SDK model:** `UserBalance`
- `buddo_points` (int) — mapped from `"points"` field

### MeResponse (`GET /api/auth/me`)

```json
{
  "user": {
    "id": "uuid", "email": "...", "username": "alice",
    "tier": "Demon", "tier_emoji": "😈", "points": 1250,
    "referral_code": "ALICE42", "signup_multiplier": 1,
    "email_verified": true, "totp_enabled": false,
    "stats": {"direct_referrals": 3, "connected_apps": 2, "total_earned": 5000, "total_spent": 3750}
  }
}
```

> Note: response is wrapped in `{"user": {...}}`. The `user` object has `points` not a separate balance field.

### AdServeResponse (`GET /api/external/ads/serve`)

```json
{"campaign": {"id": "uuid", "payout_rate": 50}, "impression_token": "eyJ..."}
```

### AdEvent (`POST /api/external/ads/event`)

```json
{"event": {"id": "uuid", "campaign_id": "uuid", "event_type": "impression", "surface_type": "banner", "payout_rate_snapshot": 50, "inserted_at": "2026-06-16T10:30:00Z"}}
```

### OAuthTokenResponse (`POST /api/oauth/token`)

```json
{
  "access_token": "eyJ...", "token_type": "Bearer", "expires_in": 3600,
  "refresh_token": "eyJ...",
  "session_token": "eyJ...",  // only on authorization_code grants
  "session_token_expires_at": "2026-06-16T10:10:00Z"  // only on authorization_code grants
}
```

### TokenIntrospection (`POST /api/oauth/token/verify`)

```json
{"active": true, "user_id": "uuid", "app_id": "uuid", "scopes": ["profile:read", "points:read"], "expires_at": "2026-06-16T16:00:00Z"}
```

> Note: field names are `user_id` (not `sub`), `scopes` array (not `scope` string), `expires_at` (not `exp`).

### Deployment (`POST /api/deploy/apps`)

```json
{"id": "uuid", "app_id": "uuid", "deploy_tier_id": "uuid", "container_name": "my-app", "container_image": "docker.io/library/nginx:latest", "subdomain": "my-app.buddo.app", "status": "deploying", "memory_limit_mb": 256, "cpu_limit_millicores": 500, "inserted_at": "2026-06-16T12:00:00Z"}
```

### Error Response

```json
{"error": {"code": "impression_token_replay", "message": "This impression token has already been used.", "details": {}}}
```

---

## 16. Common Agent Workflows

### Workflow 1: Ad Serving Bot (Complete Flow)

```python
import asyncio, base64, hashlib, secrets, httpx

BASE = "https://api.buddo.xyz"

async def ad_serving_bot(email, password, client_id):
    verifier = secrets.token_urlsafe(43)
    challenge = base64.urlsafe_b64encode(
        hashlib.sha256(verifier.encode()).digest()
    ).rstrip(b"=").decode()

    async with httpx.AsyncClient(timeout=30) as http:
        # Authenticate
        r = await http.post(f"{BASE}/api/auth/login",
            json={"email": email, "password": password})
        jwt = r.json()["token"]

        r = await http.get(f"{BASE}/api/oauth/authorize", params={
            "client_id": client_id, "response_type": "code",
            "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
            "code_challenge": challenge, "code_challenge_method": "S256",
            "scope": "profile:read points:read",
        }, headers={"Authorization": f"Bearer {jwt}"})
        code = r.json()["code"]

        r = await http.post(f"{BASE}/api/oauth/token", json={
            "grant_type": "authorization_code", "code": code,
            "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
            "client_id": client_id, "code_verifier": verifier,
        })
        user_token = r.json()["access_token"]
        headers = {"Authorization": f"Bearer {user_token}"}

        # Check balance
        r = await http.get(f"{BASE}/api/external/points", headers=headers)
        print(f"Balance before: {r.json()['points']}")

        # Serve ad
        r = await http.get(f"{BASE}/api/external/ads/serve",
            params={"surface_type": "banner"}, headers=headers)
        d = r.json()
        campaign_id, impression_token = d["campaign"]["id"], d["impression_token"]

        # Record impression
        r = await http.post(f"{BASE}/api/external/ads/event", headers=headers,
            json={"campaign_id": campaign_id, "event_type": "impression",
                  "impression_token": impression_token, "surface_type": "banner"})
        print(f"Event recorded: {r.status_code}")

        # Verify balance
        r = await http.get(f"{BASE}/api/external/points", headers=headers)
        print(f"Balance after: {r.json()['points']}")

asyncio.run(ad_serving_bot("user@example.com", "password", "YOUR_CLIENT_ID"))
```

### Workflow 2: Deploy Application

```python
async def deploy_app(business_token: str, name: str, image: str):
    async with httpx.AsyncClient(timeout=30) as http:
        headers = {"Authorization": f"Bearer {business_token}"}

        # Check tiers first
        r = await http.get(f"{BASE}/api/deploy/tiers", headers=headers)
        tiers = r.json()
        tier_id = tiers[0]["id"]  # pick first available tier

        # Deploy
        r = await http.post(f"{BASE}/api/deploy/apps", headers=headers,
            json={"name": name, "image": image, "port": 3000, "tier_id": tier_id})
        app = r.json()
        app_id = app["id"]
        print(f"Deploying {app_id}")

        # Poll until running
        while True:
            r = await http.get(f"{BASE}/api/deploy/apps/{app_id}/status", headers=headers)
            status = r.json()["status"]
            if status == "running":
                print(f"Running at {app['subdomain']}.buddo.app")
                break
            elif status == "destroyed":
                raise RuntimeError("Deployment failed")
            await asyncio.sleep(5)
```

### Workflow 3: Business Health Check

```python
async def business_health_check(business_token: str):
    async with httpx.AsyncClient(timeout=30) as http:
        headers = {"Authorization": f"Bearer {business_token}"}

        # Analytics
        r = await http.get(f"{BASE}/api/operator/analytics", headers=headers)
        analytics = r.json()
        print(f"Total earnings: {analytics['earnings']['total']}")

        # Active campaigns
        r = await http.get(f"{BASE}/api/v1/ads/campaigns",
            params={"status": "active"}, headers=headers)
        campaigns = r.json()
        print(f"Active campaigns: {len(campaigns)}")

        for campaign in campaigns[:3]:
            r = await http.get(
                f"{BASE}/api/v1/ads/analytics/campaign/{campaign['id']}",
                headers=headers)
            print(f"Campaign {campaign.get('name', campaign['id'])}: {r.json()}")
```

---

## 17. Troubleshooting / Common Failure Modes

### 1. HTTP 401 `invalid_credentials`

**Cause:** Wrong token type. `/api/external/*` endpoints require an OAuth access token, NOT a JWT login token.

**Fix:**
- JWT from `POST /api/auth/login` → use only for `GET /api/oauth/authorize` Bearer header
- OAuth access token from `POST /api/oauth/token` → use for all API calls

### 2. HTTP 403 `insufficient_scope`

**Cause:** OAuth token doesn't have the required scope.

**Fix:** Re-authenticate requesting the missing scope. Check Section 4 scope table.
- Deploy endpoints need `deploy:manage`
- Create app (`POST /api/oauth/apps`) requires only a JWT from login — no OAuth scope needed

```bash
curl -X POST https://api.buddo.xyz/api/oauth/token/verify \
  -H "Content-Type: application/json" \
  -d '{"token": "YOUR_ACCESS_TOKEN"}'
# → {"active": true, "scopes": ["profile:read"], ...}
```

### 3. HTTP 422 `impression_token_replay`

**Cause:** `impression_token` already used. This is **HTTP 422** (not 409).

**Fix:** Call `GET /api/external/ads/serve` again for a fresh token.

```python
# WRONG — reusing same token
serve = await serve_ad()
await record_event(serve.impression_token)
await record_event(serve.impression_token)  # 422!

# RIGHT — fresh token per impression
serve1 = await serve_ad()
await record_event(serve1.impression_token)
serve2 = await serve_ad()
await record_event(serve2.impression_token)
```

### 4. HTTP 422 `insufficient_deploy_balance`

**Cause:** Business account lacks enough Buddo points or Bitcoin to cover the deployment tier cost.

**Fix:** Check business billing or add funds before deploying.

### 5. Deploy image rejected (422 `invalid_image_url`)

**Cause:** Image URL doesn't start with an allowed registry.

**Fix:** Only these registries are allowed:
- `harbor.buddo.xyz:4443/` (Buddo private registry)
- `docker.io/library/` (Docker Hub official images)
- `ghcr.io/` (GitHub Container Registry)

### 6. Attempting to Award Points Directly

`POST /api/points/award` does NOT exist. Points credit automatically when `POST /api/external/ads/event` is accepted.

### 7. Wrong Base URL

Use `https://api.buddo.xyz` not `https://buddo.xyz`.

### 8. HTTP 429 Rate Limit

SDK handles automatically with 3 retries. If `BuddoRateLimitError` raised, wait `e.retry_after` seconds.

### 9. Token Introspection Field Mismatch

Live introspection response uses `user_id` (not `sub`), `scopes` array (not `scope` string), `expires_at` (not `exp`). If parsing introspection responses, use these field names.

### 10. OAuth App Creation Field Names

`POST /api/oauth/apps` uses camelCase: `name`, `redirectUris`, `scopes` — not `app_name`, `redirect_uris`, `allowed_scopes`.

### 11. BuddoClient Not Opened Error

```python
# WRONG
client = BuddoClient(client_id="...", client_secret="...")
balance = await client.users.get_balance()  # BuddoError: transport not initialized

# RIGHT
async with BuddoClient(client_id="...", client_secret="...") as client:
    balance = await client.users.get_balance()
```

---

## Appendix: Full Endpoint Index (91 paths from OpenAPI)

Generated from the live OpenAPI spec v4.0.0 (107 operations) at every image build. Auth labels: `jwt` = Bearer JWT from `/api/auth/login`; `oauth` / `oauth:scope+scope` = OAuth 2.0 PKCE access token (required scopes after the colon); `internal` = platform-internal, not for businesses; `public` = no Authorization header.

```
### ADS (3)
POST   /api/external/ads/event  [oauth:profile:read]  Record an ad impression or click event
GET    /api/external/ads/serve  [oauth:profile:read]  Serve an ad campaign for a given surface type
GET    /api/external/ads/serve/v2  [oauth:profile:read]  Serve an ad with placement-aware targeting (v2)

### ADS-MARKETPLACE (17)
GET    /api/v1/ads/analytics/campaign/{id}  [jwt]  Campaign analytics
GET    /api/v1/ads/analytics/overview  [jwt]  Analytics overview
GET    /api/v1/ads/analytics/placement/{id}  [jwt]  Placement analytics
GET    /api/v1/ads/campaigns  [jwt]  List ad campaigns
POST   /api/v1/ads/campaigns  [jwt]  Create a campaign
GET    /api/v1/ads/campaigns/{id}  [jwt]  Get a campaign
PUT    /api/v1/ads/campaigns/{id}  [jwt]  Update a campaign
DELETE /api/v1/ads/campaigns/{id}  [jwt]  Delete a campaign
POST   /api/v1/ads/campaigns/{id}/pause  [jwt]  Pause a campaign
POST   /api/v1/ads/campaigns/{id}/resume  [jwt]  Resume a campaign
GET    /api/v1/ads/campaigns/{id}/targeting  [jwt]  Get campaign targeting
POST   /api/v1/ads/campaigns/{id}/targeting  [jwt]  Set campaign targeting
POST   /api/v1/ads/pricing/bulk-quote  [jwt]  Get bulk pricing quote
GET    /api/v1/ads/pricing/rates  [jwt]  List pricing rates
GET    /api/v1/ads/pricing/rates/{placement_id}  [jwt]  Get rate for surface type
POST   /api/v1/ads/purchases/bulk  [jwt]  Execute bulk purchase
GET    /api/v1/ads/segments  [jwt]  List audience segments

### APP (1)
GET    /api/external/app/balance  [oauth:app:balance:read]  Get the business app's earned-point balance

### AUTH (11)
POST   /api/auth/forgot-password  [public]  Request a password reset link
POST   /api/auth/login  [public]  Authenticate and receive a JWT token
GET    /api/auth/me  [jwt]  Get the authenticated user's full profile
POST   /api/auth/register  [public]  Register a new user account
POST   /api/auth/reset-password  [public]  Reset password using a reset token
POST   /api/auth/self-verify-email  [oauth:profile:read]  Self-verify email for authenticated user (no OTP required)
POST   /api/auth/send-verification  [jwt]  Resend the email verification link
POST   /api/auth/totp/enable  [jwt]  Enable TOTP by confirming a valid code
POST   /api/auth/totp/setup  [jwt]  Generate a TOTP secret and provisioning URI
POST   /api/auth/totp/verify  [jwt]  Verify a TOTP or recovery code
POST   /api/auth/verify-email  [public]  Verify a user's email address with a token

### BUSINESS (4)
GET    /api/operator/analytics  [oauth:app:balance:read]  Get business analytics
GET    /api/operator/app  [oauth:app:balance:read]  Get business's app details
PUT    /api/operator/app  [oauth:app:balance:read]  Update business's app
GET    /api/operator/billing/history  [oauth:app:balance:read]  Get paginated billing history for the business app account

### BUSINESS-REGISTRATION (3)
POST   /api/operators/register  [public]  Register a new business account (business self-service)
POST   /api/operators/resend-verification  [public]  Resend email verification link
GET    /api/operators/verify/{token}  [public]  Verify business email and receive OAuth credentials

### DEPLOY (10)
GET    /api/deploy/apps  [oauth:deploy:manage]  List business's deployments
POST   /api/deploy/apps  [oauth:deploy:manage]  Create a new deployment
GET    /api/deploy/apps/{id}  [oauth:deploy:manage]  Get a single deployment
DELETE /api/deploy/apps/{id}  [oauth:deploy:manage]  Destroy a deployment
GET    /api/deploy/apps/{id}/logs  [oauth:deploy:manage]  Get deployment action logs
POST   /api/deploy/apps/{id}/restart  [oauth:deploy:manage]  Restart a deployment
GET    /api/deploy/apps/{id}/status  [oauth:deploy:manage]  Lightweight deployment status check
POST   /api/deploy/apps/{id}/stop  [oauth:deploy:manage]  Stop a running deployment
GET    /api/deploy/sandbox-status  [jwt]  Check sandbox deployment eligibility
GET    /api/deploy/tiers  [oauth:deploy:manage]  List available deployment tiers

### DISCOVERY (3)
GET    /.well-known/oauth-protected-resource  [public]  OAuth 2.0 Protected Resource discovery (RFC 9728)
GET    /.well-known/openapi.json  [public]  This OpenAPI specification document
GET    /llms.txt  [public]  LLM agent discovery file - describes the API for AI agents

### EDUCATION (5)
GET    /api/btc-progress/available-modules  [jwt]  List available modules
POST   /api/btc-progress/learning-path  [jwt]  Set learning path
POST   /api/btc-progress/module/{module_number}/reset  [jwt]  Reset a completed module
GET    /api/btc-progress/module/{module_number}/status  [jwt]  Get module progress
POST   /api/btc-progress/{step_id}/complete  [jwt]  Complete a learning step

### EXTERNAL-CAMPAIGNS (7)
GET    /api/external/campaigns  [jwt]  List business campaigns
POST   /api/external/campaigns  [jwt]  Create a business campaign
GET    /api/external/campaigns/{id}  [jwt]  Get a campaign
PUT    /api/external/campaigns/{id}  [jwt]  Update a campaign
DELETE /api/external/campaigns/{id}  [jwt]  Cancel a campaign
POST   /api/external/campaigns/{id}/pause  [oauth:campaigns:manage]  Pause an active campaign
POST   /api/external/campaigns/{id}/resume  [oauth:campaigns:manage]  Resume a paused campaign

### INFRASTRUCTURE (1)
GET    /health  [public]  Health check

### OAUTH (8)
POST   /api/oauth/apps  [jwt]  Register a new OAuth app
GET    /api/oauth/apps/{client_id}  [public]  Get public app metadata by client_id
GET    /api/oauth/authorize  [jwt]  Request an authorization code
GET    /api/oauth/my-apps  [jwt]  List OAuth apps owned by the authenticated user
PUT    /api/oauth/my-apps/{id}  [jwt]  Update an OAuth app owned by the authenticated user
POST   /api/oauth/my-apps/{id}/scope-request  [jwt]  Request additional scopes for an owned app
POST   /api/oauth/token  [public]  Exchange an authorization code or refresh token for access tokens
POST   /api/oauth/token/verify  [public]  Introspect an access token

### POINTS (3)
GET    /api/external/points  [oauth:points:read]  Get user point balance
POST   /api/external/points/spend  [oauth:points:spend]  Spend user points, crediting the business account
POST   /api/external/points/transfer  [oauth:points:transfer]  Transfer points from the authenticated user to another user

### PUBLIC (1)
GET    /api/public/operators  [public]  List approved public businesses

### SESSIONS (3)
POST   /api/external/session/end  [oauth:profile:read]  End the user's active session with this app
GET    /api/external/session/status  [oauth:profile:read]  Check whether the user has an active session with this app
POST   /api/session/refresh  [public]  Refresh a session token

### SOCIAL (24)
GET    /api/social/avatar  [jwt]  Get the current user's avatar
PUT    /api/social/avatar  [jwt]  Update avatar appearance or display name
PUT    /api/social/avatar/equip  [jwt]  Equip or unequip a cosmetic item
GET    /api/social/avatar/{user_id}  [jwt]  Get a user's public avatar
POST   /api/social/block  [jwt]  Block a user
DELETE /api/social/block/{user_id}  [jwt]  Unblock a user
POST   /api/social/chat/channels  [jwt]  Create or ensure a chat channel
GET    /api/social/chat/{channel_id}/messages  [jwt]  Get messages from a chat channel
POST   /api/social/chat/{channel_id}/messages  [jwt]  Send a message to a chat channel
GET    /api/social/cosmetics  [public]  Browse the cosmetic catalogue
GET    /api/social/cosmetics/inventory  [jwt]  Get the current user's cosmetic inventory
POST   /api/social/cosmetics/{id}/purchase  [jwt]  Purchase a cosmetic item
GET    /api/social/friends  [jwt]  List current user's friends
POST   /api/social/friends  [jwt]  Send a friend request
GET    /api/social/friends/pending  [jwt]  List pending friend requests to the current user
PUT    /api/social/friends/{id}  [jwt]  Accept or reject a friend request
DELETE /api/social/friends/{id}  [jwt]  Remove a friendship
GET    /api/social/presence  [jwt]  Get friends' online presence
POST   /api/social/presence  [jwt]  Track user presence
DELETE /api/social/presence  [jwt]  Untrack user presence
GET    /api/social/presence/friends  [jwt]  Get online friends (heartbeat presence)
POST   /api/social/presence/heartbeat  [jwt]  Send presence heartbeat
GET    /api/social/presence/table  [jwt]  Get presence for a game table
GET    /api/social/users/search  [jwt]  Search users by username

### USER (3)
GET    /api/external/user  [oauth:profile:read]  Get authenticated user profile
GET    /api/user/connected-apps  [jwt]  List user's connected OAuth apps
DELETE /api/user/connected-apps/{app_id}  [jwt]  Revoke an OAuth app authorization
```

---

## Appendix: Corrections vs. Pre-S234 Documentation

| Field | Old (Wrong) | New (Correct) |
|-------|-------------|----------------|
| Base URL | `https://buddo.xyz` | `https://api.buddo.xyz` |
| Auth method | Static API key `bdk_live_*` | OAuth 2.0 PKCE only |
| Balance endpoint | `GET /api/users/me/balance` | `GET /api/external/points` |
| Impression endpoint | `POST /api/ads/impressions` | 2-step: serve → event |
| Replay error code | 409 | **422** `impression_token_replay` |
| Award points | `POST /api/points/award` | Does not exist — treasury auto-credits |
| Campaign list path | `GET /api/ads/campaigns` | `GET /api/v1/ads/campaigns` |
| User profile path | `GET /api/users/me` | `GET /api/auth/me` |
| OAuth app creation field | `app_name`, `redirect_uris`, `allowed_scopes` | `name`, `redirectUris`, `scopes` |
| Token introspection `sub` | `sub` | `user_id` |
| Token introspection `scope` | `scope` (string) | `scopes` (array) |
| Token introspection `exp` | `exp` (unix timestamp) | `expires_at` (ISO datetime) |
| Scope table | Missing `deploy:manage`, `operator:write` | Added — see Section 4 |
| Scope `operator:read` | Listed in scope table as valid | **PHANTOM** — not in backend @valid_scopes; use `analytics:read` + `app:balance:read` |
| Scope `operator:write` | Listed in scope table as valid | **PHANTOM** — not in backend @valid_scopes; `POST /api/oauth/apps` needs only a JWT |

---

## Appendix: Environment Overrides

```python
# Default production
client = BuddoClient(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET")

# Local development
client = BuddoClient(
    client_id="test_client",
    client_secret="test_secret",
    base_url="http://localhost:4000",
)

# Custom timeout / retries
client = BuddoClient(
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    timeout=60.0,
    max_retries=5,
    retry_backoff=1.5,
)
```
