# ComfyUI API Endpoints Documentation

## Overview

This document covers the ComfyUI generation API endpoints exposed through the
Lilith BFF service. These endpoints wrap the RunComfy API with additional
features like authentication, rate limiting, and platform integration.

## Base URL

```
Production: https://api.lilith.ai/v1
Staging:    https://api.staging.lilith.ai/v1
Development: http://localhost:8080/v1
```

## Authentication

All endpoints require a valid JWT token:

```http
Authorization: Bearer <jwt_token>
```

## Endpoints

### Generate Image

Queue a new image generation job.

```http
POST /comfyui/generate
Content-Type: application/json
Authorization: Bearer <token>
```

**Request Body:**

```json
{
  "deploymentId": "sacred-mandala-v1",
  "prompt": "sacred mandala, golden, intricate patterns, tibetan buddhist style",
  "negativePrompt": "blurry, low quality, distorted",
  "seed": 12345,
  "steps": 30,
  "cfg": 7.5,
  "width": 1024,
  "height": 1024,
  "sampler": "euler_ancestral",
  "scheduler": "normal",
  "batchSize": 1,
  "priority": "normal",
  "webhook": "https://your-api.com/webhook",
  "metadata": {
    "userId": "user-123",
    "sessionId": "session-456"
  }
}
```

**Request Parameters:**

| Parameter      | Type    | Required | Default  | Description                              |
| -------------- | ------- | -------- | -------- | ---------------------------------------- |
| deploymentId   | string  | Yes      | -        | Target deployment ID                     |
| prompt         | string  | Yes      | -        | Generation prompt                        |
| negativePrompt | string  | No       | ""       | Negative prompt                          |
| seed           | integer | No       | random   | Random seed (0-2147483647)               |
| steps          | integer | No       | 30       | Sampling steps (10-150)                  |
| cfg            | number  | No       | 7.5      | CFG scale (1.0-30.0)                     |
| width          | integer | No       | 1024     | Image width (512-2048, step 64)          |
| height         | integer | No       | 1024     | Image height (512-2048, step 64)         |
| sampler        | string  | No       | "euler"  | Sampler name                             |
| scheduler      | string  | No       | "normal" | Scheduler name                           |
| batchSize      | integer | No       | 1        | Number of images (1-8)                   |
| priority       | string  | No       | "normal" | Job priority (low, normal, high, urgent) |
| webhook        | string  | No       | -        | Webhook URL for completion               |
| metadata       | object  | No       | {}       | Custom metadata                          |

**Response (202 Accepted):**

```json
{
  "jobId": "job-abc123def456",
  "status": "QUEUED",
  "queuePosition": 3,
  "estimatedWaitSeconds": 45,
  "deploymentId": "sacred-mandala-v1",
  "createdAt": "2024-12-18T12:00:00Z"
}
```

**Error Responses:**

| Status | Code                 | Description              |
| ------ | -------------------- | ------------------------ |
| 400    | INVALID_REQUEST      | Invalid parameters       |
| 401    | UNAUTHORIZED         | Invalid or missing token |
| 403    | FORBIDDEN            | Insufficient permissions |
| 404    | DEPLOYMENT_NOT_FOUND | Unknown deployment       |
| 429    | RATE_LIMITED         | Too many requests        |
| 503    | SERVICE_UNAVAILABLE  | Service down             |

---

### Get Job Status

Check the status of a generation job.

```http
GET /comfyui/jobs/{jobId}/status
Authorization: Bearer <token>
```

**Response (200 OK):**

```json
{
  "jobId": "job-abc123def456",
  "status": "PROCESSING",
  "progress": 65,
  "currentNode": {
    "id": "3",
    "class": "KSampler",
    "progress": 65
  },
  "queuePosition": null,
  "estimatedTimeSeconds": 15
}
```

**Status Values:**

| Status     | Description           |
| ---------- | --------------------- |
| QUEUED     | Waiting in queue      |
| PROCESSING | Currently generating  |
| COMPLETED  | Successfully finished |
| FAILED     | Generation failed     |
| CANCELLED  | Cancelled by user     |

---

### Get Job Result

Retrieve the result of a completed job.

```http
GET /comfyui/jobs/{jobId}
Authorization: Bearer <token>
```

**Response (200 OK - Completed):**

