> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chromaflow.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

> Comprehensive guide to ChromaFlow's real-time APIs—endpoints for streaming chat, integrations, payments, and utilities with examples, auth, and error handling.

# Real-Time Enterprise API Reference

ChromaFlow's APIs power real-time AI development at enterprise scale. All endpoints use JSON payloads, Bearer token auth (via Auth0), and follow REST conventions with SSE/WebSocket for streaming. Base URL: `https://app.chromaflow.ai`.

<div class="doc-cards">
  <div class="doc-card">
    <span class="doc-badge">Streaming</span>
    <h3>Real-Time Chat</h3>
    <p>Low-latency AI interactions with progressive responses and agent orchestration.</p>
  </div>

  <div class="doc-card">
    <span class="doc-badge">Secure</span>
    <h3>Enterprise Integrations</h3>
    <p>OAuth flows, data sync, and webhooks for GitHub, Supabase, Stripe.</p>
  </div>

  <div class="doc-card">
    <span class="doc-badge">Scalable</span>
    <h3>Utilities & Publishing</h3>
    <p>Edge-optimized tools for deployment, search, and monitoring.</p>
  </div>
</div>

## Authentication & Headers

All requests require:

```
Authorization: Bearer <auth0_token>
Content-Type: application/json
X-Client-ID: <your_client_id> (for metering)
```

* **Token Acquisition**: Use `/auth/login` or Auth0 SDK.
* **Scopes**: `chat:write`, `integrations:read`, `billing:manage` (RBAC enforced).
* **Rate Limits**: 100 req/min (chat), 50 req/min (integrations); burst to 500. Exceeding returns 429 with `Retry-After`.
* **Error Format**:
  ```json
  {
    "error": "Invalid scope",
    "code": "AUTH_001",
    "details": "Required: chat:write",
    "timestamp": "2025-09-28T12:00:00Z"
  }
  ```

## Real-Time Chat & Agents

### POST `/api/chat` – Streaming Conversation

Initiate real-time chat with Claude models. Supports tool-calling and search augmentation.

**Auth**: `chat:write`

**Request**:

```json
{
  "messages": [{ "role": "user", "content": "Build a real-time dashboard" }],
  "model": "claude-3-5-sonnet-20240620",
  "stream": true,
  "temperature": 0.7,
  "max_tokens": 4096,
  "tools": ["search", "code_execution"]
}
```

**Response**: `text/event-stream`

```
data: {"type": "delta", "content": "Here's a real-time dashboard using React..."}

data: {"type": "tool_call", "name": "search", "args": {"query": "latest React hooks"}}

data: {"type": "done", "usage": {"input": 150, "output": 800}}
```

**Notes**:

* Auto-triggers Perplexity if confidence \< 0.8.
* Special commands: `!search`, `!image`, parsed server-side.
* Scalability: Edge-cached prompts; Durable Objects for session state.

### POST `/api/enhanced-chat` – Advanced Orchestration

Enhanced with step-by-step reasoning and auto-debug.

**Request**:

```json
{
  "messages": [...],
  "enhance": true,
  "debug": true,
  "context": {"project_id": "proj_123"}
}
```

**Response**: SSE with reasoning traces.

### GET `/ws/agent` – WebSocket Agent Control

Persistent connection for real-time agent management.

**Upgrade Headers**:

```
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: <key>
```

**Messages**:

* Client → Server: `{"type": "agent_command", "command": "debug", "params": {...}}`
* Server → Client: `{"type": "progress", "status": "running", "eta": "2s"}`

**Notes**: Handles up to 10k concurrent connections via Durable Objects. Ping/pong every 30s.

## Integrations APIs

### POST `/api/integrations/:provider/auth` – OAuth Initiation

Start secure integration flow (GitHub, Supabase, etc.).

**Path Params**: `provider` (e.g., "github")

**Request**:

