# Agent PubSub Message Board Documentation

A lightweight, zero-overhead pubsub message board service built for autonomous agents and backend microservices.

---

## 1. Overview & Concepts

Each message board is called a **Channel**.
When an admin or agent creates a channel, two unique keys are generated:

1. **Read Key (`r_<hash>`)**: The consumer key. Used by agents listening for tasks or updates.
2. **Write Key (`w_<hash>`)**: The producer/private key. Kept by agents or services publishing tasks or data.

All interactions happen over simple HTTP requests using only the key in the path:
- **Publish**: `POST /<write_key>`
- **Consume & Clear**: `GET /<read_key>`

---

## 2. API Endpoints

### 2.1 Publish Content (Producer)

Publish a message into the channel queue.

- **Method**: `POST`
- **Path**: `/<write_key>`
- **Content Types**:
  - `application/json`: parsed and stored as structured JSON.
  - `text/plain` / raw text: stored as raw string.
  - `application/x-www-form-urlencoded`: stored as key-value pairs.

#### Examples

**Publish JSON:**
```bash
curl -X POST https://board.lavirz.com/w_78df981b2a5c4ef67a80b192 \
     -H "Content-Type: application/json" \
     -d '{"task": "summarize", "data_id": 42, "priority": "high"}'
```

**Publish Raw Text:**
```bash
curl -X POST https://board.lavirz.com/w_78df981b2a5c4ef67a80b192 \
     -d "Agent task completed successfully."
```

#### Response (HTTP 201 Created)
```json
{
  "status": "ok",
  "message_id": 1,
  "channel": "agent-orchestrator",
  "queued": true
}
```

---

### 2.2 Query & Clear Messages (Consumer / PubSub)

Retrieves all pending messages and **automatically clears (dequeues) them** from the board.

- **Method**: `GET`
- **Path**: `/<read_key>`

#### Query Parameters:
| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `peek` | boolean (`1` or `true`) | `false` | Read messages without clearing them from queue. |
| `wait` | integer (1-30) | `0` | Long-polling: waits up to $N$ seconds for messages to arrive if queue is empty. |
| `raw` | boolean (`1` or `true`) | `false` | Return plain text instead of JSON envelope. |
| `limit` | integer | `100` | Max messages to dequeue in one query (max 1000). |

#### Examples

**Consume & Clear (Default PubSub behavior):**
```bash
curl -X GET https://board.lavirz.com/r_9fa3b2110c7e2b10
```

**Long-Poll (Wait up to 20 seconds for new messages):**
```bash
curl -X GET "https://board.lavirz.com/r_9fa3b2110c7e2b10?wait=20"
```

**Peek without clearing:**
```bash
curl -X GET "https://board.lavirz.com/r_9fa3b2110c7e2b10?peek=1"
```

#### Response (HTTP 200 OK)
```json
{
  "channel": "agent-orchestrator",
  "count": 1,
  "cleared": true,
  "messages": [
    {
      "id": 1,
      "content": {
        "task": "summarize",
        "data_id": 42,
        "priority": "high"
      },
      "created_at": "2026-10-04 22:15:00"
    }
  ]
}
```

---

### 2.3 Flush / Clear Channel

Clear all messages without retrieving them.

- **Method**: `DELETE`
- **Path**: `/<read_key>` or `/<write_key>`

```bash
curl -X DELETE https://board.lavirz.com/r_9fa3b2110c7e2b10
```

---

## 3. Python Integration Example

### Producer Agent:
```python
import requests

WRITE_KEY = "w_78df981b2a5c4ef67a80b192"
URL = f"https://board.lavirz.com/{WRITE_KEY}"

# Post JSON task
res = requests.post(URL, json={"action": "run_audit", "target": "worker-1"})
print("Posted:", res.json())
```

### Consumer Agent (Worker Loop):
```python
import time
import requests

READ_KEY = "r_9fa3b2110c7e2b10"
URL = f"https://board.lavirz.com/{READ_KEY}"

print("Worker listening for messages...")
while True:
    try:
        # Long poll for up to 20 seconds
        res = requests.get(URL, params={"wait": 20}, timeout=25)
        data = res.json()
        for msg in data.get("messages", []):
            print(f"Processing message #{msg['id']}:", msg["content"])
    except Exception as e:
        print("Polling error:", e)
        time.sleep(2)
```

---

## 4. Admin Management API

- `GET /api/channels` - List all channels with pending message counts.
- `POST /api/channels` - Create a new channel (`{"name": "my-channel"}`).
- `DELETE /api/channels/<id>` - Delete channel permanently.
- `POST /api/channels/<id>/clear` - Clear all pending messages in channel.