```json
{
  "jobId": "job-abc123def456",
  "status": "COMPLETED",
  "deploymentId": "sacred-mandala-v1",
  "queuedAt": "2024-12-18T12:00:00Z",
  "startedAt": "2024-12-18T12:00:05Z",
  "completedAt": "2024-12-18T12:00:35Z",
  "processingTimeMs": 30000,
  "outputs": [
    {
      "type": "image",
      "url": "https://cdn.lilith.ai/outputs/abc123/image_0.png",
      "thumbnailUrl": "https://cdn.lilith.ai/outputs/abc123/image_0_thumb.png",
      "mimeType": "image/png",
      "sizeBytes": 2456789,
      "filename": "sacred_mandala_001.png",
      "nodeId": "9",
      "outputIndex": 0,
      "metadata": {
        "width": 1024,
        "height": 1024,
        "seed": 12345
      }
    }
  ],
  "metadata": {
    "userId": "user-123",
    "sessionId": "session-456"
  }
}
```

**Response (200 OK - Failed):**

```json
{
  "jobId": "job-abc123def456",
  "status": "FAILED",
  "deploymentId": "sacred-mandala-v1",
  "queuedAt": "2024-12-18T12:00:00Z",
  "startedAt": "2024-12-18T12:00:05Z",
  "completedAt": "2024-12-18T12:00:10Z",
  "error": {
    "code": "NODE_ERROR",
    "message": "KSampler node failed: Invalid seed value",
    "nodeId": "3",
    "details": {
      "nodeClass": "KSampler",
      "inputName": "seed",
      "providedValue": -5
    }
  }
}
```

---

### Cancel Job

Cancel a queued or processing job.

```http
POST /comfyui/jobs/{jobId}/cancel
Authorization: Bearer <token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "message": "Job cancelled successfully",
  "jobId": "job-abc123def456",
  "previousStatus": "QUEUED"
}
```

**Response (400 Bad Request):**

```json
{
  "success": false,
  "message": "Cannot cancel completed job",
  "jobId": "job-abc123def456",
  "currentStatus": "COMPLETED"
}
```

---

### List Deployments

Get available deployments for the current user.

```http
GET /comfyui/deployments
Authorization: Bearer <token>
```

**Query Parameters:**

| Parameter | Type    | Description             |
| --------- | ------- | ----------------------- |
| category  | string  | Filter by category      |
| active    | boolean | Filter by active status |
| tier      | string  | Filter by required tier |

**Response (200 OK):**

```json
{
  "deployments": [
    {
      "deploymentId": "sacred-mandala-v1",
      "name": "Sacred Mandala Generator",
      "description": "Generate sacred mandala patterns",
      "category": "sacred_art",
      "version": "1.0.0",
      "gpuType": "A5000",
      "estimatedProcessingTime": 45,
      "costPerRun": 5,
      "active": true,
      "requiredTier": "basic",
      "tags": ["mandala", "sacred-geometry"]
    },
    {
      "deploymentId": "fractal-mandelbrot-v1",
      "name": "Fractal Mandelbrot Generator",
      "description": "High-resolution fractal art",
      "category": "fractal",
      "version": "1.0.0",
      "gpuType": "A6000",
      "estimatedProcessingTime": 120,
      "costPerRun": 10,
      "active": true,
      "requiredTier": "premium",
      "tags": ["fractal", "mandelbrot", "math-art"]
    }
  ],
  "total": 2
}
```

---

### Get Deployment Details

Get detailed information about a specific deployment.

```http
GET /comfyui/deployments/{deploymentId}
Authorization: Bearer <token>
```

**Response (200 OK):**

```json
{
  "deploymentId": "sacred-mandala-v1",
  "name": "Sacred Mandala Generator",
  "description": "Generate sacred mandala patterns with configurable symmetry and colors",
  "category": "sacred_art",
  "version": "1.0.0",
  "gpuType": "A5000",
  "estimatedProcessingTime": 45,
  "maxTimeout": 120,
  "costPerRun": 5,
  "active": true,
  "inputs": [
    {
      "name": "prompt",
      "nodeId": "6",
      "type": "string",
      "required": true,
      "description": "Generation prompt"
    },
    {
      "name": "seed",
      "nodeId": "3",
      "type": "seed",
      "required": false,
      "default": -1,
      "description": "Random seed"
    },
    {
      "name": "width",
      "nodeId": "5",
      "type": "integer",
      "required": false,
      "default": 1024,
      "validation": {
        "min": 512,
        "max": 2048,
        "step": 64
      }
    }
  ],
  "outputs": [
    {
      "name": "image",
      "type": "image",
      "mimeType": "image/png",
      "description": "Generated mandala image"
    }
  ],
  "tags": ["mandala", "sacred-geometry", "spiritual"],
  "requiredTier": "basic",
  "promptTemplateId": "sacred-mandala"
}
```

