# API.

> Read and drive Koidog from your own programs.
> https://koi.dog/docs/api/

## Base URL.

It is served by the control plane you sign in to.

```text
https://app.koi.dog/api/v1
```

## Authentication.

Create an API key in Settings → API. Its token is shown once. Send it on every request. A key holds only the scopes you give it; an endpoint lists every scope it needs.

| Scope | Lets the key |
| --- | --- |
| `read` | Read crews, agents, runs, events and everything else. |
| `crews` | Launch and control crews. |
| `config` | Change projects, connections, nodes, settings and webhooks. |
| `approve` | Merge, decide approvals, raise budget limits and do destructive things. |

```text
Authorization: Bearer <key>
```

## Events.

Follow the timeline live as server-sent events. It takes the same filters as `GET /events`. Reconnect with `Last-Event-ID` to replay what you missed, in order. A key may hold 8 streams at once.

```text
GET /api/v1/events/stream?crewId=<crewId>

id: 1842
event: event
data: {"seq":1842,"kind":"crew.state","crewId":"<crewId>",…}
```

## Webhooks.

Koidog POSTs matching events to your https endpoint, signed with the endpoint's secret. The secret is shown once.

| Header | What it holds |
| --- | --- |
| `Koidog-Timestamp` | When the delivery was signed, in Unix seconds. |
| `Koidog-Signature` | `v1=` and the hex HMAC-SHA256 of the timestamp, a dot and the raw body. |
| `Koidog-Delivery-Id` | The same across retries. |
| `Koidog-Webhook-Id` | The endpoint's id. |
| `Koidog-Attempt` | 1 on the first try, then 2, 3 and on. |
| `User-Agent` | `Koidog-Webhooks/1` |
| `Content-Type` | `application/json`. The body holds the delivery: its `id`, `type`, `createdAt` and the timeline `event`. |

Check the signature and refuse old timestamps; the code beside this does both. Answer any 2xx within 10 seconds; anything else is retried for about 21 hours. Koidog switches an endpoint off after 50 failed attempts in a row, or when every attempt has failed for 24 hours, and records a `webhook.disabled` event.

```js
import { createHmac, timingSafeEqual } from "node:crypto";

// secret: the endpoint's secret. rawBody: the body exactly as it arrived, as a string.
export function verifyKoidog(secret, headers, rawBody) {
  const timestamp = headers["koidog-timestamp"];
  const signature = headers["koidog-signature"] ?? "";
  // Refuse a delivery signed more than five minutes ago.
  if (!timestamp || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
  const expected = "v1=" + createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex");
  return signature.length === expected.length && timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}
```

```python
import hashlib
import hmac
import time

# secret: the endpoint's secret. raw_body: the body exactly as it arrived, as bytes.
def verify_koidog(secret: str, headers, raw_body: bytes) -> bool:
    timestamp = headers.get("Koidog-Timestamp", "")
    signature = headers.get("Koidog-Signature", "")
    # Refuse a delivery signed more than five minutes ago.
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300:
        return False
    signed = timestamp.encode() + b"." + raw_body
    expected = "v1=" + hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature, expected)
```

## OpenAPI.

OpenAPI 3.1, made from the schemas the server checks with. No key needed.

```text
GET /api/v1/openapi.json
```

## Errors.

Every error has this shape. Branch on `type`; `code` is the stable reason. `details` lists each problem when there is more than one.

Types: `invalid_request`, `authentication`, `permission`, `not_found`, `conflict`, `rate_limited`, `not_built`, `upstream`, `internal`.

```json
{
  "error": {
    "type": "authentication",
    "code": "invalid_api_key",
    "message": "That API key is not known to this server.",
    "requestId": "req_q8M2x7C4k9TzWb3n"
  }
}
```

```json
{
  "error": {
    "type": "conflict",
    "code": "launch_blocked",
    "message": "Project \"Landing page\" is archived. Unarchive it to launch a crew on it.",
    "requestId": "req_q8M2x7C4k9TzWb3n",
    "details": [
      {
        "message": "Project \"Landing page\" is archived. Unarchive it to launch a crew on it."
      }
    ]
  }
}
```