```json
{
  "redirect_uri": "https://app.chromaflow.ai/callback",
  "scopes": ["repo", "user:email"]
}
```

**Response**:

```json
{
  "auth_url": "https://github.com/login/oauth/authorize?...",
  "state": "csrf_token_abc123",
  "expires_in": 600
}
```

**Error Handling**: 401 if scopes invalid; retries with exponential backoff.

### GET `/api/integrations/:provider/status` – Connection Check

Verify integration status and metadata.

**Response**:

```json
{
  "connected": true,
  "provider": "github",
  "user": { "username": "devteam", "repos": 42 },
  "last_sync": "2025-09-28T10:00:00Z",
  "permissions": ["repo:write"]
}
```

### POST `/api/github/import` – Repo Import

Real-time repository cloning and analysis.

**Request**:

```json
{
  "repo_url": "https://github.com/user/my-app",
  "branch": "main",
  "analyze": true
}
```

**Response**: SSE stream of import progress (cloning, parsing, AI summary).

| Provider | Supported Scopes     | Sync Frequency     | Enterprise Features               |
| -------- | -------------------- | ------------------ | --------------------------------- |
| GitHub   | repo, user, workflow | Real-time webhooks | Branch protection, CI integration |
| Supabase | project:manage       | On-demand          | RLS policies, edge functions      |
| Stripe   | billing:read\_write  | Event-driven       | Subscription metering, invoices   |

## Payments & Billing

### POST `/api/stripe/create-checkout` – Session Creation

Generate secure checkout for plans.

**Request**:

```json
{
  "price_id": "price_pro_monthly",
  "success_url": "https://app.chromaflow.ai/success",
  "cancel_url": "https://app.chromaflow.ai/cancel",
  "metadata": { "user_id": "user_123" }
}
```

**Response**:

```json
{
  "url": "https://checkout.stripe.com/...",
  "session_id": "cs_abc123",
  "expires_at": 1696000000
}
```

**Webhook**: POST `/api/stripe/webhook` – Verify with `STRIPE_WEBHOOK_SECRET`; handles subscription events.

### GET `/api/stripe/billing-portal` – Customer Portal

Redirect to Stripe portal for management.

**Security**: SCA compliant; audit logs in Supabase.

## Utilities & Publishing

### POST `/api/perplexity-search` – Intelligent Search

Enterprise-grade web search with caching.

**Request**:

```json
{
  "query": "enterprise real-time architectures",
  "max_results": 10,
  "depth": "advanced"
}
```

**Response**:

```json
{
  "success": true,
  "results": [...],
  "answer": "Summary based on top sources...",
  "metadata": {"cached": false, "duration_ms": 150}
}
```

### POST `/api/publish-github-pages` – Instant Deployment

Deploy generated site to GitHub Pages.

**Request**:

```json
{
  "repo_name": "my-site",
  "files": { "index.html": "<html>...</html>" },
  "branch": "gh-pages"
}
```

**Response**: SSE with deploy progress; returns live URL on completion.

### POST `/api/search` – Internal Codebase Search

Semantic search across imported repos.

**Rate Limits**: 200/min; enterprise tiers allow unlimited.

## Error Codes & Best Practices

| Code | Description         | Resolution                                     |
| ---- | ------------------- | ---------------------------------------------- |
| 429  | Rate Limited        | Implement exponential backoff; upgrade plan    |
| 401  | Unauthorized        | Refresh token; check scopes                    |
| 503  | Service Unavailable | Retry with jitter; check status.chromaflow\.ai |

**Best Practices**:

* Use connection pooling for high-volume integrations.
* Monitor via `/api/usage` endpoint (enterprise only).
* Implement client-side caching for search results (TTL: 5min).
* For real-time: Handle SSE reconnections gracefully; use WebSocket heartbeats.

This API suite scales to 1M+ users with Cloudflare's edge network. For custom endpoints, contact [enterprise@chromaflow.ai](mailto:enterprise@chromaflow.ai).