---

### Get Deployment Status

Get real-time health and queue status.

```http
GET /comfyui/deployments/{deploymentId}/status
Authorization: Bearer <token>
```

**Response (200 OK):**

```json
{
  "deploymentId": "sacred-mandala-v1",
  "healthy": true,
  "active": true,
  "currentJobs": 3,
  "queuedJobs": 12,
  "avgProcessingTimeMs": 42500,
  "successRate": 0.985,
  "gpuUtilization": 75,
  "lastHealthCheck": "2024-12-18T12:00:00Z"
}
```

---

### Apply Prompt Template

Generate prompt from template.

```http
POST /comfyui/templates/{templateId}/apply
Authorization: Bearer <token>
Content-Type: application/json
```

**Request Body:**

```json
{
  "variables": {
    "style": "visionary art",
    "colors": "vibrant rainbow"
  }
}
```

**Response (200 OK):**

```json
{
  "templateId": "sacred-mandala",
  "prompt": "sacred mandala, visionary art style, vibrant rainbow, intricate geometric patterns, spiritual symbolism, meditation art, high detail, centered composition, ethereal glow",
  "negativePrompt": "blurry, low quality, distorted, asymmetric, ugly, deformed",
  "availableVariables": ["style", "colors"],
  "usedDefaults": {}
}
```

---

### List Prompt Templates

Get available prompt templates.

```http
GET /comfyui/templates
Authorization: Bearer <token>
```

**Response (200 OK):**

```json
{
  "templates": [
    {
      "id": "sacred-mandala",
      "name": "Sacred Mandala",
      "description": "Generate sacred mandala artwork",
      "variables": ["style", "colors"],
      "defaults": {
        "style": "tibetan buddhist",
        "colors": "gold and deep blue"
      },
      "category": "sacred_art"
    },
    {
      "id": "consciousness-map",
      "name": "Consciousness Map",
      "description": "Visualize consciousness concepts",
      "variables": ["concept", "colors", "atmosphere"],
      "defaults": {
        "concept": "unified field",
        "colors": "deep purple and electric blue",
        "atmosphere": "mystical ethereal"
      },
      "category": "consciousness"
    }
  ]
}
```

---

### Get User Generation History

Get user's generation history.

```http
GET /comfyui/history
Authorization: Bearer <token>
```

**Query Parameters:**

| Parameter    | Type    | Default | Description                 |
| ------------ | ------- | ------- | --------------------------- |
| limit        | integer | 20      | Results per page (max 100)  |
| offset       | integer | 0       | Pagination offset           |
| status       | string  | all     | Filter by status            |
| deploymentId | string  | -       | Filter by deployment        |
| startDate    | string  | -       | Filter from date (ISO 8601) |
| endDate      | string  | -       | Filter to date (ISO 8601)   |

**Response (200 OK):**

```json
{
  "jobs": [
    {
      "jobId": "job-abc123",
      "deploymentId": "sacred-mandala-v1",
      "status": "COMPLETED",
      "prompt": "sacred mandala, golden...",
      "thumbnailUrl": "https://cdn.lilith.ai/...",
      "createdAt": "2024-12-18T12:00:00Z",
      "processingTimeMs": 42000,
      "cost": 5
    }
  ],
  "total": 150,
  "limit": 20,
  "offset": 0
}
```

---

### Get Usage Statistics

Get user's usage statistics.

```http
GET /comfyui/stats
Authorization: Bearer <token>
```

**Query Parameters:**

| Parameter | Type   | Default | Description                          |
| --------- | ------ | ------- | ------------------------------------ |
| period    | string | month   | Time period (day, week, month, year) |

**Response (200 OK):**

```json
{
  "period": "month",
  "startDate": "2024-12-01T00:00:00Z",
  "endDate": "2024-12-31T23:59:59Z",
  "totalJobs": 150,
  "completedJobs": 145,
  "failedJobs": 5,
  "successRate": 0.967,
  "totalCreditsUsed": 750,
  "avgProcessingTimeMs": 38500,
  "byDeployment": {
    "sacred-mandala-v1": {
      "jobs": 80,
      "credits": 400
    },
    "fractal-mandelbrot-v1": {
      "jobs": 35,
      "credits": 350
    }
  },
  "byDay": [
    { "date": "2024-12-01", "jobs": 5, "credits": 25 },
    { "date": "2024-12-02", "jobs": 8, "credits": 40 }
  ]
}
```

