# Kairos API Reference

The Kairos API is a production-hosted service. This documentation matches the live codebase in `backend/` and explains the supported authentication methods, common endpoints, and recommended request patterns for third-party developers.

IMPORTANT: the API is only accessible at the hosted endpoint — you cannot run or access the same API locally for third-party integrations. Point all requests to the production Base URL and obtain tokens via the flows below.

Base URL (production):

```
https://kairosapp.co/api
```

## Authentication

- Preferred: Bearer access tokens sent in the `Authorization` header.
  - Header: `Authorization: Bearer <ACCESS_TOKEN>`
  - The backend resolves users from bearer tokens and falls back to legacy `uid`+`auth` checks for some endpoints.
- Device Authorization and OAuth provider flows are supported to obtain user-scoped tokens (see "Authentication flows").
- Compatibility: Some legacy endpoints accept `uid` and `auth` in the JSON body. For widest compatibility include both the `Authorization` header and `uid` when applicable.

## Error handling

All responses are JSON. On error the API returns an HTTP status code (400, 401, 403, 404, 500) and a body with an `error` key, for example:

```
HTTP/1.1 401 Unauthorized
Content-Type: application/json

{ "error": "Invalid Token" }
```

## Authentication flows

### 1) Device Authorization Flow (recommended for headless clients)

Start device flow:

```
POST https://kairosapp.co/api/auth/device/init
Content-Type: application/json
{ "client_name": "My CLI" }
```

You will receive a `device_code` / `user_code` pair and a `verification_uri` where the end user authorizes the device.

Poll the device token endpoint until approval:

```
POST https://kairosapp.co/api/auth/device/poll
Content-Type: application/json
{ "device_code": "..." }
```

On success the poll returns `{ "uid": <id>, "auth": "<ACCESS_TOKEN>", "token_type": "bearer" }`.

### 2) OAuth provider login / provider exchanges

- Redirect users to `/api/auth/<provider>/login` (server performs provider redirect).
- To store provider tokens for a user the server supports both server-side exchange (`POST /api/auth/<provider>/exchange` with a `Bearer <USER_TOKEN>`) and a frontend-compatible exchange (`POST /api/oauth/exchange` with `uid` + `auth`).

### 3) Token refresh

Refresh flows are provider-specific and handled by the backend's OAuth managers. Contact support for service-account or extended refresh behavior.

## Calling the API (recommended patterns)

- Always prefer `Authorization: Bearer <ACCESS_TOKEN>`.
- If an endpoint requires a `uid` in the body (many task/notes and legacy endpoints do), include `uid` in the request payload even when using `Authorization`.
- Respect production rate limits (applied per token/user). Contact support@kairosapp.co for quota increases.

## Selected endpoints

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/addTask` | Create tasks for a user |
| POST | `/api/updateEvent` | Update task/event fields |
| POST | `/api/latestTasks` | Fetch latest tasks |
| POST | `/api/refreshSchedule` | Refresh a user's schedule |
| POST | `/api/readTask` | Read tasks |
| POST | `/api/getNotifications` | Fetch notifications |
| POST | `/api/workflows/<workflow_id>/run` | Manually trigger a workflow |
| GET | `/api/spr/processes` | List SPR processes |
| POST | `/api/spr/run/<id>` | Run an SPR process |
| POST | `/api/spr/shared-notes-runner/execute` | SPR shared-notes operations (write requires proper tier) |

The live backend supports both modern bearer tokens and legacy `uid`/`auth` checks; including both is the most compatible pattern.

For provider integrations (Google, Jira, Trello, Proton, Slack, GitHub) follow the OAuth/device flows above; provider tokens are persisted on the user account after exchange.

## Request / response examples

Replace `ACCESS_TOKEN`, `uid`, and ids with real values from your integration.

### 1) Add tasks — `POST /api/addTask`

Request:

```
POST https://kairosapp.co/api/addTask
Headers: { "Authorization": "Bearer <ACCESS_TOKEN>", "Content-Type": "application/json" }
Body:
{
  "uid": 123,
  "tasks": "Prepare slides for meeting; Email Alice; Buy milk"
}
```

Response (201/200):

```json
{
  "tasks": [
    { "id": 987, "task_name": "Prepare slides for meeting", "created_at": "2026-01-25T12:00:00Z", "status": "open" },
    { "id": 988, "task_name": "Email Alice", "created_at": "2026-01-25T12:00:01Z", "status": "open" }
  ]
}
```

Curl:

```bash
curl -X POST "https://kairosapp.co/api/addTask" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"uid":123, "tasks":"Buy milk; Email Bob"}'
```

Python:

```python
import requests
resp = requests.post(
    "https://kairosapp.co/api/addTask",
    json={"uid": 123, "tasks": "Buy milk"},
    headers={"Authorization": f"Bearer {ACCESS_TOKEN}"},
)
print(resp.json())
```

Node / fetch:

```js
await fetch('https://kairosapp.co/api/addTask', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ACCESS_TOKEN}` },
  body: JSON.stringify({ uid: 123, tasks: 'Buy milk' })
});
```

### 2) Update / complete a task — `POST /api/updateEvent`

Request:

```json
{
  "uid": 123,
  "id": 987,
  "updates": { "status": "completed", "completed_at": "2026-01-25T15:30:00Z" }
}
```

Response:

```json
{
  "success": true,
  "updated": { "id": 987, "status": "completed", "completed_at": "2026-01-25T15:30:00Z" }
}
```

### 3) Manual workflow trigger — `POST /api/workflows/<workflow_id>/run`

Request:

```json
{
  "payload": { "report_name": "weekly_summary", "params": { "days": 7 } }
}
```

Response:

```json
{ "success": true, "message": "Workflow run initiated" }
```

### 4) Device auth (init + poll)

Init response:

```json
{
  "device_code": "abc123",
  "user_code": "ABCD-1234",
  "verification_uri": "https://kairosapp.co/device",
  "expires_in": 900,
  "interval": 5
}
```

Poll success response:

```json
{
  "uid": 123,
  "auth": "<ACCESS_TOKEN>",
  "token_type": "bearer",
  "expires_in": 3600
}
```

### 5) Latest tasks — `POST /api/latestTasks`

Request:

```json
{ "user_id": 123, "amount": 5 }
```

Response:

```json
{
  "tasks": [
    { "task_name": "Buy milk", "time_utc": "2026-01-25T16:00:00Z", "user_tz": "America/New_York", "priority": 2 },
    { "task_name": "Call Alice", "time_utc": "2026-01-25T18:00:00Z", "user_tz": "America/New_York", "priority": 1 }
  ]
}
```

### 6) SPR shared-notes (premium) — `POST /api/spr/shared-notes-runner/execute`

Request:

```json
{
  "operation": "write",
  "user_id": 123,
  "user_tier": "pro",
  "data": [ { "title": "Meeting notes", "content": "Discuss Q1 roadmap" } ]
}
```

Response (success):

```json
{
  "status": "success",
  "usage_info": { "units_used": 12, "units_remaining": 988 }
}
```
