# OpenAI Compatibility Guide

The GoClaw Gateway exposes an OpenAI-compatible interface, allowing it to act as a drop-in proxy for tools like Cursor, Continue.dev, or any library that supports the OpenAI API.

## Endpoints

### `/v1/chat/completions`
**Method:** `POST`

Implements the standard OpenAI Chat Completions API.

**Key Features:**
- **Streaming:** Supports `stream: true` using Server-Sent Events (SSE). Besides the usual `chat.completion.chunk` frames, a stream can carry `data: {"buffer_reset":true}` (the reply is being retried: discard the text received so far) and `data: {"error":{"message":"…"}}`, which ends the stream with no finish chunk and no `data: [DONE]`.
- **Non-Streaming:** Returns a standard JSON response.
- **Message content:** Each message's `content` must be a string. Content sent as an array of parts (text and images) is refused with `400`.
- **Model Routing:** All requests go to the **Default Agent** configured in GoClaw. The `model` parameter is echoed back in the response and does not select an agent or a model. `max_tokens` and `temperature` are read and ignored.
- **Subagent Commands:** A last user message that starts with `/subagents` is a GoClaw subagent command, answered without the model: `/subagents spawn <agent_id> <task>`, `/subagents list`, `/subagents status <run_id>`, `/subagents stop <run_id>`.

**Example Request:**
```bash
curl http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-token" \
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "How many files are in the current directory?"}]
  }'
```

---

### `/v1/models`
**Method:** `GET`

Not implemented: the gateway answers `404`. Use the `default` model or any string, as all traffic goes to the default agent.

---

## Authentication

The gateway token is always required: the gateway does not start without `gateway.auth.token`. Provide it in one of the following ways:

- **Bearer Token:** `Authorization: Bearer <your-token>`
- **Custom Header:** `X-GoClaw-Token: <your-token>`
- **Query Parameter:** `?token=<your-token>` (for browser clients that cannot set a header, such as `EventSource`)
- **Cookie:** the `X-Goclaw-Token` cookie a browser receives from the Web UI's login link

`?auth_code=` is a different thing: a one-time login code the gateway prints at startup, which
exchanges itself for a session cookie. It is not the token.

## Request Handling

When a request is received via the OpenAI compatibility layer:

1. **Agent Selection:** The Gateway uses the **Default Agent**: `agents.default`, else the agent marked `default: true`, else the first agent in `agents.list`, else `main`.
2. **Conversation:** The last `user` message is the prompt; the `system`, `user` and `assistant` messages before it are the conversation history. GoClaw keeps no history for this endpoint: a session `openai-compat:<client-ip>` is created, but nothing is written to it, so send the whole conversation in `messages` on every request.
3. **Provider Logic:** The request is processed by the default agent's provider. When it fails before the reply used a tool (a rate limit, an outage, a bad key), the next provider of `ai.fallback` serves it (see [Provider Fallback](../architecture/provider_fallback.md)). When every provider fails, the error is returned as an OpenAI-style error (`{"error":{"message":…}}`, status `500` when not streaming).
4. **Token Estimation:** Usage stats (`prompt_tokens`, `completion_tokens`) are estimated based on character count (~4 characters per token).

## Usage in IDEs (Cursor/Continue)

To use GoClaw in your IDE:
1. Set the **Base URL** to `http://your-gateway:8080/v1`.
2. Set the **API Key** to your gateway token.
3. Select any model (GoClaw will route to your default configured agent).