## Error Codes

| Code                 | HTTP Status | Description                     |
| -------------------- | ----------- | ------------------------------- |
| INVALID_REQUEST      | 400         | Request validation failed       |
| INVALID_DEPLOYMENT   | 400         | Invalid deployment ID or config |
| INVALID_OVERRIDES    | 400         | Invalid workflow overrides      |
| UNAUTHORIZED         | 401         | Authentication failed           |
| FORBIDDEN            | 403         | Insufficient permissions        |
| NOT_FOUND            | 404         | Resource not found              |
| JOB_NOT_FOUND        | 404         | Job ID not found                |
| DEPLOYMENT_NOT_FOUND | 404         | Deployment not found            |
| RATE_LIMITED         | 429         | Rate limit exceeded             |
| QUOTA_EXCEEDED       | 429         | Credit quota exceeded           |
| WORKFLOW_ERROR       | 500         | Workflow execution error        |
| NODE_ERROR           | 500         | Specific node error             |
| TIMEOUT              | 504         | Processing timeout              |
| OUT_OF_MEMORY        | 500         | GPU memory exhausted            |
| SERVICE_UNAVAILABLE  | 503         | Service temporarily unavailable |

## Error Response Format

```json
{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "Invalid width value: must be between 512 and 2048",
    "details": {
      "field": "width",
      "provided": 100,
      "constraints": {
        "min": 512,
        "max": 2048,
        "step": 64
      }
    },
    "requestId": "req-xyz789"
  }
}
```

## Rate Limits

| Tier       | Requests/min | Concurrent Jobs | Daily Limit |
| ---------- | ------------ | --------------- | ----------- |
| Free       | 10           | 2               | 50          |
| Basic      | 30           | 5               | 200         |
| Premium    | 100          | 10              | 1000        |
| Enterprise | 500          | 50              | Unlimited   |

Rate limit headers:

```http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1702900800
```

## Webhooks

### Webhook Payload

When job completes, webhook receives:

```json
{
  "event": "job.completed",
  "timestamp": "2024-12-18T12:00:35Z",
  "data": {
    "jobId": "job-abc123def456",
    "status": "COMPLETED",
    "deploymentId": "sacred-mandala-v1",
    "processingTimeMs": 30000,
    "outputs": [
      {
        "type": "image",
        "url": "https://cdn.lilith.ai/outputs/abc123/image_0.png",
        "mimeType": "image/png",
        "sizeBytes": 2456789
      }
    ],
    "metadata": {
      "userId": "user-123"
    }
  }
}
```

### Webhook Events

| Event         | Description                |
| ------------- | -------------------------- |
| job.queued    | Job added to queue         |
| job.started   | Processing began           |
| job.progress  | Progress update (optional) |
| job.completed | Job finished successfully  |
| job.failed    | Job failed                 |
| job.cancelled | Job was cancelled          |

### Webhook Security

Verify webhook signature:

```http
X-Lilith-Signature: sha256=abc123...
X-Lilith-Timestamp: 1702900800
```

```typescript
function verifyWebhook(
  payload: string,
  signature: string,
  timestamp: string
): boolean {
  const expected = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(`${timestamp}.${payload}`)
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(`sha256=${expected}`),
    Buffer.from(signature)
  );
}
```

## SDK Usage

### TypeScript/JavaScript

```typescript
import { LilithComfyUIClient } from '@lilith/sdk';

const client = new LilithComfyUIClient({
  apiKey: process.env.LILITH_API_KEY,
  baseUrl: 'https://api.lilith.ai/v1',
});

// Generate image
const job = await client.generate({
  deploymentId: 'sacred-mandala-v1',
  prompt: 'sacred mandala, golden',
  width: 1024,
  height: 1024,
});

// Wait for completion
const result = await client.waitForCompletion(job.jobId);
console.log(result.outputs[0].url);
```

### Python

```python
from lilith import ComfyUIClient

client = ComfyUIClient(api_key=os.environ['LILITH_API_KEY'])

# Generate image
job = client.generate(
    deployment_id='sacred-mandala-v1',
    prompt='sacred mandala, golden',
    width=1024,
    height=1024
)

# Wait for completion
result = client.wait_for_completion(job.job_id)
print(result.outputs[0].url)
```

## Related Documentation

- [RunComfy API Client](./runcomfy-api-client.md)
- [Workflow Builder](./workflow-builder.md)
- [Deployment Registry](./deployment-registry.md)
- [Troubleshooting Guide](./troubleshooting.md)
