# Comentu (啃馒头) v2 — Agent Integration Guide

## Overview

Comentu v2 API is designed for both human users and AI Agents (AutoGPT, CrewAI, LangGraph, etc.).
This guide covers authentication, typical workflows, batch operations, error handling, and webhook configuration.

---

## Authentication

Comentu supports two authentication methods. All protected endpoints accept either method.

### 1. JWT Token (for interactive sessions)

```
POST /api/v2/auth/login
Content-Type: application/json

{ "email": "user@example.com", "password": "secret123" }
```

Response:
```json
{ "token": "eyJhbGciOiJIUzI1NiJ9...", "clientId": "client-123" }
```

Use the token in subsequent requests:
```
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
```

### 2. API Key (recommended for Agents)

API Keys are long-lived and don't require a login flow. Pass the key via header:

```
X-API-Key: ck_live_a1b2c3d4e5f6...
```

API Keys use the format `ck_live_<hex>` for production or `ck_test_<hex>` for testing.

---

## Typical Agent Workflow

```
1. Authenticate (API Key recommended)
2. Create tasks (single or batch)
3. Register webhook for event notifications
4. Wait for preview_ready event
5. Confirm previews (single or batch, with autoConfirm)
6. Wait for send_verified event
7. Query final results (single or batch)
```

### Step-by-step Example

#### 1. Batch Create Tasks

```
POST /api/v2/tasks/batch
X-API-Key: ck_live_a1b2c3d4...
Content-Type: application/json

{
  "tasks": [
    { "platform": "bilibili", "videoUrl": "https://bilibili.com/video/BV1xx", "interactionType": "comment" },
    { "platform": "xiaohongshu", "videoUrl": "https://xiaohongshu.com/note/123", "interactionType": "comment" }
  ]
}
```

Response:
```json
{
  "results": [
    { "index": 0, "success": true, "taskId": "task-001" },
    { "index": 1, "success": true, "taskId": "task-002" }
  ],
  "totalSucceeded": 2,
  "totalFailed": 0
}
```

#### 2. Register Webhook

```
POST /api/v2/webhooks
X-API-Key: ck_live_a1b2c3d4...
Content-Type: application/json

{
  "url": "https://your-agent.example.com/webhook",
  "events": ["task:status_changed", "task:preview_ready", "task:send_verified"],
  "secret": "your-webhook-secret"
}
```

#### 3. Batch Confirm Previews

When you receive `task:preview_ready` events via webhook:

```
POST /api/v2/preview/batch-confirm
X-API-Key: ck_live_a1b2c3d4...
Content-Type: application/json

{
  "sessionIds": ["session-001", "session-002"],
  "autoConfirm": true
}
```

#### 4. Batch Query Status

```
POST /api/v2/tasks/batch-status
X-API-Key: ck_live_a1b2c3d4...
Content-Type: application/json

{
  "taskIds": ["task-001", "task-002"]
}
```

---

## Error Handling

All API errors return structured JSON:

```json
{
  "code": "VALIDATION_ERROR",
  "message": "Missing required fields: platform",
  "details": [{ "field": "platform", "message": "platform is required" }]
}
```

### Error Codes

| Code | HTTP Status | Action |
|------|-------------|--------|
| VALIDATION_ERROR | 400 | Fix request parameters and retry |
| UNAUTHORIZED | 401 | Check API key or JWT token |
| FORBIDDEN | 403 | Insufficient permissions |
| NOT_FOUND | 404 | Check resource ID |
| RATE_LIMITED | 429 | Wait until X-RateLimit-Reset and retry |
| INTERNAL_ERROR | 500 | Retry with exponential backoff |

### Rate Limiting

All responses include rate limit headers:

```
X-RateLimit-Remaining: 55
X-RateLimit-Reset: 2024-01-01T00:01:00.000Z
```

When `X-RateLimit-Remaining` reaches 0, wait until `X-RateLimit-Reset` before making more requests.

---

## Webhook Events

Webhook payloads are signed with HMAC-SHA256. Verify the signature using the `X-Webhook-Signature` header:

```
signature = HMAC-SHA256(payload_body, your_secret)
```

### Event Types

| Event | Description |
|-------|-------------|
| task:status_changed | Task status updated |
| task:preview_ready | Content preview is ready for confirmation |
| task:send_verified | Send verification completed |
| account:health_alert | Account health score below threshold |

### Webhook Payload Example

```json
{
  "type": "task:status_changed",
  "data": {
    "taskId": "task-001",
    "oldStatus": "previewing",
    "newStatus": "confirmed"
  },
  "timestamp": "2024-01-01T00:00:00.000Z"
}
```

---

## Batch Operations

Batch endpoints process each item independently. Partial failures do not affect other items.

| Endpoint | Method | Description |
|----------|--------|-------------|
| /api/v2/tasks/batch | POST | Batch create tasks |
| /api/v2/tasks/batch-status | POST | Batch query task status |
| /api/v2/preview/batch-confirm | POST | Batch confirm previews |

---

## MCP Integration

For MCP-compatible agents (Claude, Cursor), use the MCP tool definition:

```
GET /api/v2/mcp-tools.json
```

## OpenAPI Spec

Full API specification in OpenAPI 3.0 format:

```
GET /api/v2/openapi.json
```
